-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.go
More file actions
613 lines (529 loc) · 15.3 KB
/
Copy pathgithub.go
File metadata and controls
613 lines (529 loc) · 15.3 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
package githubresource
//go:generate go run github.com/Khan/genqlient
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"github.com/Khan/genqlient/graphql"
"github.com/google/go-github/v84/github"
)
//go:generate go tool counterfeiter -generate
type Config struct {
AccessToken string `json:"access_token"`
GraphqlEndpoint string `json:"graphql_endpoint"`
RestEndpoint string `json:"rest_endpoint"`
HostEndpoint string `json:"host_endpoint"`
Repository string `json:"repository"`
DisableGitLFS bool `json:"disable_git_lfs"`
SkipSSLVerification bool `json:"skip_ssl_verification"`
}
//counterfeiter:generate . GithubClient
type GithubClient interface {
// Returns the REST and GraphQL endpoints
APIEndpoints() (string, string)
HostEndpoint() string
AccessToken() string
// Returns pull requests matching the states and labels provided.
//
// If you want to match against no labels, pass in nil.
// PullRequest.FilesChanged is NOT populated.
ListPullRequests(states []PullRequestState, labels []string) ([]PullRequest, error)
// Returns the latest commit SHA for a given PR
LatestCommitForPR(int) (string, error)
// Returns information about the Pull Request. Only the first 100 files are
// listed.
GetPRInfo(int) (PullRequest, error)
// Returns the latest commits for matching PRs
LatestCommitsFromPrs(states []PullRequestState, labels []string) ([]PRCommit, error)
// Updates the status for a given ref
UpdatePRStatus(ref, name, status, descr string) error
// Configures the repo, initializing at the specified branch
InitRepo(uri, branch string) error
// Does `git fetch` to download the PR's data
FetchPr(uri, number string, depth int, fetchTags, submodules bool) error
// Pulls a known branch from origin
PullBranch(branch string, depth int, fetchTags, submodules bool) error
CheckoutPr(prBranch, ref string, submodules bool) error
RebasePr(baseRef, prRef string, submodules bool) error
MergePr(prRef string, submodules bool) error
}
type githubClient struct {
gqlClient graphql.Client
restClient *github.Client
owner string
repo string
config Config
cliEnv []string
}
var _ GithubClient = (*githubClient)(nil)
type authedTransport struct {
accessToken string
transport http.RoundTripper
}
func (a *authedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if a.accessToken != "" {
req.Header.Set("Authorization", "bearer "+a.accessToken)
}
return a.transport.RoundTrip(req)
}
const DefaultGraphqlEndpoint = "https://api.github.com/graphql"
const DefaultRestEndpoint = "https://api.github.com/"
const DefaultHostEndpoint = "https://github.com"
func NewGithubClient(cfg Config) (GithubClient, error) {
_, err := exec.LookPath("git")
if err != nil {
return nil, fmt.Errorf("error checking for the git cli: %w", err)
}
if cfg.GraphqlEndpoint == "" {
cfg.GraphqlEndpoint = DefaultGraphqlEndpoint
}
if cfg.RestEndpoint == "" {
cfg.RestEndpoint = DefaultRestEndpoint
}
if cfg.HostEndpoint == "" {
cfg.HostEndpoint = DefaultHostEndpoint
}
if cfg.Repository == "" {
return nil, errors.New("repository is blank and must be set. Expected format is 'OWNER/REPO'.")
}
repository := strings.Split(cfg.Repository, "/")
if len(repository) != 2 {
return nil, errors.New("unexpected format for 'repository'. Expected format is 'OWNER/REPO'.")
}
var httpClient *http.Client
var transport http.RoundTripper
if cfg.SkipSSLVerification {
transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
httpClient = &http.Client{
Transport: transport,
}
} else {
httpClient = http.DefaultClient
transport = http.DefaultTransport
}
gqlClient := graphql.NewClient(cfg.GraphqlEndpoint, &http.Client{
Transport: &authedTransport{
accessToken: cfg.AccessToken,
transport: transport,
},
})
ghc := github.NewClient(httpClient)
if cfg.AccessToken != "" {
ghc = ghc.WithAuthToken(cfg.AccessToken)
}
if cfg.RestEndpoint != DefaultRestEndpoint {
u, err := url.Parse(cfg.RestEndpoint)
if err != nil {
return nil, err
}
ghc.BaseURL = u
}
return &githubClient{
gqlClient: gqlClient,
restClient: ghc,
owner: repository[0],
repo: repository[1],
config: cfg,
cliEnv: []string{
fmt.Sprintf("%s=%s", "X_OAUTH_BASIC_TOKEN", cfg.AccessToken),
fmt.Sprintf("%s=%t", "GIT_LFS_SKIP_SMUDGE", cfg.DisableGitLFS),
"GIT_ASKPASS=/usr/local/bin/gitpass.sh",
"GIT_TERMINAL_PROMPT=0",
},
}, nil
}
func (g *githubClient) APIEndpoints() (string, string) {
return g.restClient.BaseURL.String(), g.config.GraphqlEndpoint
}
func (g *githubClient) HostEndpoint() string {
return g.config.HostEndpoint
}
func (g *githubClient) AccessToken() string {
return g.config.AccessToken
}
type PullRequest struct {
Number string `json:"number"`
Url string `json:"url,omitempty"`
IsDraft bool `json:"-"`
TargetBranch string `json:"target_branch,omitempty"`
FilesChanged []string `json:"changed_files,omitempty"`
ParentRepoUrl string `json:"parent_url,omitempty"`
Branch string `json:"branch,omitempty"`
Author string `json:"author,omitempty"`
Title string `json:"title,omitempty"`
}
func (g *githubClient) ListPullRequests(states []PullRequestState, labels []string) ([]PullRequest, error) {
_ = `# @genqlient
query getPullRequests(
$owner: String!
$name: String!
$states: [PullRequestState!]
$labels: [String!]
$endCursor: String
) {
repository(owner: $owner, name: $name) {
pullRequests(
first: 100,
after: $endCursor,
states: $states,
labels: $labels,
orderBy: {field: CREATED_AT, direction: ASC}
) {
nodes {
number
isDraft
permalink
baseRefName
headRefName
author {
login
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}`
prs := []PullRequest{}
ctx := context.Background()
hasNextPage := true
endCursor := ""
for hasNextPage {
resp, err := getPullRequests(ctx, g.gqlClient, g.owner, g.repo, states, labels, endCursor)
if err != nil {
return nil, err
}
for _, v := range resp.Repository.PullRequests.Nodes {
prs = append(prs, PullRequest{
Number: strconv.Itoa(v.Number),
Url: v.Permalink,
IsDraft: v.IsDraft,
TargetBranch: v.BaseRefName,
Branch: v.HeadRefName,
Author: v.Author.GetLogin(),
})
}
hasNextPage = resp.Repository.PullRequests.PageInfo.HasNextPage
endCursor = resp.Repository.PullRequests.PageInfo.EndCursor
}
return prs, nil
}
func (g *githubClient) LatestCommitForPR(prNumber int) (string, error) {
_ = `# @genqlient
query latestCommitForPr(
$owner: String!
$name: String!
$number: Int!
) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
commits(last: 1) {
nodes {
commit {
oid
}
}
}
}
}
}`
ctx := context.Background()
resp, err := latestCommitForPr(ctx, g.gqlClient, g.owner, g.repo, prNumber)
if err != nil {
return "", err
}
if len(resp.Repository.PullRequest.Commits.Nodes) < 1 {
return "", errors.New("no commits found for the given PR")
}
return resp.Repository.PullRequest.Commits.Nodes[0].Commit.Oid, nil
}
func (g *githubClient) GetPRInfo(prNumber int) (PullRequest, error) {
_ = `# @genqlient
query getPullRequest(
$owner: String!
$name: String!
$number: Int!
) {
repository(owner: $owner, name: $name) {
url
pullRequest(number: $number) {
number
title
isDraft
permalink
baseRefName
headRefName
author {
login
}
files(first: 100) {
nodes {
path
}
}
}
}
}
`
ctx := context.Background()
resp, err := getPullRequest(ctx, g.gqlClient, g.owner, g.repo, prNumber)
if err != nil {
return PullRequest{}, err
}
files := []string{}
for _, p := range resp.Repository.PullRequest.Files.Nodes {
files = append(files, p.Path)
}
return PullRequest{
Number: strconv.Itoa(prNumber),
Url: resp.Repository.PullRequest.Permalink,
IsDraft: resp.Repository.PullRequest.IsDraft,
TargetBranch: resp.Repository.PullRequest.BaseRefName,
FilesChanged: files,
ParentRepoUrl: resp.Repository.Url,
Branch: resp.Repository.PullRequest.HeadRefName,
Author: resp.Repository.PullRequest.Author.GetLogin(),
Title: resp.Repository.PullRequest.Title,
}, nil
}
type PRCommit struct {
PullRequest
Ref string `json:"ref"`
Date string `json:"date"`
Headline string `json:"headline"`
}
func (g *githubClient) LatestCommitsFromPrs(states []PullRequestState, labels []string) ([]PRCommit, error) {
_ = `# @genqlient
query latestCommitsFromPrs(
$owner: String!
$name: String!
$states: [PullRequestState!]
$labels: [String!]
$endCursor: String
) {
repository(owner: $owner, name: $name) {
pullRequests(
first: 100,
after: $endCursor,
states: $states,
labels: $labels,
orderBy: {field: UPDATED_AT, direction: ASC}
) {
nodes {
number
isDraft
title
permalink
baseRefName
headRefName
url
author {
login
}
commits(last: 1) {
nodes {
commit {
oid
messageHeadline
committedDate
}
}
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}`
prs := []PRCommit{}
ctx := context.Background()
hasNextPage := true
endCursor := ""
for hasNextPage {
resp, err := latestCommitsFromPrs(ctx, g.gqlClient, g.owner, g.repo, states, labels, endCursor)
if err != nil {
return nil, err
}
for _, v := range resp.Repository.PullRequests.Nodes {
if len(v.Commits.Nodes) > 0 {
prs = append(prs, PRCommit{
PullRequest: PullRequest{
Number: strconv.Itoa(v.Number),
Url: v.Permalink,
IsDraft: v.IsDraft,
TargetBranch: v.BaseRefName,
Branch: v.HeadRefName,
Author: v.Author.GetLogin(),
},
Ref: v.Commits.Nodes[0].Commit.Oid,
Date: v.Commits.Nodes[0].Commit.CommittedDate,
Headline: v.Commits.Nodes[0].Commit.MessageHeadline,
})
} else {
log.Printf("PR '%d' has no commits\n", v.Number)
}
}
hasNextPage = resp.Repository.PullRequests.PageInfo.HasNextPage
endCursor = resp.Repository.PullRequests.PageInfo.EndCursor
}
return prs, nil
}
func (g *githubClient) UpdatePRStatus(ref, name, status, descr string) error {
targetUrl := os.Getenv("BUILD_URL_SHORT")
if targetUrl == "" {
targetUrl = fmt.Sprintf("%s/builds/%s", os.Getenv("ATC_EXTERNAL_URL"), os.Getenv("BUILD_ID"))
}
_, _, err := g.restClient.Repositories.CreateStatus(context.TODO(), g.owner, g.repo, ref, github.RepoStatus{
State: &status,
Context: &name,
Description: &descr,
TargetURL: &targetUrl,
})
return err
}
func (g *githubClient) git(args ...string) *exec.Cmd {
cmd := exec.Command("git", args...)
cmd.Env = append(cmd.Env, os.Environ()...)
cmd.Env = append(cmd.Env, g.cliEnv...)
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
return cmd
}
func (g *githubClient) endpoint(uri string) (string, error) {
endpoint, err := url.Parse(uri)
if err != nil {
return "", fmt.Errorf("failed to parse uri: %w", err)
}
endpoint.User = url.UserPassword("x-oauth-basic", g.config.AccessToken)
return endpoint.String(), nil
}
func (g *githubClient) InitRepo(uri, branch string) error {
err := g.git("init", "--initial-branch", branch).Run()
if err != nil {
return fmt.Errorf("git init error: %w", err)
}
err = g.git("config", "user.name", "concourse-ci").Run()
if err != nil {
return fmt.Errorf("git config user.name error: %w", err)
}
err = g.git("config", "user.email", "concourse@local").Run()
if err != nil {
return fmt.Errorf("git config user.email error: %w", err)
}
err = g.git("config", "url.https://x-oauth-basic@github.com/.insteadOf", "git@github.com:").Run()
if err != nil {
return fmt.Errorf("git config url-1 error: %w", err)
}
err = g.git("config", "url.https://.insteadOf", "git://").Run()
if err != nil {
return fmt.Errorf("git config url-2 error: %w", err)
}
remoteUri, err := g.endpoint(uri)
if err != nil {
return err
}
err = g.git("remote", "add", "origin", remoteUri).Run()
if err != nil {
return fmt.Errorf("error setting origin: %w", err)
}
return nil
}
func (g *githubClient) PullBranch(branch string, depth int, fetchTags, submodules bool) error {
pullArgs := []string{"pull", "origin", branch}
if depth > 0 {
pullArgs = append(pullArgs, "--depth", strconv.Itoa(depth))
}
if fetchTags {
pullArgs = append(pullArgs, "--tags")
}
if submodules {
pullArgs = append(pullArgs, "--recurse-submodules")
}
err := g.git(pullArgs...).Run()
if err != nil {
return fmt.Errorf("error pulling origin: %w", err)
}
if submodules {
err = g.git("submodule", "update", "--init", "--recursive").Run()
if err != nil {
return fmt.Errorf("error updating submodules: %w", err)
}
}
return nil
}
func (g *githubClient) FetchPr(uri, number string, depth int, fetchTags, submodules bool) error {
remoteUri, err := g.endpoint(uri)
if err != nil {
return err
}
args := []string{"fetch", remoteUri, fmt.Sprintf("pull/%s/head", number)}
if depth > 0 {
args = append(args, "--depth", strconv.Itoa(depth))
}
if fetchTags {
args = append(args, "--tags")
}
if submodules {
args = append(args, "--recurse-submodules")
}
err = g.git(args...).Run()
if err != nil {
return fmt.Errorf("error fetching PR: %w", err)
}
return nil
}
func (g *githubClient) CheckoutPr(prBranch, ref string, submodules bool) error {
err := g.git("checkout", "-b", prBranch, ref).Run()
if err != nil {
return fmt.Errorf("error checking out PR: %w", err)
}
if submodules {
err = g.git("submodule", "update", "--init", "--recursive", "--checkout").Run()
if err != nil {
return fmt.Errorf("error updating submodules: %w", err)
}
}
return nil
}
func (g *githubClient) RebasePr(baseRef, prRef string, submodules bool) error {
err := g.git("rebase", baseRef, prRef).Run()
if err != nil {
return fmt.Errorf("error rebasing PR: %w", err)
}
if submodules {
err = g.git("submodule", "update", "--init", "--recursive", "--rebase").Run()
if err != nil {
return fmt.Errorf("error updating submodules: %w", err)
}
}
return nil
}
func (g *githubClient) MergePr(prRef string, submodules bool) error {
err := g.git("merge", prRef, "--no-stat").Run()
if err != nil {
return fmt.Errorf("error merging PR: %w", err)
}
if submodules {
err = g.git("submodule", "update", "--init", "--recursive", "--merge").Run()
if err != nil {
return fmt.Errorf("error updating submodules: %w", err)
}
}
return nil
}