/
main.go
345 lines (320 loc) · 8.4 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
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
package main
import (
"bytes"
"context"
"fmt"
"log"
"net/http"
"os"
"os/user"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"text/template"
"time"
"github.com/BurntSushi/toml"
"github.com/Songmu/prompter"
"github.com/google/go-github/v27/github"
"github.com/kelseyhightower/envconfig"
homedir "github.com/mitchellh/go-homedir"
flag "github.com/spf13/pflag"
"go.uber.org/multierr"
"golang.org/x/oauth2"
"gopkg.in/go-playground/validator.v9"
)
const (
appName = "gh-pr-release"
envPrefix = "gh_pr_release"
title = `Release {{.ReleaseAt.Format "2006-01-02 15:04:05 -0700"}}`
body = `{{ range .PullRequests }}* [{{if .Checked}}x{{else}} {{end}}] #{{ .Number }} {{ .Title }}
{{ end }}`
)
var (
configHomePath string
globalConfigPath string
debug = flag.Bool("debug", false, "print debug information")
configPath = flag.String("config", fmt.Sprintf("%s.toml", appName), "configuration file path")
)
func init() {
configHomePath := os.Getenv("XDG_CONFIG_HOME")
if configHomePath == "" {
homeDir, err := homedir.Dir()
if err != nil {
log.Fatal(err)
}
configHomePath = filepath.Join(homeDir, ".config")
}
globalConfigPath = filepath.Join(configHomePath, appName, "config.toml")
}
type Config struct {
Token string `validate:"-"`
Owner string `validate:"required"`
Repo string `validate:"required"`
Base string `validate:"required"`
Head string `validate:"required"`
Title string `validate:"required"`
Body string `validate:"required"`
}
func loadConfig(localConfigPath string) (cfg Config, err error) {
cfg = Config{
Base: "master",
Head: "develop",
Title: title,
Body: body,
}
for _, path := range []string{globalConfigPath, localConfigPath} {
_, err = toml.DecodeFile(path, &cfg)
if os.IsNotExist(err) {
continue
}
if err != nil {
return
}
}
if err = envconfig.Process(envPrefix, &cfg); err != nil {
return
}
return
}
func createToken(ctx context.Context) (string, error) {
defaultUsername := ""
u, err := user.Current()
if err == nil {
defaultUsername = u.Username
}
username := prompter.Prompt("Username", defaultUsername)
password := prompter.Password("Password")
// Create a new client using HTTP Basic Authentication to create new GitHub API Token
basicAuth := github.BasicAuthTransport{
Username: username,
Password: password,
}
client := github.NewClient(basicAuth.Client())
note := appName
authReq := &github.AuthorizationRequest{
Scopes: []github.Scope{github.ScopeRepo},
Note: ¬e,
}
auth, res, err := client.Authorizations.Create(ctx, authReq)
if res.StatusCode == http.StatusUnauthorized && strings.Contains(res.Header.Get("x-github-otp"), "required") {
// Retry with two-factor authentication OTP code.
basicAuth.OTP = prompter.Prompt("Two-factor authentication OTP code", "")
client = github.NewClient(basicAuth.Client())
auth, res, err = client.Authorizations.Create(ctx, authReq)
}
if err != nil {
return "", err
}
return auth.GetToken(), nil
}
func exists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
func saveToken(token string) (err error) {
var (
f *os.File
toml string
)
if exists(globalConfigPath) {
f, err = os.OpenFile(globalConfigPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
return err
}
toml = "\n"
} else {
if !exists(configHomePath) {
err = os.MkdirAll(filepath.Dir(globalConfigPath), os.ModePerm)
if err != nil {
return
}
}
f, err = os.Create(globalConfigPath)
if err != nil {
return
}
}
defer func() {
err = multierr.Append(err, f.Close())
}()
toml += "token = %q\n"
_, err = fmt.Fprintf(f, toml, token)
return
}
type PullRequest struct {
*github.PullRequest
Checked bool
}
func renderTemplate(name, text string, cfg Config, releaseAt time.Time, pullRequests []PullRequest) (string, error) {
pr := struct {
Config
ReleaseAt time.Time
PullRequests []PullRequest
}{
Config: cfg,
ReleaseAt: releaseAt,
PullRequests: pullRequests,
}
tmpl, err := template.New(name).Parse(text)
if err != nil {
return "", err
}
buf := bytes.NewBuffer(nil)
err = tmpl.Execute(buf, pr)
if err != nil {
return "", err
}
return buf.String(), nil
}
func mergedPullRequests(ctx context.Context, cfg Config, client *github.Client) ([]*github.PullRequest, error) {
// List merged pull requests into the base branch
comparison, _, err := client.Repositories.CompareCommits(context.Background(), cfg.Owner, cfg.Repo, cfg.Base, cfg.Head)
if err != nil {
return nil, err
}
hashes := map[string]bool{}
for _, c := range comparison.Commits {
if c.SHA != nil {
hashes[*c.SHA] = true
}
}
mergedPRs := []*github.PullRequest{}
opt := &github.PullRequestListOptions{
State: "closed",
Base: cfg.Head,
Sort: "created",
Direction: "desc",
ListOptions: github.ListOptions{
PerPage: 100,
},
}
for {
prs, resp, err := client.PullRequests.List(context.Background(), cfg.Owner, cfg.Repo, opt)
if err != nil {
return nil, err
}
for _, pr := range prs {
if pr.MergeCommitSHA != nil && hashes[*pr.MergeCommitSHA] {
mergedPRs = append(mergedPRs, pr)
delete(hashes, *pr.MergeCommitSHA)
}
}
if len(hashes) == 0 || resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
sort.Slice(mergedPRs, func(i, j int) bool {
return mergedPRs[i].GetNumber() < mergedPRs[j].GetNumber()
})
return mergedPRs, nil
}
func main() {
flag.Parse()
if *debug {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
} else {
log.SetFlags(0)
}
// Load configuration
cfg, err := loadConfig(*configPath)
if err != nil {
log.Fatal(err)
}
validate := validator.New()
if err := validate.Struct(&cfg); err != nil {
log.Fatal(err)
}
if cfg.Token == "" {
log.Println("Could not obtain GitHub API token.")
log.Println("Trying to create new token...")
token, err := createToken(context.Background())
if err != nil {
log.Fatal(err)
}
if err := saveToken(token); err != nil {
log.Fatal(err)
}
cfg.Token = token
}
// Create a new client of github api with the api token
tc := oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: cfg.Token},
))
client := github.NewClient(tc)
// List pull requests which merged into the head branch
mergedPRs, err := mergedPullRequests(context.Background(), cfg, client)
if err != nil {
log.Fatal(err)
}
if len(mergedPRs) == 0 {
log.Println("No pull requests to be released")
return
}
for _, pr := range mergedPRs {
log.Printf("To be released: #%d %s", pr.GetNumber(), pr.GetTitle())
}
// Find the release pull request
prs, _, err := client.PullRequests.List(context.Background(), cfg.Owner, cfg.Repo, &github.PullRequestListOptions{
State: "open",
Base: cfg.Base,
Head: fmt.Sprintf("%s:%s", cfg.Owner, cfg.Head),
})
if err != nil {
log.Fatal(err)
}
var releasePR *github.PullRequest
if len(prs) > 0 {
releasePR = prs[0]
}
checked := map[int]bool{}
if releasePR != nil {
log.Printf("An existing release pull request #%d found", releasePR.GetNumber())
reg := regexp.MustCompile(`(-|\*) *\[x\] *\#(\d+)`)
for _, groups := range reg.FindAllStringSubmatch(releasePR.GetBody(), -1) {
n, _ := strconv.Atoi(groups[2])
checked[n] = true
}
}
// Create title and body of the release pull request
releaseAt := time.Now()
pullRequests := []PullRequest{}
for _, pr := range mergedPRs {
pullRequests = append(pullRequests, PullRequest{
PullRequest: pr,
Checked: checked[pr.GetNumber()],
})
}
title, err := renderTemplate("title", cfg.Title, cfg, releaseAt, pullRequests)
if err != nil {
log.Fatal(err)
}
body, err := renderTemplate("body", cfg.Body, cfg, releaseAt, pullRequests)
if err != nil {
log.Fatal(err)
}
if releasePR != nil {
// Update an existing pull request
releasePR.Title = &title
releasePR.Body = &body
_, _, err := client.PullRequests.Edit(context.Background(), cfg.Owner, cfg.Repo, releasePR.GetNumber(), releasePR)
if err != nil {
log.Fatal(err)
}
log.Printf("Updated pull request #%d: %s", releasePR.GetNumber(), releasePR.GetURL())
} else {
// Create a new release pull request
releasePR, _, err := client.PullRequests.Create(context.Background(), cfg.Owner, cfg.Repo, &github.NewPullRequest{
Title: &title,
Body: &body,
Head: &cfg.Head,
Base: &cfg.Base,
})
if err != nil {
log.Fatal(err)
}
log.Printf("Created pull request #%d: %s", releasePR.GetNumber(), releasePR.GetURL())
}
}