Skip to content

Commit d6f3216

Browse files
committed
style: format
1 parent 0b1575b commit d6f3216

File tree

1 file changed

+154
-154
lines changed

1 file changed

+154
-154
lines changed

main.go

Lines changed: 154 additions & 154 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
11
package main
22

33
import (
4-
"context"
5-
"crypto/tls"
6-
"encoding/json"
7-
"fmt"
8-
"github.com/avast/retry-go"
9-
"github.com/bndr/gojenkins"
10-
"github.com/spf13/cobra"
11-
"net/http"
12-
"os"
13-
"strings"
14-
"time"
4+
"context"
5+
"crypto/tls"
6+
"encoding/json"
7+
"fmt"
8+
"github.com/avast/retry-go"
9+
"github.com/bndr/gojenkins"
10+
"github.com/spf13/cobra"
11+
"net/http"
12+
"os"
13+
"strings"
14+
"time"
1515
)
1616

1717
const (
18-
defaultJenkinsUrl = "http://127.0.0.1:8080"
19-
defaultWait = false
20-
defaultWaitPollSecond = 10
21-
defaultWaitMaxAttempts = 60
22-
desc = `This command triggers Jenkins job.
18+
defaultJenkinsUrl = "http://127.0.0.1:8080"
19+
defaultWait = false
20+
defaultWaitPollSecond = 10
21+
defaultWaitMaxAttempts = 60
22+
desc = `This command triggers Jenkins job.
2323
2424
You can specify the '--job'/'-j' flag to determine the name of the Jenkins job to run.
2525
To specify jobs within folders, use the '-–job-folders'/'-f' flag to define the folder path using slashes (/) as separators (e.g., foo/bar).
@@ -49,179 +49,179 @@ Use '--max-attempts' flag to set the max count of polling for results.
4949
)
5050

