-
Notifications
You must be signed in to change notification settings - Fork 1
/
listpullreqs.go
216 lines (183 loc) · 6.26 KB
/
listpullreqs.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
/*
Copyright 2019 Cornelius Weig
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.
*/
/*****************************************************
* NOTE The original version of this script is due to
* Balint Pato and was published as part of Skaffold
* (https://github.com/GoogleContainerTools/skaffold)
* under the following license:
Copyright 2019 The Skaffold Authors
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.
*****************************************************/
// listpullreqs.go lists pull requests since the last release.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"regexp"
"syscall"
"github.com/blang/semver"
"github.com/google/go-github/v38/github"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/oauth2"
)
const (
sinceAny = "any"
sincePatch = "patch"
sinceMinor = "minor"
sinceMajor = "major"
)
var (
org string
repo string
token string
since string
// versionMatchRE matches the raw version number from a string
versionMatchRE = regexp.MustCompile(`^\s*v?(.*)$`)
)
const longDescription = `The script uses the GitHub API to retrieve a list of all merged pull
requests since the last release. The found pull requests are then
printed as markdown changelog with their commit summary and a link
to the pull request on GitHub.`
var rootCmd = &cobra.Command{
Use: "release-notes {org} {repo}",
Example: "release-notes GoogleContainerTools skaffold",
Short: "Generate a markdown changelog of merged pull requests since last release",
Long: longDescription,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
org, repo = args[0], args[1]
printPullRequests()
},
}
func main() {
rootCmd.Flags().StringVar(&token, "token", "", "Specify personal Github Token if you are hitting a rate limit anonymously. https://github.com/settings/tokens")
rootCmd.Flags().StringVar(&since, "since", "patch", "The previous tag up to which PRs should be collected (one of any, patch, minor, major, or a valid semver) [defaults to 'patch']")
if err := rootCmd.Execute(); err != nil {
logrus.Fatal(err)
}
}
func printPullRequests() {
ctx := contextWithCtrlCHandler()
client := getClient(ctx)
lastRelease, err := fetchLastRelease(ctx, client)
if err != nil {
logrus.Fatal(err)
}
lastReleaseTime := lastRelease.GetPublishedAt().Time
fmt.Fprintf(os.Stderr, "Collecting pull request that were merged since the last release: %s (%s)\n", lastRelease.GetTagName(), lastReleaseTime)
for page := 1; page != 0; {
pullRequests, resp, err := client.PullRequests.List(ctx, org, repo, &github.PullRequestListOptions{
State: "closed",
Sort: "updated",
Direction: "desc",
ListOptions: github.ListOptions{
PerPage: 20,
Page: page,
},
})
if err != nil {
logrus.Fatalf("Failed to list pull requests: %v", err)
}
page = resp.NextPage
for idx := range pullRequests {
pr := pullRequests[idx]
if pr.GetUpdatedAt().Before(lastReleaseTime) {
page = 0 // we are done now
break
}
if pr.MergedAt != nil && pr.MergedAt.After(lastReleaseTime) {
fmt.Printf("* %s [#%d](https://github.com/%s/%s/pull/%d)\n", pr.GetTitle(), pr.GetNumber(), org, repo, pr.GetNumber())
}
}
}
}
func fetchLastRelease(ctx context.Context, client *github.Client) (*github.RepositoryRelease, error) {
releases, _, err := client.Repositories.ListReleases(ctx, org, repo, &github.ListOptions{})
if err != nil {
return nil, errors.Wrapf(err, "failed to list releases")
}
matches, err := toVersionMatcher(since)
if err != nil {
return nil, err
}
for _, release := range releases {
version, err := parseSemver(release.GetTagName())
if err != nil {
return nil, err
}
if matches(version) {
return release, nil
}
}
return nil, fmt.Errorf("no previous release found tag %s/%s", org, repo)
}
func toVersionMatcher(since string) (func(semver.Version) bool, error) {
// magic version specifiers
switch since {
case sinceAny:
return func(_ semver.Version) bool { return true }, nil
case sincePatch:
return func(v semver.Version) bool { return len(v.Pre) == 0 }, nil
case sinceMinor:
return func(v semver.Version) bool { return v.Patch == 0 && len(v.Pre) == 0 }, nil
case sinceMajor:
return func(v semver.Version) bool { return v.Minor == 0 && v.Patch == 0 && len(v.Pre) == 0 }, nil
}
previousVersion, err := parseSemver(since)
if err != nil {
return nil, errors.Wrapf(err, "could not parse semver %q", since)
}
return previousVersion.GTE, nil
}
func parseSemver(tagName string) (semver.Version, error) {
parts := versionMatchRE.FindStringSubmatch(tagName)
if parts == nil {
return semver.Version{}, fmt.Errorf("%q does not look like a version string", tagName)
}
version, err := semver.Parse(parts[1])
return version, errors.Wrapf(err, "could not parse as semver")
}
func getClient(ctx context.Context) *github.Client {
if len(token) == 0 {
return github.NewClient(nil)
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
return github.NewClient(tc)
}
func contextWithCtrlCHandler() context.Context {
ctx, cancel := context.WithCancel(context.Background())
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT, syscall.SIGPIPE)
go func() {
<-sigs
signal.Stop(sigs)
cancel()
logrus.Infof("Aborted.")
}()
return ctx
}