-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
job_log.go
98 lines (82 loc) · 2.35 KB
/
job_log.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package cmd
import (
"fmt"
"log"
"time"
"github.com/jenkins-zh/jenkins-cli/client"
"github.com/spf13/cobra"
)
// JobLogOption is the job log option
type JobLogOption struct {
WatchOption
History int
LogText string
LastBuildID int
LastBuildURL string
}
var jobLogOption JobLogOption
func init() {
jobCmd.AddCommand(jobLogCmd)
jobLogCmd.Flags().IntVarP(&jobLogOption.History, "history", "s", -1, "Specific build history of log")
jobLogCmd.Flags().BoolVarP(&jobLogOption.Watch, "watch", "w", false, "Watch the job logs")
jobLogCmd.Flags().IntVarP(&jobLogOption.Interval, "interval", "i", 1, "Interval of watch")
}
var jobLogCmd = &cobra.Command{
Use: "log <jobName>",
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 {
cmd.Help()
return
}
name := args[0]
jenkins := getCurrentJenkinsFromOptionsOrDie()
jclient := &client.JobClient{}
jclient.URL = jenkins.URL
jclient.UserName = jenkins.UserName
jclient.Token = jenkins.Token
jclient.Proxy = jenkins.Proxy
jclient.ProxyAuth = jenkins.ProxyAuth
lastBuildID := -1
for {
if build, err := jclient.GetBuild(name, -1); err == nil {
jobLogOption.LastBuildID = build.Number
jobLogOption.LastBuildURL = build.URL
}
if lastBuildID != jobLogOption.LastBuildID {
lastBuildID = jobLogOption.LastBuildID
fmt.Println("Current build number:", jobLogOption.LastBuildID)
fmt.Println("Current build url:", jobLogOption.LastBuildURL)
printLog(jclient, name, jobLogOption.History, 0)
}
if !jobLogOption.Watch {
break
}
time.Sleep(time.Duration(jobLogOption.Interval) * time.Second)
}
},
}
func printLog(jclient *client.JobClient, jobName string, history int, start int64) {
if status, err := jclient.Log(jobName, history, start); err == nil {
isNew := false
if jobLogOption.LogText != status.Text {
jobLogOption.LogText = status.Text
isNew = true
} else if history == -1 {
if build, err := jclient.GetBuild(jobName, -1); err == nil && jobLogOption.LastBuildID != build.Number {
jobLogOption.LastBuildID = build.Number
jobLogOption.LastBuildURL = build.URL
isNew = true
}
}
if isNew {
fmt.Print(status.Text)
}
if status.HasMore {
printLog(jclient, jobName, history, status.NextStart)
}
} else {
log.Fatal(err)
}
}