Skip to content

Commit 94454db

Browse files
WangXiangUSTCLinuxSuRen
authored andcommitted
Allow pass a file type param when build Jenkins job
* define const string * fix check * merge master * minor update * support upload file * can run success * add unit test * refine code * add cmd config param-file
1 parent 13ca43f commit 94454db

File tree

4 files changed

+96
-20
lines changed

4 files changed

+96
-20
lines changed

app/cmd/job_build.go

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,10 @@ package cmd
33
import (
44
"encoding/json"
55
"fmt"
6-
"github.com/jenkins-zh/jenkins-cli/app/cmd/common"
76
"strings"
87

8+
"github.com/jenkins-zh/jenkins-cli/app/cmd/common"
99
"github.com/jenkins-zh/jenkins-cli/app/i18n"
10-
1110
"github.com/jenkins-zh/jenkins-cli/client"
1211
"github.com/spf13/cobra"
1312
)
@@ -19,6 +18,8 @@ type JobBuildOption struct {
1918

2019
Param string
2120
ParamArray []string
21+
22+
ParamFilePathArray []string
2223
}
2324

2425
var jobBuildOption JobBuildOption
@@ -35,6 +36,9 @@ func init() {
3536
i18n.T("Parameters of the job which is JSON format"))
3637
jobBuildCmd.Flags().StringArrayVar(&jobBuildOption.ParamArray, "param-entry", nil,
3738
i18n.T("Parameters of the job which are the entry format, for example: --param-entry name=value"))
39+
jobBuildCmd.Flags().StringArrayVar(&jobBuildOption.ParamFilePathArray, "param-file", nil,
40+
i18n.T("Parameters of the job which is file path, for example: --param-file name=filename"))
41+
3842
jobBuildOption.BatchOption.Stdio = common.GetSystemStdio()
3943
jobBuildOption.CommonOption.Stdio = common.GetSystemStdio()
4044
}
@@ -45,8 +49,8 @@ var jobBuildCmd = &cobra.Command{
4549
Long: i18n.T(`Build the job of your Jenkins.
4650
You need to give the parameters if your pipeline has them. Learn more about it from https://jenkins.io/doc/book/pipeline/syntax/#parameters.`),
4751
Args: cobra.MinimumNArgs(1),
48-
PreRunE: func(cmd *cobra.Command, args []string) (err error) {
49-
if jobBuildOption.ParamArray == nil {
52+
PreRunE: func(_ *cobra.Command, _ []string) (err error) {
53+
if jobBuildOption.ParamArray == nil && jobBuildOption.ParamFilePathArray == nil {
5054
return
5155
}
5256

@@ -67,13 +71,23 @@ You need to give the parameters if your pipeline has them. Learn more about it f
6771
}
6872
}
6973

74+
for _, filepathEntry := range jobBuildOption.ParamFilePathArray {
75+
if filepathArray := strings.SplitN(filepathEntry, "=", 2); len(filepathArray) == 2 {
76+
paramDefs = append(paramDefs, client.ParameterDefinition{
77+
Name: filepathArray[0],
78+
Filepath: filepathArray[1],
79+
Type: client.FileParameterDefinition,
80+
})
81+
}
82+
}
83+
7084
var data []byte
7185
if data, err = json.Marshal(paramDefs); err == nil {
7286
jobBuildOption.Param = string(data)
7387
}
7488
return
7589
},
76-
RunE: func(cmd *cobra.Command, args []string) (err error) {
90+
RunE: func(_ *cobra.Command, args []string) (err error) {
7791
name := args[0]
7892

7993
if !jobBuildOption.Confirm(fmt.Sprintf("Are you sure to build job %s", name)) {

app/cmd/job_build_test.go

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@ package cmd
33
import (
44
"bytes"
55
"fmt"
6+
"io/ioutil"
7+
"net/http"
8+
"os"
9+
610
"github.com/golang/mock/gomock"
711
"github.com/jenkins-zh/jenkins-cli/client"
812
"github.com/jenkins-zh/jenkins-cli/mock/mhttp"
913
. "github.com/onsi/ginkgo"
1014
. "github.com/onsi/gomega"
11-
"io/ioutil"
12-
"net/http"
13-
"os"
1415
)
1516

1617
var _ = Describe("job build command", func() {
@@ -102,6 +103,22 @@ var _ = Describe("job build command", func() {
102103
_, err = rootCmd.ExecuteC()
103104
Expect(err).NotTo(HaveOccurred())
104105
})
106+
107+
/* FIXME: fix the test case
108+
It("with --param-file", func() {
109+
data, err := generateSampleConfig()
110+
Expect(err).To(BeNil())
111+
err = ioutil.WriteFile(rootOptions.ConfigFile, data, 0664)
112+
Expect(err).To(BeNil())
113+
114+
client.PrepareForBuildWithParams(roundTripper, "http://localhost:8080/jenkins", jobName,
115+
"admin", "111e3a2f0231198855dceaff96f20540a9")
116+
117+
rootCmd.SetArgs([]string{"job", "build", jobName, "--param-file", "sample=/tmp/sample.txt", "-b", "true", "--param", ""})
118+
_, err = rootCmd.ExecuteC()
119+
Expect(err).NotTo(HaveOccurred())
120+
})
121+
*/
105122
})
106123
})
107124

app/i18n/bindata.go

Lines changed: 5 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

client/job.go

Lines changed: 52 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
11
package client
22

33
import (
4+
"bytes"
45
"encoding/json"
56
"fmt"
6-
"go.uber.org/zap"
7+
"io"
78
"io/ioutil"
8-
"moul.io/http2curl"
9+
"mime/multipart"
910
"net/http"
1011
"net/url"
12+
"os"
13+
"path/filepath"
1114
"strconv"
1215
"strings"
1316

17+
"go.uber.org/zap"
18+
"moul.io/http2curl"
19+
1420
"github.com/jenkins-zh/jenkins-cli/util"
1521
)
1622

23+
// FileParameterDefinition is the definition for file parameter
24+
const FileParameterDefinition = "FileParameterDefinition"
25+
1726
// JobClient is client for operate jobs
1827
type JobClient struct {
1928
JenkinsCore
@@ -55,20 +64,55 @@ func (q *JobClient) BuildWithParams(jobName string, parameters []ParameterDefini
5564
path := ParseJobPath(jobName)
5665
api := fmt.Sprintf("%s/build", path)
5766

67+
fileParameters := make([]ParameterDefinition, 0, len(parameters))
68+
for _, parameter := range parameters {
69+
if parameter.Type == FileParameterDefinition {
70+
fileParameters = append(fileParameters, parameter)
71+
}
72+
}
73+
74+
body := &bytes.Buffer{}
75+
writer := multipart.NewWriter(body)
76+
defer writer.Close()
77+
78+
// upload file
79+
for _, parameter := range fileParameters {
80+
var file *os.File
81+
file, err = os.Open(parameter.Filepath)
82+
if err != nil {
83+
return err
84+
}
85+
defer file.Close()
86+
87+
var fWriter io.Writer
88+
fWriter, err = writer.CreateFormFile(parameter.Filepath, filepath.Base(parameter.Filepath))
89+
if err != nil {
90+
return err
91+
}
92+
_, err = io.Copy(fWriter, file)
93+
}
94+
5895
var paramJSON []byte
5996
if len(parameters) == 1 {
6097
paramJSON, err = json.Marshal(parameters[0])
6198
} else {
6299
paramJSON, err = json.Marshal(parameters)
63100
}
101+
if err != nil {
102+
return err
103+
}
64104

65-
if err == nil {
66-
formData := url.Values{"json": {fmt.Sprintf("{\"parameter\": %s}", string(paramJSON))}}
67-
payload := strings.NewReader(formData.Encode())
105+
if err = writer.WriteField("json", fmt.Sprintf("{\"parameter\": %s}", string(paramJSON))); err != nil {
106+
return err
107+
}
68108

69-
_, err = q.RequestWithoutData("POST", api,
70-
map[string]string{util.ContentType: util.ApplicationForm}, payload, 201)
109+
if err = writer.Close(); err != nil {
110+
return err
71111
}
112+
113+
_, err = q.RequestWithoutData("POST", api,
114+
map[string]string{util.ContentType: writer.FormDataContentType()}, body, 201)
115+
72116
return
73117
}
74118

@@ -377,6 +421,7 @@ type ParameterDefinition struct {
377421
Name string `json:"name"`
378422
Type string
379423
Value string `json:"value"`
424+
Filepath string `json:"file"`
380425
DefaultParameterValue DefaultParameterValue
381426
}
382427

0 commit comments

Comments
 (0)