-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
301 lines (259 loc) · 7.23 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
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"text/template"
"time"
"github.com/google/go-github/v43/github"
"gitlab.com/golang-commonmark/markdown"
"golang.org/x/oauth2"
)
var rnTemplate = `## {{.Title}}
Released on {{.DateString}}
{{""}}
{{- if .Description}}
{{.Description}}
{{end}}
{{- if .Features }}
### New Features {#new-features-{{.TitleDash}}}
{{- range .Features}}
* {{.}}.
{{- end}}
{{end}}
{{- if .Improvements }}
### Improvements {#improvements-{{.TitleDash}}}
{{- range .Improvements}}
* {{.}}.
{{- end}}
{{end}}
{{- if .Bugs }}
### Bug Fixes {#bug-fixes-{{.TitleDash}}}
{{- range .Bugs}}
* {{.}}.
{{- end}}
{{end}}`
const GithubAuthTokenEnvironmentVarName = "GITHUB_AUTH_TOKEN"
type ReleaseNotes struct {
Title string
TitleDash string
DateString string
Description string
Features []string
Improvements []string
Bugs []string
}
func main() {
var ownerRepo string
var base string
var head string
var title string
var description string
var includePrLinks bool
flag.StringVar(&ownerRepo, "owner-repo", "", "The owner/repo of the Github repository to be used (required)")
flag.StringVar(&base, "base", "", "Base of release notes diff (defaults to the last non-prerelease tag)")
flag.StringVar(&head, "head", "", "Head of release notes diff (required)")
flag.StringVar(&title, "title", "", "The release notes title")
flag.StringVar(&description, "description", "", "Description to be added to the release notes (optional)")
flag.BoolVar(&includePrLinks, "include-pr-links", false, "Include links back to pull requests")
typeLabelFlags := NewTypeLabelFlags(flag.CommandLine)
flag.Parse()
typeLabelFlags.Parse()
var httpClient *http.Client
// if we have a token, use it to authenticate to prevent rate limiting
if token, ok := os.LookupEnv(GithubAuthTokenEnvironmentVarName); ok {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
httpClient = oauth2.NewClient(context.Background(), ts)
} else {
fmt.Fprintf(os.Stderr, "WARNING: No %s environment variable found, rate limiting may occur\n", GithubAuthTokenEnvironmentVarName)
}
ownerRepoParts := strings.Split(ownerRepo, "/")
if len(ownerRepoParts) != 2 {
log.Fatalf("Wrong number of parts in %s", ownerRepo)
}
owner := ownerRepoParts[0]
repo := ownerRepoParts[1]
client := github.NewClient(httpClient)
ctx := context.Background()
// get the latest released version if we don't have a base
if base == "" {
latest, err := getLatestReleasedVersion(ctx, client, owner, repo)
if err != nil {
log.Fatalf("Failed to get latest released version: %v", err)
}
base = latest
}
notes, err := getAllReleaseNotes(ctx, client, owner, repo, base, head, includePrLinks, typeLabelFlags)
// if the release notes do not contain any features, improvements, or bugs, do not submit release notes
if len(notes.Features) == 0 && len(notes.Improvements) == 0 && len(notes.Bugs) == 0 {
return
}
if err != nil {
log.Fatalf("Failed to get release notes: %v", err)
}
notes.Title = title
notes.TitleDash = strings.ReplaceAll(notes.Title, ".", "-")
notes.DateString = time.Now().Format("January 2, 2006")
notes.Description = strings.ReplaceAll(description, "`", "\\`") // escape backticks
t := template.Must(template.New("template").Parse(rnTemplate))
err = t.Execute(os.Stdout, notes)
if err != nil {
log.Fatalf("Failed to execute template: %v", err)
}
}
func getLatestReleasedVersion(ctx context.Context, client *github.Client, owner string, repo string) (string, error) {
var releases []*github.RepositoryRelease
listOptions := github.ListOptions{
Page: 1,
PerPage: 100,
}
releases, response, err := client.Repositories.ListReleases(ctx, owner, repo, &listOptions)
if err != nil {
return "", err
}
if response.StatusCode != 200 {
return "", fmt.Errorf("unexpected status code when listing releases: %d", response.StatusCode)
}
latest := ""
for _, rel := range releases {
if !*rel.Prerelease {
latest = rel.GetTagName()
break
}
}
return latest, nil
}
func getAllReleaseNotes(ctx context.Context, client *github.Client, owner, repo, base, head string, includePrLinks bool, typeLabelFlags *TypeLabelFlags) (*ReleaseNotes, error) {
var commits []*github.RepositoryCommit
listOptions := github.ListOptions{
Page: 0,
PerPage: 100,
}
for {
cmp, response, err := client.Repositories.CompareCommits(
ctx,
owner,
repo,
base,
head,
&listOptions,
)
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
return nil, fmt.Errorf("unexpected status code when getting commits: %d", response.StatusCode)
}
if len(cmp.Commits) > 0 {
commits = append(commits, cmp.Commits...)
}
if response.NextPage == 0 {
break
}
listOptions.Page = response.NextPage
}
// Picks up merge commits and squash-merged PRs
r := regexp.MustCompile(`#(\d{1,5})`)
prsToCheck := []string{}
for _, commit := range commits {
matches := r.FindStringSubmatch(*commit.Commit.Message)
if len(matches) > 1 {
prsToCheck = append(prsToCheck, matches[1])
}
}
releaseNotes := ReleaseNotes{
Features: []string{},
Improvements: []string{},
Bugs: []string{},
}
for _, prToCheck := range prsToCheck {
prNumber, err := strconv.Atoi(prToCheck)
if err != nil {
return nil, err
}
pr, resp, err := client.PullRequests.Get(
ctx,
owner,
repo,
prNumber,
)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("unexpected status code when getting PR: %d", resp.StatusCode)
}
if pr.Body == nil {
continue
}
notes := getReleaseNotes(*pr.Body)
if len(notes) == 0 {
continue
}
for _, note := range notes {
note = cleanReleaseNote(note)
if strings.EqualFold(note, "NONE") {
continue
}
if includePrLinks {
note = fmt.Sprintf("[#%d](%s) %s", prNumber, *pr.HTMLURL, note)
}
noteType := typeLabelFlags.GetNoteTypeFromLabels(pr.Labels)
switch noteType {
case "feature":
releaseNotes.Features = append(releaseNotes.Features, note)
case "improvement":
releaseNotes.Improvements = append(releaseNotes.Improvements, note)
case "bug":
releaseNotes.Bugs = append(releaseNotes.Bugs, note)
}
}
}
return &releaseNotes, nil
}
func getReleaseNotes(raw string) []string {
md := markdown.New()
tokens := md.Parse([]byte(raw))
for _, t := range tokens {
snippet := getSnippet(t)
snippet.content = strings.TrimSpace(snippet.content)
if snippet.content != "" && snippet.lang == "release-note" {
notes := strings.Split(snippet.content, "\n")
return notes
}
}
return []string{}
}
// snippet represents the snippet we will output.
type snippet struct {
content string
lang string
}
// getSnippet extract only code snippet from markdown object.
func getSnippet(tok markdown.Token) snippet {
switch tok := tok.(type) {
case *markdown.Fence:
return snippet{
tok.Content,
tok.Params,
}
}
return snippet{}
}
func cleanReleaseNote(note string) string {
note = strings.TrimSpace(note)
note = strings.TrimPrefix(note, "-")
note = strings.TrimPrefix(note, "*")
note = strings.TrimSuffix(note, ".")
note = strings.TrimSpace(note)
note = strings.ReplaceAll(note, "`", "\\`") // escape backticks
return note
}