提交 5e514bda 编写于 作者: LinuxSuRen's avatar LinuxSuRen

Add search as sub-cmd

上级 ff4a4ea9
package cmd
import (
"github.com/spf13/cobra"
)
type JobOption struct {
OutputOption
}
var jobOption JobOption
func init() {
rootCmd.AddCommand(jobCmd)
jobCmd.PersistentFlags().StringVarP(&queueOption.Format, "output", "o", "json", "Format the output")
}
var jobCmd = &cobra.Command{
Use: "job",
Short: "Print the job of your Jenkins",
Long: `Print the job of your Jenkins`,
Run: func(cmd *cobra.Command, args []string) {
},
}
package cmd
import (
"fmt"
"log"
"github.com/linuxsuren/jenkins-cli/client"
"github.com/spf13/cobra"
)
type JobSearchOption struct {
OutputOption
}
var jobSearchOption JobSearchOption
func init() {
jobCmd.AddCommand(jobSearchCmd)
jobSearchCmd.PersistentFlags().StringVarP(&queueOption.Format, "output", "o", "json", "Format the output")
}
var jobSearchCmd = &cobra.Command{
Use: "search",
Short: "Print the job of your Jenkins",
Long: `Print the job of your Jenkins`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
log.Fatal("need a keyword")
}
keyword := args[0]
jenkins := getCurrentJenkins()
jclient := &client.JobClient{}
jclient.URL = jenkins.URL
jclient.UserName = jenkins.UserName
jclient.Token = jenkins.Token
jclient.Proxy = jenkins.Proxy
jclient.ProxyAuth = jenkins.ProxyAuth
if status, err := jclient.Search(keyword); err == nil {
var data []byte
if data, err = Format(status, queueOption.Format); err == nil {
fmt.Printf("%s\n", string(data))
} else {
log.Fatal(err)
}
} else {
log.Fatal(err)
}
},
}
package client
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type JobClient struct {
JenkinsCore
}
// Search find a set of jobs by name
func (q *JobClient) Search(keyword string) (status *SearchResult, err error) {
api := fmt.Sprintf("%s/search/suggest?query=%s", q.URL, keyword)
var (
req *http.Request
response *http.Response
)
req, err = http.NewRequest("GET", api, nil)
if err == nil {
q.AuthHandle(req)
} else {
return
}
client := q.GetClient()
if response, err = client.Do(req); err == nil {
code := response.StatusCode
var data []byte
data, err = ioutil.ReadAll(response.Body)
if code == 200 {
if err == nil {
status = &SearchResult{}
err = json.Unmarshal(data, status)
}
} else {
log.Fatal(string(data))
}
} else {
log.Fatal(err)
}
return
}
type SearchResult struct {
Suggestions []SearchResultItem
}
type SearchResultItem struct {
Name string
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册