This repository has been archived by the owner on Aug 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
/
utils.go
330 lines (279 loc) · 8.63 KB
/
utils.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/Sirupsen/logrus"
"github.com/crosbymichael/octokat"
"github.com/docker/leeroy/github"
)
// Commit describes information in a commit
type Commit struct {
CommentsURL string `json:"comments_url,omitempty"`
HTMLURL string `json:"html_url,omitempty"`
Sha string `json:"sha,omitempty"`
URL string `json:"url,omitempty"`
}
func (c Config) getBuilds(baseRepo string, isCustom bool, includePipeline bool) (builds []Build, err error) {
for _, build := range c.Builds {
if build.Repo == baseRepo && isCustom == build.Custom {
if !includePipeline && build.IsPipeline {
continue
}
builds = append(builds, build)
}
}
if len(builds) <= 0 {
return builds, fmt.Errorf("Could not find config for %s", baseRepo)
}
return builds, nil
}
func (c Config) getBuildByJob(job string) (build Build, err error) {
for _, build := range c.Builds {
if build.Job == job {
return build, nil
}
}
return build, fmt.Errorf("Could not find config for %s", job)
}
func (c Config) getBuildByContextAndRepo(context, repo string) (build Build, err error) {
if context == "" {
context = DEFAULTCONTEXT
}
for _, build := range c.Builds {
if build.Context == context && build.Repo == repo {
return build, nil
}
}
return build, fmt.Errorf("Could not find config for context: %s, repo: %s", context, repo)
}
func (c Config) addGithubComment(repoName, pr, comment string) error {
// parse git repo for username
// and repo name
r := strings.SplitN(repoName, "/", 2)
if len(r) < 2 {
return fmt.Errorf("repo name could not be parsed: %s", repoName)
}
// initialize github client
gh := octokat.NewClient()
gh = gh.WithToken(c.GHToken)
repo := octokat.Repo{
Name: r[1],
UserName: r[0],
}
// add comment to the PR
if _, err := gh.AddComment(repo, pr, comment); err != nil {
return fmt.Errorf("adding comment to %s#%s failed: %v", repoName, pr, err)
}
return nil
}
func (c Config) updateGithubStatus(repoName, context, sha, state, desc, buildURL string) error {
// parse git repo for username
// and repo name
r := strings.SplitN(repoName, "/", 2)
if len(r) < 2 {
return fmt.Errorf("repo name could not be parsed: %s", repoName)
}
// initialize github client
gh := octokat.NewClient()
gh = gh.WithToken(c.GHToken)
repo := octokat.Repo{
Name: r[1],
UserName: r[0],
}
status := &octokat.StatusOptions{
State: state,
Description: desc,
URL: buildURL,
Context: context,
}
if _, err := gh.SetStatus(repo, sha, status); err != nil {
return fmt.Errorf("setting status for repo: %s, sha: %s failed: %v", repoName, sha, err)
}
logrus.Infof("Setting status on %s %s to %s for %s succeeded", repoName, sha, state, context)
return nil
}
func hasStatus(gh *octokat.Client, repo octokat.Repo, sha, context string) bool {
statuses, err := gh.Statuses(repo, sha, &octokat.Options{})
if err != nil {
logrus.Warnf("getting status for %s for %s/%s failed: %v", sha, repo.UserName, repo.Name, err)
return false
}
for _, status := range statuses {
if status.Context == context && status.State == "success" {
return true
}
}
return false
}
func (c Config) getShas(owner, name, context string, number int, ref string) (shas []string, pr *octokat.PullRequest, err error) {
// initialize github client
gh := octokat.NewClient()
gh = gh.WithToken(c.GHToken)
repo := octokat.Repo{
Name: name,
UserName: owner,
}
// get the pull request so we can get the commits
if number != 0 {
pr, err = gh.PullRequest(repo, strconv.Itoa(number), &octokat.Options{})
if err != nil {
return shas, pr, fmt.Errorf("getting pull request %d for %s/%s failed: %v", number, owner, name, err)
}
}
if ref != "" {
commit, err := gh.Commit(repo, ref, &octokat.Options{})
if err != nil {
return shas, pr, fmt.Errorf("getting ref %s for %s/%s failed: %v", ref, owner, name, err)
}
shas = append(shas, commit.Sha)
}
// check which commits we want to get
// from the original flag --build-commits
if c.BuildCommits == "all" || c.BuildCommits == "new" {
// get the commits url
req, err := http.Get(pr.CommitsURL)
if err != nil {
return shas, pr, err
}
defer req.Body.Close()
// parse the response
var commits []Commit
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&commits); err != nil {
return shas, pr, fmt.Errorf("parsing the response from %s failed: %v", pr.CommitsURL, err)
}
// append the commit shas
for _, commit := range commits {
// if we only want the new shas
// check to make sure the status
// has not been set before appending
if c.BuildCommits == "new" {
if hasStatus(gh, repo, commit.Sha, context) {
continue
}
}
shas = append(shas, commit.Sha)
}
} else if pr != nil {
// this is the case where buildCommits == "last"
// just get the sha of the pr
shas = append(shas, pr.Head.Sha)
}
return shas, pr, nil
}
func (c Config) scheduleJenkinsBuild(baseRepo string, number int, ref string, build Build) error {
// setup the jenkins client
j := &config.Jenkins
// make sure we even want to build
if build.Job == "" {
return nil
}
// cancel any existing builds if we can, before sheduling another
if err := j.CancelBuildsForPR(build.Job, strconv.Itoa(number)); err != nil {
logrus.Warnf("Trying to cancel existing builds for job %s, pr %d failed: %v", build.Job, number, err)
}
// find the comments about failed builds and remove them
if err := config.removeFailedBuildComment(baseRepo, build.Job, number); err != nil {
logrus.Error(err)
}
// parse git repo for username
// and repo name
r := strings.SplitN(baseRepo, "/", 2)
if len(r) < 2 {
return fmt.Errorf("repo name could not be parsed: %s", baseRepo)
}
// get the shas to build
shas, pr, err := c.getShas(r[0], r[1], build.Context, number, ref)
if err != nil {
return err
}
for _, sha := range shas {
// schedule the build
if build.IsPipeline {
// Pipeline builds set their own status and have their own queue per PR/branch.
prNumber := 0
if pr != nil {
prNumber = pr.Number
ref = pr.Base.Ref
}
if err := j.BuildPipeline(build.Job, prNumber, ref); err != nil {
return fmt.Errorf("scheduling jenkins pipeline build failed with: %v", err)
}
} else {
// update the github status
if err := c.updateGithubStatus(baseRepo, build.Context, sha, "pending", "Jenkins build is being scheduled", c.Jenkins.Baseurl); err != nil {
return err
}
// setup the parameters
htmlURL := fmt.Sprintf("https://github.com/%s/pull/%d", baseRepo, pr.Number)
headRepo := fmt.Sprintf("%s/%s", pr.Head.Repo.Owner.Login, pr.Head.Repo.Name)
parameters := fmt.Sprintf("GIT_BASE_REPO=%s&GIT_HEAD_REPO=%s&GIT_SHA1=%s&GITHUB_URL=%s&PR=%d&BASE_BRANCH=%s", baseRepo, headRepo, sha, htmlURL, pr.Number, pr.Base.Ref)
if err := j.BuildWithParameters(build.Job, parameters); err != nil {
return fmt.Errorf("scheduling jenkins build failed: %v", err)
}
}
}
return nil
}
func (c Config) getFailedPRs(context, repoName string) (nums []int, err error) {
// parse git repo for username
// and repo name
r := strings.SplitN(repoName, "/", 2)
if len(r) < 2 {
return nums, fmt.Errorf("repo name could not be parsed: %s", repoName)
}
// initialize github client
gh := octokat.NewClient()
gh = gh.WithToken(c.GHToken)
repo := octokat.Repo{
Name: r[1],
UserName: r[0],
}
// get pull requests
prs, err := gh.PullRequests(repo, &octokat.Options{
Params: map[string]string{
"state": "open",
"per_page": "100",
},
})
if err != nil {
return nums, fmt.Errorf("requesting open repos for %s failed: %v", repoName, err)
}
for _, pr := range prs {
if !hasStatus(gh, repo, pr.Head.Sha, context) {
nums = append(nums, pr.Number)
}
}
return nums, nil
}
func (c Config) removeFailedBuildComment(repoName, job string, pr int) error {
// parse git repo for username
// and repo name
r := strings.SplitN(repoName, "/", 2)
if len(r) < 2 {
return fmt.Errorf("repo name could not be parsed: %s", repoName)
}
// initialize github client
g := github.GitHub{
AuthToken: c.GHToken,
User: c.GHUser,
}
repo := octokat.Repo{
Name: r[1],
UserName: r[0],
}
content, err := g.GetContent(repo, pr, true)
if err != nil {
return fmt.Errorf("getting pull request content failed: %v", err)
}
// find the comments about failed builds and remove them
if comment := content.FindComment(fmt.Sprintf("Job: %s [FAILED", job), c.GHUser); comment != nil {
if err := g.Client().RemoveComment(repo, comment.Id); err != nil {
return fmt.Errorf("removing comment from %s#%d for %s failed: %v", repoName, pr, job, err)
}
}
return nil
}