5151
func main() {
52-
c := config{
53-
Jenkins: jenkins{
54-
Url: defaultJenkinsUrl,
55-
},
56-
Job: job{},
57-
Wait: wait{
58-
Enabled: defaultWait,
59-
PollTime: defaultWaitPollSecond * time.Second,
60-
MaxAttempts: defaultWaitMaxAttempts,
61-
},
62-
}
63-
64-
params := params{}
65-
cmd := &cobra.Command{
66-
Use: "jenkins-trigger",
67-
Short: "Trigger Jenkins job in Go",
68-
Long: desc,
69-
SilenceUsage: true,
70-
RunE: func(cmd *cobra.Command, args []string) (err error) {
71-
c.Job.Params, err = params.init()
72-
if err != nil {
73-
return
74-
}
75-
return triggerBuild(c)
76-
},
77-
}
78-
79-
flags := cmd.Flags()
80-
flags.StringVar(&c.Jenkins.Url, "jenkins-url", c.Jenkins.Url, "URL of the Jenkins server")
81-
flags.StringVar(&c.Jenkins.User, "jenkins-user", c.Jenkins.User, "User for accessing Jenkins")
82-
flags.StringVar(&c.Jenkins.Pat, "jenkins-pat", c.Jenkins.Pat, "Personal access token (PAT) for accessing Jenkins")
83-
flags.BoolVarP(&c.Jenkins.Insecure, "insecure", "k", c.Jenkins.Insecure, "Allow insecure Jenkins server connections when using SSL")
84-
flags.StringVarP(&c.Job.Name, "job", "j", c.Job.Name, "The name of the Jenkins job to run")
85-
flags.StringSliceVarP(&c.Job.Folders, "job-folders", "f", c.Job.Folders, "The folder paths of the job, can specify multiple or separate parameters with slashes, e.g., foo/bar")
86-
flags.StringSliceVarP(&params.slice, "params", "p", params.slice, "The parameters of the job in key=value format, can specify multiple or separate parameters with commas, e.g., foo=bar,baz=qux")
87-
flags.StringVarP(&params.json, "params-json", "P", params.json, "The parameters of the job in JSON format, e.g., {\"foo\":\"bar\",\"baz\":\"qux\"}")
88-
flags.BoolVar(&c.Wait.Enabled, "wait", c.Wait.Enabled, "Wait for the job to complete, and return the results")
89-
flags.DurationVar(&c.Wait.PollTime, "poll-time", c.Wait.PollTime, "How often (duration) to poll the Jenkins server for results")
90-
flags.UintVar(&c.Wait.MaxAttempts, "max-attempts", c.Wait.MaxAttempts, "Max count of polling for results")
91-
92-
_ = cmd.MarkFlagRequired("job")
93-
94-
if err := cmd.Execute(); err != nil {
95-
_, _ = fmt.Fprintln(os.Stderr, err)
96-
os.Exit(1)
97-
}
52+
c := config{
53+
Jenkins: jenkins{
54+
Url: defaultJenkinsUrl,
55+
},
56+
Job: job{},
57+
Wait: wait{
58+
Enabled: defaultWait,
59+
PollTime: defaultWaitPollSecond * time.Second,
60+
MaxAttempts: defaultWaitMaxAttempts,
61+
},
62+
}
63+
64+
params := params{}
65+
cmd := &cobra.Command{
66+
Use: "jenkins-trigger",
67+
Short: "Trigger Jenkins job in Go",
68+
Long: desc,
69+
SilenceUsage: true,
70+
RunE: func(cmd *cobra.Command, args []string) (err error) {
71+
c.Job.Params, err = params.init()
72+
if err != nil {
73+
return
74+
}
75+
return triggerBuild(c)
76+
},
77+
}
78+
79+
flags := cmd.Flags()
80+
flags.StringVar(&c.Jenkins.Url, "jenkins-url", c.Jenkins.Url, "URL of the Jenkins server")
81+
flags.StringVar(&c.Jenkins.User, "jenkins-user", c.Jenkins.User, "User for accessing Jenkins")
82+
flags.StringVar(&c.Jenkins.Pat, "jenkins-pat", c.Jenkins.Pat, "Personal access token (PAT) for accessing Jenkins")
83+
flags.BoolVarP(&c.Jenkins.Insecure, "insecure", "k", c.Jenkins.Insecure, "Allow insecure Jenkins server connections when using SSL")
84+
flags.StringVarP(&c.Job.Name, "job", "j", c.Job.Name, "The name of the Jenkins job to run")
85+
flags.StringSliceVarP(&c.Job.Folders, "job-folders", "f", c.Job.Folders, "The folder paths of the job, can specify multiple or separate parameters with slashes, e.g., foo/bar")
86+
flags.StringSliceVarP(&params.slice, "params", "p", params.slice, "The parameters of the job in key=value format, can specify multiple or separate parameters with commas, e.g., foo=bar,baz=qux")
87+
flags.StringVarP(&params.json, "params-json", "P", params.json, "The parameters of the job in JSON format, e.g., {\"foo\":\"bar\",\"baz\":\"qux\"}")
88+
flags.BoolVar(&c.Wait.Enabled, "wait", c.Wait.Enabled, "Wait for the job to complete, and return the results")
89+
flags.DurationVar(&c.Wait.PollTime, "poll-time", c.Wait.PollTime, "How often (duration) to poll the Jenkins server for results")
90+
flags.UintVar(&c.Wait.MaxAttempts, "max-attempts", c.Wait.MaxAttempts, "Max count of polling for results")
91+
92+
_ = cmd.MarkFlagRequired("job")
93+
94+
if err := cmd.Execute(); err != nil {
95+
_, _ = fmt.Fprintln(os.Stderr, err)
96+
os.Exit(1)
97+
}
9898
}
9999

