Skip to content

Commit c926d60

Browse files
authored
feat: add job trigger and get log ouput (jenkins-zh#771)
* feat:add log print function with exit code ass log ptint func Log: Change-Id: I46cb977e39e8c00b794376c70a88384bd555e223 * feat: add job build and wait log with exit code add job build and wait log with exit code and fix test error Log: Change-Id: I8ae90c8649cbbb817e339119f75db54caa6fd0e3
1 parent bd33a1b commit c926d60

22 files changed

+398
-93
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
# Output of the go coverage tool, specifically when used with LiteIDE
1212
*.out
1313

14-
bin/
14+
bin/**/jcli
1515
release/
1616
jcli
1717

.jenkins-cli.yaml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
current: test
2+
jenkins_servers:
3+
- name: yourServer
4+
url: http://localhost:8080/jenkins
5+
username: test
6+
token: 211e3a2f0231198856dceaff96f2v75ce3
7+
insecureSkipVerify: true
8+
#mirrors:
9+
#- name: default
10+
# url: http://mirrors.jenkins.io/
11+
# Language context is accept-language for HTTP header, It contains zh-CN/zh-TW/en/en-US/ja and so on
12+
# Goto 'http://localhost:8080/jenkins/me/configure', then you can generate your token.

Dockerfile

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ COPY . .
55
RUN CGO_ENABLED=0 go build -v -a -o jcli .
66

77
FROM alpine:3.10
8-
COPY --from=builder /work/jcli /usr/bin/jcli
8+
ENV JOB_NAME "test"
9+
COPY --from=builder /work/bin/linux/jcli /usr/bin/jcli
910
RUN jcli config generate -i=false > ~/.jenkins-cli.yaml
11+
COPY bin/build.sh /usr/bin/jclih
12+
RUN chmod +x /usr/bin/jclih
1013

11-
ENTRYPOINT ["jcli"]
14+
ENTRYPOINT ["jclih"]

app/cmd/backup.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import (
1111
"github.com/spf13/cobra"
1212
)
1313

14-
//BackupOption is an option for backup
14+
// BackupOption is an option for backup
1515
type BackupOption struct {
1616
RoundTripper http.RoundTripper
1717
BackupDir string
@@ -38,7 +38,7 @@ var backupCmd = &cobra.Command{
3838
RunE: backupOption.Backup,
3939
}
4040

41-
//Check will find out whether Thin Backup Plugin installed or not
41+
// Check will find out whether Thin Backup Plugin installed or not
4242
func (o *BackupOption) Check() (err error) {
4343
opt := PluginOptions{
4444
Option: common.Option{RoundTripper: o.RoundTripper},
@@ -47,7 +47,7 @@ func (o *BackupOption) Check() (err error) {
4747
return
4848
}
4949

50-
//Backup will trigger thinBackup plugin to make a backup
50+
// Backup will trigger thinBackup plugin to make a backup
5151
func (o *BackupOption) Backup(cmd *cobra.Command, _ []string) (err error) {
5252
jClient := &client.CoreClient{
5353
JenkinsCore: client.JenkinsCore{
@@ -88,7 +88,7 @@ func (o *BackupOption) Backup(cmd *cobra.Command, _ []string) (err error) {
8888
return
8989
}
9090

91-
//ThinBackupAPI requests backupManual api
91+
// ThinBackupAPI requests backupManual api
9292
func ThinBackupAPI(client *client.CoreClient) (err error) {
9393
_, err = client.RequestWithoutData(http.MethodGet, "/thinBackup/backupManual", nil, nil, 200)
9494
return err

app/cmd/center_list.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,31 +14,31 @@ import (
1414
"github.com/spf13/cobra"
1515
)
1616

17-
//LtsURL is the URL of stable Jenkins RSS
17+
// LtsURL is the URL of stable Jenkins RSS
1818
const LtsURL = "https://www.jenkins.io/changelog-stable/rss.xml"
1919

20-
//WidthOfDescription is the width of the description column
20+
// WidthOfDescription is the width of the description column
2121
const WidthOfDescription = 60
2222

23-
//ASCIIOfLineFeed is the ASCII of line feed
23+
// ASCIIOfLineFeed is the ASCII of line feed
2424
const ASCIIOfLineFeed = 10
2525

26-
//ASCIIOfSpace is the ASCII of space
26+
// ASCIIOfSpace is the ASCII of space
2727
const ASCIIOfSpace = 32
2828

29-
//CenterListOption as options for Jenkins RSS
29+
// CenterListOption as options for Jenkins RSS
3030
type CenterListOption struct {
3131
Channel Channel `xml:"channel"`
3232
// RoundTripper http.RoundTripper
3333
}
3434

35-
//Channel as part of CenterListOption
35+
// Channel as part of CenterListOption
3636
type Channel struct {
3737
Title string `xml:"title"`
3838
Items []Item `xml:"item"`
3939
}
4040

41-
//Item as a option for information of newly-released Jenkins
41+
// Item as a option for information of newly-released Jenkins
4242
type Item struct {
4343
Title string `xml:"title"`
4444
Description string `xml:"description"`

app/cmd/common/plugin.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package common
22

33
import "fmt"
44

5-
//GetJCLIPluginPath returns the path of a jcli plugin
5+
// GetJCLIPluginPath returns the path of a jcli plugin
66
func GetJCLIPluginPath(userHome, name string, binary bool) string {
77
suffix := ".yaml"
88
if binary {

app/cmd/condition/plugin_dep.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ type PluginDepCheck struct {
1414
pluginName, targetVersion string
1515
}
1616

17-
//NewChecker returns a plugin dep checker
17+
// NewChecker returns a plugin dep checker
1818
func NewChecker(jenkins *appCfg.JenkinsServer, roundTripper http.RoundTripper, pluginName, targetVersion string) (
1919
checker *PluginDepCheck) {
2020
checker = &PluginDepCheck{

app/cmd/job_build.go

Lines changed: 45 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"fmt"
66
"strings"
7+
"time"
78

89
"github.com/jenkins-zh/jenkins-cli/app/cmd/common"
910
"github.com/jenkins-zh/jenkins-cli/app/i18n"
@@ -18,15 +19,18 @@ type JobBuildOption struct {
1819
common.Option
1920
cobra_ext.OutputOption
2021

21-
Param string
22-
ParamArray []string
22+
Param string
23+
ParamArray []string
24+
ParamJsonString string
2325

2426
ParamFilePathArray []string
2527

26-
Wait bool
27-
WaitTime int
28-
Delay int
29-
Cause string
28+
Wait bool
29+
WaitTime int
30+
WaitInterval int
31+
Delay int
32+
Cause string
33+
LogConsole bool
3034
}
3135

3236
var jobBuildOption JobBuildOption
@@ -40,23 +44,28 @@ func init() {
4044
jobCmd.AddCommand(jobBuildCmd)
4145
jobBuildCmd.Flags().BoolVarP(&jobBuildOption.Batch, "batch", "b", false, "Batch mode, no need confirm")
4246
jobBuildCmd.Flags().StringVarP(&jobBuildOption.Param, "param", "", "",
43-
i18n.T("Parameters of the job which is JSON format"))
47+
i18n.T("Parameters of the job which is JSON format, for example: --param '{\"limit\":\"2\",\"timeoutLimit\":\"10\"}'"))
4448
jobBuildCmd.Flags().StringArrayVar(&jobBuildOption.ParamArray, "param-entry", nil,
45-
i18n.T("Parameters of the job which are the entry format, for example: --param-entry name=value"))
49+
i18n.T("Parameters of the job which are the entry format, for example: --param-entry name1=value1, --param-entry name2=value2"))
4650
jobBuildCmd.Flags().StringArrayVar(&jobBuildOption.ParamFilePathArray, "param-file", nil,
4751
i18n.T("Parameters of the job which is file path, for example: --param-file name=filename"))
4852
jobBuildCmd.Flags().BoolVarP(&jobBuildOption.Wait, "wait", "", false,
4953
i18n.T("If you want to wait for the build ID from Jenkins. You need to install plugin pipeline-restful-api first"))
50-
jobBuildCmd.Flags().IntVarP(&jobBuildOption.WaitTime, "wait-timeout", "", 30,
54+
jobBuildCmd.Flags().IntVarP(&jobBuildOption.WaitTime, "wait-timeout", "", 60,
5155
i18n.T("The timeout of seconds when you wait for the build ID"))
56+
jobBuildCmd.Flags().IntVarP(&jobBuildOption.WaitInterval, "wait-interval", "", 10,
57+
i18n.T("The interval of seconds when you want to wait for buildID... query, use with wait"))
5258
jobBuildCmd.Flags().IntVarP(&jobBuildOption.Delay, "delay", "", 0,
5359
i18n.T("Delay when trigger a Jenkins job"))
5460
jobBuildCmd.Flags().StringVarP(&jobBuildOption.Cause, "cause", "", "triggered by jcli",
5561
i18n.T("The cause of a job build"))
62+
jobBuildCmd.Flags().BoolVarP(&jobBuildOption.LogConsole, "log", "l", false,
63+
i18n.T("If you want to wait for build log and wait log output end"))
5664

5765
jobBuildOption.SetFlagWithHeaders(jobBuildCmd, "Number,URL")
5866
jobBuildOption.BatchOption.Stdio = common.GetSystemStdio()
5967
jobBuildOption.Option.Stdio = common.GetSystemStdio()
68+
6069
}
6170

6271
var jobBuildCmd = &cobra.Command{
@@ -66,15 +75,28 @@ var jobBuildCmd = &cobra.Command{
6675
You need to give the parameters if your pipeline has them. Learn more about it from https://jenkins.io/doc/book/pipeline/syntax/#parameters.`),
6776
Args: cobra.MinimumNArgs(1),
6877
PreRunE: func(_ *cobra.Command, _ []string) (err error) {
69-
if jobBuildOption.ParamArray == nil && jobBuildOption.ParamFilePathArray == nil {
78+
if jobBuildOption.ParamArray == nil && jobBuildOption.ParamFilePathArray == nil && jobBuildOption.Param == "" {
7079
return
7180
}
7281

7382
paramDefs := make([]client.ParameterDefinition, 0)
7483
if jobBuildOption.Param != "" {
75-
if err = json.Unmarshal([]byte(jobBuildOption.Param), &paramDefs); err != nil {
84+
paramMap := make(map[string]interface{})
85+
if err = json.Unmarshal([]byte(jobBuildOption.Param), &paramMap); err != nil {
86+
logger.Error(fmt.Sprintf("build param unmarshal error %v", err.Error()))
7687
return
7788
}
89+
for key, value := range paramMap {
90+
if key == "" || value == nil {
91+
logger.Error("build param key or value empty")
92+
return
93+
}
94+
paramDefs = append(paramDefs, client.ParameterDefinition{
95+
Name: key,
96+
Value: fmt.Sprintf("%v", value),
97+
Type: client.StringParameterDefinition,
98+
})
99+
}
78100
}
79101

80102
for _, paramEntry := range jobBuildOption.ParamArray {
@@ -113,6 +135,7 @@ You need to give the parameters if your pipeline has them. Learn more about it f
113135
jclient := &client.JobClient{
114136
JenkinsCore: client.JenkinsCore{
115137
RoundTripper: jobBuildOption.RoundTripper,
138+
Timeout: time.Duration(jobBuildOption.WaitTime) * time.Second,
116139
},
117140
}
118141
getCurrentJenkinsAndClient(&(jclient.JenkinsCore))
@@ -150,13 +173,18 @@ You need to give the parameters if your pipeline has them. Learn more about it f
150173
}
151174

152175
if err == nil {
176+
options := client.JobCmdOptionsCommon{
177+
Wait: jobBuildOption.Wait,
178+
WaitTime: jobBuildOption.WaitTime,
179+
WaitInterval: jobBuildOption.WaitInterval,
180+
LogConsole: jobBuildOption.LogConsole,
181+
}
182+
153183
if hasParam {
154-
err = jclient.BuildWithParams(name, paramDefs)
155-
} else if jobBuildOption.Wait {
156-
var build client.IdentityBuild
157-
if build, err = jclient.BuildAndReturn(name, jobBuildOption.Cause, jobBuildOption.WaitTime, jobBuildOption.Delay); err == nil {
158-
jobBuildOption.Writer = cmd.OutOrStdout()
159-
err = jobBuildOption.OutputV2([1]client.SimpleJobBuild{build.Build.SimpleJobBuild})
184+
var jobState client.JenkinsBuildState
185+
jobState, err = jclient.BuildWithParamsGetResponse(name, paramDefs, options)
186+
if err == nil && jobBuildOption.LogConsole && jobState.RunId > 0 {
187+
err = printLogRunFunc(name, JobLogOptionGetDefault(int(jobState.RunId)), cmd)
160188
}
161189
} else {
162190
err = jclient.Build(name)

app/cmd/job_delete_test.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import (
1313

1414
"github.com/AlecAivazis/survey/v2/terminal"
1515
"github.com/golang/mock/gomock"
16-
"github.com/hinshun/vt10x"
1716
. "github.com/onsi/ginkgo"
1817
. "github.com/onsi/gomega"
1918
"github.com/stretchr/testify/require"
@@ -180,9 +179,9 @@ func RunTest(t *testing.T, test func(terminal.Stdio) error, procedures ...func(*
180179
// Multiplex output to a buffer as well for the raw bytes.
181180
buf := new(bytes.Buffer)
182181

183-
//c, err := expect.NewConsole(expect.WithStdout(buf))
182+
c, err := expect.NewConsole(expect.WithStdout(buf))
184183
//c, err := expect.NewConsole(expect.WithStdout(os.Stdout))
185-
c, _, err := vt10x.NewVT10XConsole(expect.WithStdout(buf))
184+
//c, _, err := vt10x.New(expect.WithStdout(buf))
186185

187186
require.Nil(t, err)
188187
defer c.Close()

app/cmd/job_edit.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ func (j *JobEditOption) getSampleJenkinsfile() string {
148148
`
149149
}
150150

151-
//func getPipeline(name string) (script string, err error) {
151+
// func getPipeline(name string) (script string, err error) {
152152
func (j *JobEditOption) getPipeline(jClient *client.JobClient, name string) (script string, err error) {
153153
script = j.Script //we take the script from input firstly
154154
if script != "" {

0 commit comments

Comments
 (0)