提交 1e4f543a 编写于 作者: LinuxSuRen's avatar LinuxSuRen

Add user cmd

上级 c7ea09d5
......@@ -35,3 +35,4 @@ dep: ## Clean the generated artifacts
go get github.com/spf13/cobra
go get github.com/spf13/viper
go get gopkg.in/yaml.v2
go get github.com/Pallinder/go-randomdata
package cmd
import (
"fmt"
"log"
"github.com/linuxsuren/jenkins-cli/client"
"github.com/spf13/cobra"
)
type UserOption struct {
OutputOption
}
var userOption UserOption
func init() {
rootCmd.AddCommand(userCmd)
userCmd.Flags().StringVarP(&userOption.Format, "output", "o", "json", "Format the output")
}
var userCmd = &cobra.Command{
Use: "user",
Short: "Print the user of your Jenkins",
Long: `Print the user of your Jenkins`,
Run: func(cmd *cobra.Command, args []string) {
jenkins := getCurrentJenkins()
jclient := &client.UserClient{}
jclient.URL = jenkins.URL
jclient.UserName = jenkins.UserName
jclient.Token = jenkins.Token
jclient.Proxy = jenkins.Proxy
jclient.ProxyAuth = jenkins.ProxyAuth
var tokenName string
if len(args) > 0 {
tokenName = args[0]
}
if status, err := jclient.Create(tokenName); err == nil {
var data []byte
if data, err = userOption.Output(status); 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"
"net/url"
"strings"
"github.com/Pallinder/go-randomdata"
)
type UserClient struct {
JenkinsCore
}
type Token struct {
Status string
Data TokenData
}
type TokenData struct {
TokenName string
TokenUuid string
TokenValue string
}
func (q *UserClient) Create(newTokenName string) (status *Token, err error) {
if newTokenName == "" {
newTokenName = fmt.Sprintf("jcli-%s", randomdata.SillyName())
}
api := fmt.Sprintf("%s/user/%s/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken", q.URL, q.UserName)
var (
req *http.Request
response *http.Response
)
formData := url.Values{}
formData.Add("newTokenName", newTokenName)
payload := strings.NewReader(formData.Encode())
req, err = http.NewRequest("POST", api, payload)
if err == nil {
q.AuthHandle(req)
} else {
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if err = q.CrumbHandle(req); err != nil {
log.Fatal(err)
}
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 = &Token{}
err = json.Unmarshal(data, status)
}
} else {
log.Fatal(string(data))
}
} else {
log.Fatal(err)
}
return
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册