-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprwatcher.go
287 lines (247 loc) · 7.13 KB
/
prwatcher.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/robfig/cron"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"io/ioutil"
"net/http"
"os"
"strconv"
)
type TriggerData struct {
PR int
FromRef string
ToRef string
}
type PullRequestsResponse struct {
Size int `json:"size"`
Values []struct {
ID int `json:"id"`
Version int `json:"version"`
State string `json:"state"`
Open bool `json:"open"`
Closed bool `json:"closed"`
CreatedDate int64 `json:"createdDate"`
UpdatedDate int64 `json:"updatedDate"`
FromRef struct {
ID string `json:"id"`
} `json:"fromRef"`
ToRef struct {
ID string `json:"id"`
} `json:"toRef"`
} `json:"values"`
}
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
func getPullRequestsResponse(body []byte) (*PullRequestsResponse, error) {
s := new(PullRequestsResponse)
err := json.Unmarshal(body, &s)
if err != nil {
log.Error(err)
}
return s, err
}
func getPullRequests(host, project, repository, token string) *PullRequestsResponse {
url := host + "/rest/api/1.0/projects/" + project + "/repos/" + repository + "/pull-requests/"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Basic "+token)
res, _ := http.DefaultClient.Do(req)
body, err := ioutil.ReadAll(res.Body)
if res.StatusCode != 200 {
log.Error("Getting pull requests, failed. Status: ", res.StatusCode)
}
if res.StatusCode == 403 || res.StatusCode == 401 {
panic(string(body))
}
fmt.Println(string(body))
if err != nil {
log.Error(err)
}
defer res.Body.Close()
s, _ := getPullRequestsResponse([]byte(body))
return s
}
var active_pr_list map[int]int64 = make(map[int]int64)
var passive_pr_list map[int]int64 = make(map[int]int64)
var triggerCount int = 0
func triggerJob(host, project, repository, token, trigger_uri string) {
pull_requests := getPullRequests(host, project, repository, token)
triggerList := getTriggerList(pull_requests)
for _, data := range triggerList {
log.Info("PR: ", data.PR, " trigger starting")
triggerToUri(data.PR, data, trigger_uri)
}
}
func getTriggerList(pull_requests *PullRequestsResponse) []TriggerData {
triggerCount++
if triggerCount%10 == 0 {
log.Info("triggered ", triggerCount, " times")
log.Info("active pull requests: ", active_pr_list)
log.Info("passive pull requests: ", passive_pr_list)
}
var triggerList []TriggerData
for k, v := range active_pr_list {
if v == 0 {
continue
}
found := false
for _, pr := range pull_requests.Values {
if k == pr.ID {
found = true
break
}
}
if !found {
delete(active_pr_list, k)
passive_pr_list[k] = v
log.Info("PR: ", k, " is close(aka passive).")
}
}
for _, pr := range pull_requests.Values {
updateDate, exists := active_pr_list[pr.ID]
if exists {
if updateDate == 0 {
log.Info("PR: ", pr.ID, " will be tried again.")
active_pr_list[pr.ID] = pr.UpdatedDate
}
if pr.UpdatedDate == updateDate {
log.Info("PR: ", pr.ID, " open but this version triggered before. Will be skipped.")
} else {
log.Info("PR: ", pr.ID, " triggered before but updated on ", pr.UpdatedDate, " so will be triggered again.")
active_pr_list[pr.ID] = pr.UpdatedDate
triggerList = append(triggerList, TriggerData{pr.ID, pr.FromRef.ID, pr.ToRef.ID})
}
} else {
log.Info("New PR: ", pr.ID, " created on ", pr.CreatedDate, " updated on ", pr.UpdatedDate)
active_pr_list[pr.ID] = pr.UpdatedDate
triggerList = append(triggerList, TriggerData{pr.ID, pr.FromRef.ID, pr.ToRef.ID})
}
}
return triggerList
}
func triggerToUri(id int, data TriggerData, trigger_uri string) {
url := trigger_uri + "&cause=pr-watcher&pr=" + strconv.Itoa(data.PR) + "&fromRef=" + data.FromRef + "&toRef=" + data.ToRef
log.Info("sending post request to ", url)
req, _ := http.NewRequest("POST", url, nil)
res, _ := http.DefaultClient.Do(req)
if res.StatusCode != 201 {
log.Error("PR: ", id, " trigger failed. Status: ", res.StatusCode)
active_pr_list[id] = 0 //0 means try later
}
body, err := ioutil.ReadAll(res.Body)
if res.StatusCode == 403 || res.StatusCode == 401 {
panic(string(body))
}
fmt.Println(string(body))
if err != nil {
log.Error(err)
}
defer res.Body.Close()
}
func main() {
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
log.SetLevel(log.DebugLevel)
app := cli.NewApp()
app.Name = "prwatcher - watch stash pull requests if changes then trigger jenkins"
app.Description = "watch stash pull requests if changes then trigger"
app.Version = "0.0.1"
app.Authors = []cli.Author{
{
Name: "Ahmet Oz",
Email: "[email protected]",
},
}
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "host",
Value: "",
Usage: "host address of docker registry",
EnvVar: "HOST",
},
cli.StringFlag{
Name: "project",
Value: "",
Usage: "Only projects for which the authenticated user has the PROJECT_VIEW permission will be returned.",
EnvVar: "PROJECT",
},
cli.StringFlag{
Name: "repository",
Value: "latest",
Usage: "The authenticated user must have REPO_READ permission for the specified project to call this resource.",
EnvVar: "REPOSITORY",
},
cli.StringFlag{
Name: "username",
Value: "",
Usage: "stash user name",
EnvVar: "USERNAME",
},
cli.StringFlag{
Name: "password",
Value: "",
Usage: "stash user password",
EnvVar: "PASSWORD",
},
cli.StringFlag{
Name: "trigger_uri",
Value: "",
Usage: "job trigger uri - pr id will be added as query string to uri",
EnvVar: "TRIGGER_URI",
},
cli.StringFlag{
Name: "duration",
Value: "@every 5m",
Usage: "job duration https://godoc.org/github.com/robfig/cron#hdr-Intervals",
EnvVar: "DURATION",
},
}
app.Action = func(c *cli.Context) error {
if c.String("host") == "" {
return cli.NewExitError("host is required", 86)
}
if c.String("project") == "" {
return cli.NewExitError("project is required", 86)
}
if c.String("repository") == "" {
return cli.NewExitError("project is required", 86)
}
if c.String("username") == "" {
return cli.NewExitError("user name is required", 86)
}
if c.String("password") == "" {
return cli.NewExitError("password is required", 86)
}
if c.String("trigger_uri") == "" {
return cli.NewExitError("trigger_uri is required", 86)
}
infiniteChannel := make(chan bool)
token := basicAuth(c.String("username"), c.String("password"))
host := c.String("host")
project := c.String("project")
repository := c.String("repository")
duration := c.String("duration")
trigger_uri := c.String("trigger_uri")
log.WithFields(log.Fields{
"host": host,
"project": project,
"repository": repository,
"duration": duration,
"trigger_uri": trigger_uri,
}).Info("The PR watcher starting...")
triggerJob(host, project, repository, token, trigger_uri)
job := cron.New()
job.AddFunc(duration, func() {
triggerJob(host, project, repository, token, trigger_uri)
})
job.Start()
<-infiniteChannel
return nil
}
app.Run(os.Args)
}