/
main.go
212 lines (184 loc) · 5.56 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"path"
"time"
"github.com/google/go-github/github"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/config"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/plumbing/transport/http"
client "github.com/mattmoor/bindings/pkg/github"
"github.com/mattmoor/knobots/pkg/comment"
)
func must(s string, err error) string {
if err != nil {
panic(err)
}
return s
}
var (
username = must(client.ReadKey("username"))
password = must(client.AccessToken())
workspace = flag.String("workspace", "", "The workspace directory to turn into a PR")
owner = flag.String("organization", "", "The Github organization to which we're sending a PR")
repo = flag.String("repository", "", "The Github repository to which we're sending a PR")
branch = flag.String("branch", "master", "The branch we are building a PR against.")
// TODO(mattmoor): Figure out how to dodge CLA bot...
signature = &object.Signature{
Name: "Matt Moore (via sockpuppet)",
Email: "mattmoor@vmware.com",
When: time.Now(),
}
title = flag.String("title", "", "The title of the PR to send.")
body = flag.String("body", "", "The body of the PR to send.")
token = flag.String("token", "", "The random token for identifying this PR's provenance.")
)
func main() {
flag.Parse()
// Clean up older PRs as the first thing we do so that if the latest batch of
// changes needs nothing we don't leave old PRs around.
err := cleanupOlderPRs(*title, *owner, *repo)
if err != nil {
log.Fatalf("Error cleaning up PRs: %v", err)
}
r, err := git.PlainOpen(*workspace)
if err != nil {
log.Fatalf("Error opening /workspace: %v", err)
}
// First, build the worktree.
wt, err := r.Worktree()
if err != nil {
log.Fatalf("Error fetching worktree: %v", err)
}
// Check the status of the worktree, and if there aren't any changes
// bail out we're done.
st, err := wt.Status()
if err != nil {
log.Fatalf("Error fetching worktree status: %v", err)
}
if len(st) == 0 {
log.Println("No changes")
return
}
// Display any changed we do find: `git status --porcelain`
log.Printf("%v", st)
nonGopkgCount := 0
for p := range st {
if path.Base(p) != "Gopkg.lock" {
nonGopkgCount++
}
_, err = wt.Add(p)
if err != nil {
log.Fatalf("Error staging %q: %v", p, err)
}
}
if nonGopkgCount == 0 {
log.Println("Only Gopkg.lock files changed (skipping PR).")
return
}
commitMessage := *title + "\n\n" + *body
// Commit the staged changes to the repo.
if _, err := wt.Commit(commitMessage, &git.CommitOptions{Author: signature}); err != nil {
log.Fatalf("Error committing changes: %v", err)
}
// We use the pod name (injected by downward API) as the
// branch name so that it is pseudo-randomized and so that
// we can trace opened PRs back to logs.
branchName := os.Getenv("POD_NAME")
// Create and checkout a new branch from the commit of the HEAD reference.
// This should be roughly equivalent to `git checkout -b {new-branch}`
headRef, err := r.Head()
if err != nil {
log.Fatalf("Error fetching workspace HEAD: %v", err)
}
newBranchName := plumbing.NewBranchReferenceName(branchName)
if err := wt.Checkout(&git.CheckoutOptions{
Hash: headRef.Hash(),
Branch: newBranchName,
Create: true,
Force: true,
}); err != nil {
log.Fatalf("Error checkout out new branch: %v", err)
}
// Push the branch to a remote to which we have write access.
// TODO(mattmoor): What if the fork doesn't exist, or has another name?
remote, err := r.CreateRemote(&config.RemoteConfig{
Name: username,
URLs: []string{fmt.Sprintf("https://github.com/%s/%s.git", username, *repo)},
})
if err != nil {
log.Fatalf("Error creating new remote: %v", err)
}
// Publish all local branches to the remote.
rs := config.RefSpec(fmt.Sprintf("%s:%s", newBranchName, newBranchName))
err = remote.Push(&git.PushOptions{
RemoteName: username,
RefSpecs: []config.RefSpec{rs},
Auth: &http.BasicAuth{
Username: username, // This can be anything.
Password: password,
},
})
if err != nil {
log.Fatalf("Error pushing to remote: %v", err)
}
ctx := context.Background()
ghc, err := client.New(ctx)
if err != nil {
log.Fatalf("Error creating github client: %v", err)
}
// Head has the form source-owner:branch, per the Github API docs.
head := fmt.Sprintf("%s:%s", username, branchName)
// Inject the token (if specified) into the body of the PR, so
// that we can identify it's provenance.
bodyWithToken := comment.WithSignature(*token, *body)
pr, _, err := ghc.PullRequests.Create(ctx, *owner, *repo, &github.NewPullRequest{
Title: title,
// Inject a signature into the body that will help us clean up matching older PRs.
Body: comment.WithSignature(*title, *bodyWithToken),
Head: &head,
Base: branch,
})
if err != nil {
log.Fatalf("Error creating PR: %v", err)
}
log.Printf("Created PR: #%d", pr.GetNumber())
}
func cleanupOlderPRs(name, owner, repo string) error {
ctx := context.Background()
ghc, err := client.New(ctx)
if err != nil {
return err
}
closed := "closed"
lopt := &github.PullRequestListOptions{
Base: *branch,
}
for {
prs, resp, err := ghc.PullRequests.List(ctx, owner, repo, lopt)
if err != nil {
return err
}
for _, pr := range prs {
if comment.HasSignature(name, pr.GetBody()) {
_, _, err := ghc.PullRequests.Edit(ctx, owner, repo, pr.GetNumber(), &github.PullRequest{
State: &closed,
})
if err != nil {
return err
}
}
}
if resp.NextPage == 0 {
break
}
lopt.Page = resp.NextPage
}
return nil
}