100100
func triggerBuild(c config) error {
101-
fmt.Printf("Triggering Jenkins build for job: %+v, wait: %+v\n", c.Job, c.Wait)
102-
103-
jenkins, err := c.Jenkins.createClient()
104-
if err != nil {
105-
return err
106-
}
107-
108-
queueId, err := buildJob(context.Background(), jenkins, &c.Job)
109-
if err != nil {
110-
return err
111-
}
112-
113-
fmt.Printf("Job %s triggered successfully\n", c.Job.Name)
114-
115-
if !c.Wait.Enabled {
116-
return nil
117-
}
118-
119-
return retry.Do(
120-
pollBuildResult(c, jenkins, queueId),
121-
retry.DelayType(retry.FixedDelay),
122-
retry.Delay(c.Wait.PollTime),
123-
retry.Attempts(c.Wait.MaxAttempts),
124-
)
101+
fmt.Printf("Triggering Jenkins build for job: %+v, wait: %+v\n", c.Job, c.Wait)
102+
103+
jenkins, err := c.Jenkins.createClient()
104+
if err != nil {
105+
return err
106+
}
107+
108+
queueId, err := buildJob(context.Background(), jenkins, &c.Job)
109+
if err != nil {
110+
return err
111+
}
112+
113+
fmt.Printf("Job %s triggered successfully\n", c.Job.Name)
114+
115+
if !c.Wait.Enabled {
116+
return nil
117+
}
118+
119+
return retry.Do(
120+
pollBuildResult(c, jenkins, queueId),
121+
retry.DelayType(retry.FixedDelay),
122+
retry.Delay(c.Wait.PollTime),
123+
retry.Attempts(c.Wait.MaxAttempts),
124+
)
125125
}
126126

127127
func buildJob(ctx context.Context, jenkins *gojenkins.Jenkins, job *job) (int64, error) {
128-
var f []string
129-
for _, folder := range job.Folders {
130-
parts := strings.Split(folder, "/")
131-
for _, part := range parts {
132-
if trimmed := strings.TrimSpace(part); trimmed != "" {
133-
f = append(f, trimmed)
134-
}
135-
}
136-
}
137-
if len(f) == 0 {
138-
return jenkins.BuildJob(ctx, job.Name, job.Params)
139-
}
140-
j := gojenkins.Job{Jenkins: jenkins, Raw: new(gojenkins.JobResponse), Base: "/job/" + strings.Join(append(f, job.Name), "/job/")}
141-
return j.InvokeSimple(ctx, job.Params)
128+
var f []string
129+
for _, folder := range job.Folders {
130+
parts := strings.Split(folder, "/")
131+
for _, part := range parts {
132+
if trimmed := strings.TrimSpace(part); trimmed != "" {
133+
f = append(f, trimmed)
134+
}
135+
}
136+
}
137+
if len(f) == 0 {
138+
return jenkins.BuildJob(ctx, job.Name, job.Params)
139+
}
140+
j := gojenkins.Job{Jenkins: jenkins, Raw: new(gojenkins.JobResponse), Base: "/job/" + strings.Join(append(f, job.Name), "/job/")}
141+
return j.InvokeSimple(ctx, job.Params)
142142
}
143143

144144
func pollBuildResult(c config, jenkins *gojenkins.Jenkins, queueId int64) func() error {
145-
return func() error {
146-
fmt.Printf("Polling build result for job %s\n", c.Job.Name)
147-
148-
build, err := jenkins.GetBuildFromQueueID(context.Background(), queueId)
149-
if err != nil {
150-
return err
151-
}
152-
153-
if build.IsGood(context.Background()) {
154-
fmt.Printf("Job %s, build number %d successfully\n", c.Job.Name, build.GetBuildNumber())
155-
return nil
156-
}
157-
158-
if build.IsRunning(context.Background()) {
159-
fmt.Printf("Job %s, build number %d is still running, retry after %s\n", c.Job.Name, build.GetBuildNumber(), c.Wait.PollTime)
160-
return &IsStillRunning{time.Now(), c.Job.Name, build.GetBuildNumber()}
161-
}
162-
163-
return retry.Unrecoverable(fmt.Errorf("Job %s Build number %d did not complete successfully\n", c.Job.Name, build.GetBuildNumber()))
164-
}
145+
return func() error {
146+
fmt.Printf("Polling build result for job %s\n", c.Job.Name)
147+
148+
build, err := jenkins.GetBuildFromQueueID(context.Background(), queueId)
149+
if err != nil {
150+
return err
151+
}
152+
153+
if build.IsGood(context.Background()) {
154+
fmt.Printf("Job %s, build number %d successfully\n", c.Job.Name, build.GetBuildNumber())
155+
return nil
156+
}
157+
158+
if build.IsRunning(context.Background()) {
159+
fmt.Printf("Job %s, build number %d is still running, retry after %s\n", c.Job.Name, build.GetBuildNumber(), c.Wait.PollTime)
160+
return &IsStillRunning{time.Now(), c.Job.Name, build.GetBuildNumber()}
161+
}
162+
163+
return retry.Unrecoverable(fmt.Errorf("Job %s Build number %d did not complete successfully\n", c.Job.Name, build.GetBuildNumber()))
164+
}
165165
}
166166

