/
github.go
443 lines (394 loc) · 13.9 KB
/
github.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
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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package git
import (
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"path"
"path/filepath"
"strings"
"time"
"cloud.google.com/go/internal/gapicgen/execv"
"cloud.google.com/go/internal/gapicgen/execv/gocmd"
"github.com/google/go-github/v34/github"
"github.com/shurcooL/githubv4"
"golang.org/x/oauth2"
)
const (
gocloudBranchName = "regen_gocloud"
gocloudCommitTitle = "chore(all): auto-regenerate gapics"
gocloudCommitBody = `
This is an auto-generated regeneration of the gapic clients by
cloud.google.com/go/internal/gapicgen. Once the corresponding genproto PR is
submitted, genbot will update this PR with a newer dependency to the newer
version of genproto and assign reviewers to this PR.
If you have been assigned to review this PR, please:
- Ensure that the version of genproto in go.mod has been updated.
- Ensure that CI is passing. If it's failing, it requires your manual attention.
- Approve and submit this PR if you believe it's ready to ship.
`
genprotoBranchName = "regen_genproto"
genprotoCommitTitle = "chore(all): auto-regenerate .pb.go files"
genprotoCommitBody = `
This is an auto-generated regeneration of the .pb.go files by
cloud.google.com/go/internal/gapicgen. Once this PR is submitted, genbot will
update the corresponding PR to depend on the newer version of go-genproto, and
assign reviewers. Whilst this or any regen PR is open in go-genproto, genbot
will not create any more regeneration PRs. If all regen PRs are closed,
gapicgen will create a new set of regeneration PRs once per night.
If you have been assigned to review this PR, please:
- Ensure that CI is passing. If it's failing, it requires your manual attention.
- Approve and submit this PR if you believe it's ready to ship. That will prompt
genbot to assign reviewers to the google-cloud-go PR.
`
)
// PullRequest represents a GitHub pull request.
type PullRequest struct {
Author string
Title string
URL string
Created time.Time
IsOpen bool
Number int
Repo string
IsDraft bool
NodeID string
}
// GithubClient is a convenience wrapper around Github clients.
type GithubClient struct {
cV3 *github.Client
cV4 *githubv4.Client
// Username is the GitHub username. Read-only.
Username string
}
// NewGithubClient creates a new GithubClient.
func NewGithubClient(ctx context.Context, username, name, email, accessToken string) (*GithubClient, error) {
if err := setGitCreds(name, email, username, accessToken); err != nil {
return nil, err
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: accessToken},
)
tc := oauth2.NewClient(ctx, ts)
return &GithubClient{cV3: github.NewClient(tc), cV4: githubv4.NewClient(tc), Username: username}, nil
}
// setGitCreds configures credentials for GitHub.
func setGitCreds(githubName, githubEmail, githubUsername, accessToken string) error {
u, err := user.Current()
if err != nil {
return err
}
gitCredentials := []byte(fmt.Sprintf("https://%s:%s@github.com", githubUsername, accessToken))
if err := ioutil.WriteFile(path.Join(u.HomeDir, ".git-credentials"), gitCredentials, 0644); err != nil {
return err
}
c := execv.Command("git", "config", "--global", "user.name", githubName)
c.Env = []string{
fmt.Sprintf("PATH=%s", os.Getenv("PATH")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
fmt.Sprintf("HOME=%s", os.Getenv("HOME")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
}
if err := c.Run(); err != nil {
return err
}
c = execv.Command("git", "config", "--global", "user.email", githubEmail)
c.Env = []string{
fmt.Sprintf("PATH=%s", os.Getenv("PATH")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
fmt.Sprintf("HOME=%s", os.Getenv("HOME")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
}
return c.Run()
}
// GetRegenPR finds the first regen pull request with the given status. Accepted
// statues are: open, closed, or all.
func (gc *GithubClient) GetRegenPR(ctx context.Context, repo string, status string) (*PullRequest, error) {
log.Printf("getting %v pull requests with status %q", repo, status)
// We don't bother paginating, because it hurts our requests quota and makes
// the page slower without a lot of value.
opt := &github.PullRequestListOptions{
ListOptions: github.ListOptions{PerPage: 50},
State: status,
}
prs, _, err := gc.cV3.PullRequests.List(ctx, "googleapis", repo, opt)
if err != nil {
return nil, err
}
for _, pr := range prs {
if !strings.Contains(pr.GetTitle(), "auto-regenerate") {
continue
}
if pr.GetUser().GetLogin() != gc.Username {
continue
}
return &PullRequest{
Author: pr.GetUser().GetLogin(),
Title: pr.GetTitle(),
URL: pr.GetHTMLURL(),
Created: pr.GetCreatedAt(),
IsOpen: pr.GetState() == "open",
Number: pr.GetNumber(),
Repo: repo,
IsDraft: pr.GetDraft(),
NodeID: pr.GetNodeID(),
}, nil
}
return nil, nil
}
// CreateGenprotoPR creates a PR for a given genproto change.
//
// hasCorrespondingPR indicates that there is a corresponding google-cloud-go PR.
func (gc *GithubClient) CreateGenprotoPR(ctx context.Context, genprotoDir string, hasCorrespondingPR bool, changes []*ChangeInfo) (prNumber int, _ error) {
log.Println("creating genproto PR")
var sb strings.Builder
sb.WriteString(genprotoCommitBody)
if !hasCorrespondingPR {
sb.WriteString("\n\nThere is no corresponding google-cloud-go PR.\n")
sb.WriteString(FormatChanges(changes, false))
}
body := sb.String()
c := execv.Command("/bin/bash", "-c", `
set -ex
git config credential.helper store # cache creds from ~/.git-credentials
git branch -D $BRANCH_NAME || true
git push -d origin $BRANCH_NAME || true
git add -A
git checkout -b $BRANCH_NAME
git commit -m "$COMMIT_TITLE" -m "$COMMIT_BODY"
git push origin $BRANCH_NAME
`)
c.Env = []string{
fmt.Sprintf("PATH=%s", os.Getenv("PATH")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
fmt.Sprintf("HOME=%s", os.Getenv("HOME")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
fmt.Sprintf("COMMIT_TITLE=%s", genprotoCommitTitle),
fmt.Sprintf("COMMIT_BODY=%s", body),
fmt.Sprintf("BRANCH_NAME=%s", genprotoBranchName),
}
c.Dir = genprotoDir
if err := c.Run(); err != nil {
return 0, err
}
head := fmt.Sprintf("googleapis:" + genprotoBranchName)
base := "master"
t := genprotoCommitTitle // Because we have to take the address.
pr, _, err := gc.cV3.PullRequests.Create(ctx, "googleapis", "go-genproto", &github.NewPullRequest{
Title: &t,
Body: &body,
Head: &head,
Base: &base,
})
if err != nil {
return 0, err
}
log.Printf("creating genproto PR... done %s\n", pr.GetHTMLURL())
return pr.GetNumber(), nil
}
// CreateGocloudPR creates a PR for a given google-cloud-go change.
func (gc *GithubClient) CreateGocloudPR(ctx context.Context, gocloudDir string, genprotoPRNum int, changes []*ChangeInfo) (prNumber int, _ error) {
log.Println("creating google-cloud-go PR")
var sb strings.Builder
var draft bool
sb.WriteString(gocloudCommitBody)
if genprotoPRNum > 0 {
sb.WriteString(fmt.Sprintf("\n\nCorresponding genproto PR: https://github.com/googleapis/go-genproto/pull/%d\n", genprotoPRNum))
draft = true
} else {
sb.WriteString("\n\nThere is no corresponding genproto PR.\n")
}
sb.WriteString(FormatChanges(changes, true))
body := sb.String()
c := execv.Command("/bin/bash", "-c", `
set -ex
git config credential.helper store # cache creds from ~/.git-credentials
git branch -D $BRANCH_NAME || true
git push -d origin $BRANCH_NAME || true
git add -A
git checkout -b $BRANCH_NAME
git commit -m "$COMMIT_TITLE" -m "$COMMIT_BODY"
git push origin $BRANCH_NAME
`)
c.Env = []string{
fmt.Sprintf("PATH=%s", os.Getenv("PATH")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
fmt.Sprintf("HOME=%s", os.Getenv("HOME")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
fmt.Sprintf("COMMIT_TITLE=%s", gocloudCommitTitle),
fmt.Sprintf("COMMIT_BODY=%s", body),
fmt.Sprintf("BRANCH_NAME=%s", gocloudBranchName),
}
c.Dir = gocloudDir
if err := c.Run(); err != nil {
return 0, err
}
t := gocloudCommitTitle // Because we have to take the address.
pr, _, err := gc.cV3.PullRequests.Create(ctx, "googleapis", "google-cloud-go", &github.NewPullRequest{
Title: &t,
Body: &body,
Head: github.String(fmt.Sprintf("googleapis:" + gocloudBranchName)),
Base: github.String("master"),
Draft: github.Bool(draft),
})
if err != nil {
return 0, err
}
log.Printf("creating google-cloud-go PR... done %s\n", pr.GetHTMLURL())
return pr.GetNumber(), nil
}
// AmendGenprotoPR amends the given genproto PR with a link to the given
// google-cloud-go PR.
func (gc *GithubClient) AmendGenprotoPR(ctx context.Context, genprotoPRNum int, genprotoDir string, gocloudPRNum int, changes []*ChangeInfo) error {
var body strings.Builder
body.WriteString(genprotoCommitBody)
body.WriteString(fmt.Sprintf("\n\nCorresponding google-cloud-go PR: googleapis/google-cloud-go#%d\n", gocloudPRNum))
body.WriteString(FormatChanges(changes, false))
sBody := body.String()
c := execv.Command("/bin/bash", "-c", `
set -ex
git config credential.helper store # cache creds from ~/.git-credentials
git checkout $BRANCH_NAME
git commit --amend -m "$COMMIT_TITLE" -m "$COMMIT_BODY"
git push -f origin $BRANCH_NAME
`)
c.Env = []string{
fmt.Sprintf("PATH=%s", os.Getenv("PATH")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
fmt.Sprintf("HOME=%s", os.Getenv("HOME")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
fmt.Sprintf("COMMIT_TITLE=%s", genprotoCommitTitle),
fmt.Sprintf("COMMIT_BODY=%s", sBody),
fmt.Sprintf("BRANCH_NAME=%s", genprotoBranchName),
}
c.Dir = genprotoDir
if err := c.Run(); err != nil {
return err
}
_, _, err := gc.cV3.PullRequests.Edit(ctx, "googleapis", "go-genproto", genprotoPRNum, &github.PullRequest{
Body: &sBody,
})
return err
}
// MarkPRReadyForReview switches a draft pull request to a reviewable pull
// request.
func (gc *GithubClient) MarkPRReadyForReview(ctx context.Context, repo string, nodeID string) error {
var m struct {
MarkPullRequestReadyForReview struct {
PullRequest struct {
ID githubv4.ID
}
} `graphql:"markPullRequestReadyForReview(input: $input)"`
}
input := githubv4.MarkPullRequestReadyForReviewInput{
PullRequestID: nodeID,
}
if err := gc.cV4.Mutate(ctx, &m, input, nil); err != nil {
return err
}
return nil
}
// UpdateGocloudGoMod updates the go.mod to include latest version of genproto
// for the given gocloud ref.
func (gc *GithubClient) UpdateGocloudGoMod() error {
tmpDir, err := ioutil.TempDir("", "finalize-github-pr")
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
if err := checkoutCode(tmpDir); err != nil {
return err
}
if err := updateDeps(tmpDir); err != nil {
return err
}
if err := addAndPushCode(tmpDir); err != nil {
return err
}
return nil
}
func checkoutCode(tmpDir string) error {
c := execv.Command("/bin/bash", "-c", `
set -ex
git init
git remote add origin https://github.com/googleapis/google-cloud-go
git fetch --all
git checkout $BRANCH_NAME
`)
c.Env = []string{
fmt.Sprintf("BRANCH_NAME=%s", gocloudBranchName),
}
c.Dir = tmpDir
return c.Run()
}
func updateDeps(tmpDir string) error {
// Find directories that had code changes.
c := execv.Command("git", "diff", "--name-only", "HEAD", "HEAD~1")
c.Dir = tmpDir
out, err := c.Output()
if err != nil {
return err
}
files := strings.Split(string(out), "\n")
dirs := map[string]bool{}
for _, file := range files {
if strings.HasPrefix(file, "internal") {
continue
}
dir := filepath.Dir(file)
dirs[filepath.Join(tmpDir, dir)] = true
}
// Find which modules had code changes.
updatedModDirs := map[string]bool{}
for dir := range dirs {
modDir, err := gocmd.ListModDirName(dir)
if err != nil {
if errors.Is(err, gocmd.ErrBuildConstraint) {
continue
}
return err
}
updatedModDirs[modDir] = true
}
// Update required modules.
for modDir := range updatedModDirs {
log.Printf("Updating module dir %q", modDir)
c := execv.Command("/bin/bash", "-c", `
set -ex
go get -d google.golang.org/api | true # We don't care that there's no files at root.
go get -d google.golang.org/genproto | true # We don't care that there's no files at root.
go mod tidy
`)
c.Dir = modDir
if err := c.Run(); err != nil {
return err
}
}
return nil
}
func addAndPushCode(tmpDir string) error {
c := execv.Command("/bin/bash", "-c", `
set -ex
git add -A
filesUpdated=$( git status --short | wc -l )
if [ $filesUpdated -gt 0 ];
then
git config credential.helper store # cache creds from ~/.git-credentials
git commit --amend --no-edit
git push -f origin $BRANCH_NAME
fi
`)
c.Env = []string{
fmt.Sprintf("BRANCH_NAME=%s", gocloudBranchName),
fmt.Sprintf("PATH=%s", os.Getenv("PATH")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
fmt.Sprintf("HOME=%s", os.Getenv("HOME")), // TODO(deklerk): Why do we need to do this? Doesn't seem to be necessary in other exec.Commands.
}
c.Dir = tmpDir
return c.Run()
}