167167
// IsStillRunning indicate a Jenkins job is not done yet
168168
type IsStillRunning struct {
169-
time time.Time
170-
jobName string
171-
buildNumber int64
169+
time time.Time
170+
jobName string
171+
buildNumber int64
172172
}
173173

174174
func (r *IsStillRunning) Error() string {
175-
return fmt.Sprintf("job %s, build number %d is still running. (%s)\n", r.jobName, r.buildNumber, r.time.Format(time.Stamp))
175+
return fmt.Sprintf("job %s, build number %d is still running. (%s)\n", r.jobName, r.buildNumber, r.time.Format(time.Stamp))
176176
}
177177

178178
type config struct {
179-
Jenkins jenkins
180-
Job job
181-
Wait wait
179+
Jenkins jenkins
180+
Job job
181+
Wait wait
182182
}
183183

184184
type wait struct {
185-
Enabled bool
186-
PollTime time.Duration
187-
MaxAttempts uint
185+
Enabled bool
186+
PollTime time.Duration
187+
MaxAttempts uint
188188
}
189189

190190
type jenkins struct {
191-
Url string
192-
User string
193-
Pat string
194-
Insecure bool
191+
Url string
192+
User string
193+
Pat string
194+
Insecure bool
195195
}
196196

197197
func (j *jenkins) createClient() (*gojenkins.Jenkins, error) {
198-
client := &http.Client{Transport: &http.Transport{
199-
TLSClientConfig: &tls.Config{InsecureSkipVerify: j.Insecure},
200-
}}
201-
return gojenkins.CreateJenkins(client, j.Url, j.User, j.Pat).Init(context.Background())
198+
client := &http.Client{Transport: &http.Transport{
199+
TLSClientConfig: &tls.Config{InsecureSkipVerify: j.Insecure},
200+
}}
201+
return gojenkins.CreateJenkins(client, j.Url, j.User, j.Pat).Init(context.Background())
202202
}
203203

204204
type job struct {
205-
Name string
206-
Folders []string
207-
Params map[string]string
205+
Name string
206+
Folders []string
207+
Params map[string]string
208208
}
209209

210210
type params struct {
211-
slice []string
212-
json string
211+
slice []string
212+
json string
213213
}
214214

215215
func (p *params) init() (map[string]string, error) {
216-
params := make(map[string]string)
217-
if p.json != "" {
218-
if err := json.Unmarshal([]byte(p.json), &params); err != nil {
219-
return nil, err
220-
}
221-
}
222-
for _, v := range p.slice {
223-
split := strings.Split(v, "=")
224-
params[split[0]] = strings.Join(split[1:], "=")
225-
}
226-
return params, nil
216+
params := make(map[string]string)
217+
if p.json != "" {
218+
if err := json.Unmarshal([]byte(p.json), &params); err != nil {
219+
return nil, err
220+
}
221+
}
222+
for _, v := range p.slice {
223+
split := strings.Split(v, "=")
224+
params[split[0]] = strings.Join(split[1:], "=")
225+
}
226+
return params, nil
227227
}

0 commit comments

Comments
 (0)