-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
335 lines (273 loc) · 8.27 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
// Copyright 2021 FerretDB Inc.
//
// 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 main
import (
"context"
"encoding/hex"
"errors"
"flag"
"fmt"
"regexp"
"strings"
"text/tabwriter"
"unicode/utf8"
"github.com/google/go-github/v57/github"
"github.com/jdkato/prose/v2"
"github.com/sethvargo/go-githubactions"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"github.com/FerretDB/github-actions/internal"
"github.com/FerretDB/github-actions/internal/graphql"
)
func main() {
flag.Parse()
ctx := context.Background()
action := githubactions.New()
gClient := graphql.NewClient(ctx, action, "CONFORM_TOKEN")
internal.DebugEnv(action)
event, err := internal.ReadEvent(action)
if err != nil {
action.Errorf("Failed to read event: %s.", err)
}
prEvent, ok := event.(*github.PullRequestEvent)
if !ok {
action.Fatalf("Unexpected event type: %T.", event)
}
c := &checker{
action: action,
gClient: gClient,
}
results, community := c.runChecks(
ctx,
*prEvent.Organization.Login, *prEvent.PullRequest.User.Login, *prEvent.PullRequest.NodeID,
)
var buf strings.Builder
w := tabwriter.NewWriter(&buf, 1, 1, 1, ' ', tabwriter.Debug)
fmt.Fprintf(w, "\tCheck\tStatus\t\n")
fmt.Fprintf(w, "\t-----\t------\t\n")
conform := true
for _, res := range results {
status := "✅"
if res.err != nil {
status = "❌ " + res.err.Error()
conform = false
}
fmt.Fprintf(w, "\t%s\t%s\t\n", res.check, status)
}
w.Flush()
action.AddStepSummary(buf.String())
action.Infof("%s", buf.String())
if !conform {
if community {
action.Fatalf("Maintainers will update that PR to conform to the project's standards.")
}
action.Fatalf("PR does not conform to the project's standards.")
}
}
// checker holds state shared by all checks.
type checker struct {
action *githubactions.Action
gClient *graphql.Client
}
// checkResult is a result of a single check.
type checkResult struct {
check string
err error
}
// runChecks runs all the checks for the given PR.
//
// It returns check results and a flag indicating if the PR is from the community (true if yet).
func (c *checker) runChecks(ctx context.Context, org, user, nodeID string) ([]checkResult, bool) {
// Do less API calls and be nice to dependabot's compatibility scoring feature:
// https://docs.github.com/en/code-security/dependabot/dependabot-security-updates/about-dependabot-security-updates#about-compatibility-scores
//nolint:lll // that URL is long
if user == "dependabot[bot]" {
return nil, false
}
_, maintainer := maintainers[user]
community := !maintainer
pr := c.gClient.GetPullRequest(ctx, nodeID)
var res []checkResult
for _, err := range checkLabels(c.action, pr.Labels) {
res = append(res, checkResult{
check: "Labels",
err: err,
})
}
if res == nil {
res = append(res, checkResult{
check: "Labels",
})
}
res = append(res, checkResult{
check: "Size",
err: checkSize(c.action, pr.ProjectFields),
})
res = append(res, checkResult{
check: "Sprint",
err: checkSprint(c.action, pr.ProjectFields, community),
})
res = append(res, checkResult{
check: "Title",
err: checkTitle(c.action, pr.Title),
})
res = append(res, checkResult{
check: "Body",
err: checkBody(c.action, pr.Body),
})
res = append(res, checkResult{
check: "Auto-merge",
err: checkAutoMerge(c.action, pr, community),
})
return res, community
}
// checkLabels checks if PR's labels are valid.
func checkLabels(_ *githubactions.Action, labels []string) []error {
var res []error
if slices.Contains(labels, "do not merge") {
res = append(res, fmt.Errorf("That PR should not be merged yet."))
}
if slices.Contains(labels, "not ready") {
res = append(res, fmt.Errorf("That PR can't be merged yet; remove `not ready` label."))
}
var incorrect []string
for _, l := range labels {
switch {
case l == "badly estimated":
case l == "good first issue":
case l == "help wanted":
case l == "scope changed":
case strings.HasPrefix(l, "area/"):
case strings.HasPrefix(l, "backend/"):
default:
continue
}
incorrect = append(incorrect, l)
}
if incorrect != nil {
res = append(res, fmt.Errorf("Those labels should not be applied to PRs: %s.", strings.Join(incorrect, ", ")))
}
var found bool
required := []string{
"blog/engineering",
"blog/marketing",
"code/bug",
"code/bug-regression",
"code/chore",
"code/enhancement",
"code/feature",
"deps",
"documentation",
"project",
}
for _, l := range required {
if slices.Contains(labels, l) {
found = true
}
}
if !found {
res = append(res, fmt.Errorf(
"PR must have at least one of those labels:<br />%s.",
strings.Join(required, ", "),
))
}
return res
}
// checkSize checks that PR has a "Size" field unset.
func checkSize(_ *githubactions.Action, projectFields map[string]graphql.Fields) error {
// sort projects to make results stable
projects := maps.Keys(projectFields)
slices.Sort(projects)
var got []string
for _, project := range projects {
if size := projectFields[project]["Size"]; size != "" {
got = append(got, fmt.Sprintf("%q for project %q", size, project))
}
}
if got != nil {
return fmt.Errorf(`PR should have "Size" field unset, got %s.`, strings.Join(got, ", "))
}
return nil
}
// checkSprint checks that PR has a "Sprint" field set.
func checkSprint(_ *githubactions.Action, projectFields map[string]graphql.Fields, community bool) error {
// sort projects to make results stable
projects := maps.Keys(projectFields)
slices.Sort(projects)
for _, project := range projects {
if sprint := projectFields[project]["Sprint"]; sprint != "" {
return nil
}
}
msg := `PR should have "Sprint" field set.`
if community {
msg += ` Don't worry, maintainers will set it for you.`
}
return errors.New(msg)
}
// checkTitle checks if PR's title does not end with dot
// and also check if it starts with an imperative verb.
func checkTitle(_ *githubactions.Action, title string) error {
uppercaseRegexp := regexp.MustCompile("^[A-Z]+")
if match := uppercaseRegexp.MatchString(title); !match {
return fmt.Errorf("PR title must start with an uppercase letter.")
}
titleRegexp := regexp.MustCompile("[a-zA-Z0-9`'\"]$")
if match := titleRegexp.MatchString(title); !match {
return fmt.Errorf("PR title must end with a latin letter or digit.")
}
firstWord := strings.Split(title, " ")[0]
doc, err := prose.NewDocument("I " + firstWord)
if err != nil {
return fmt.Errorf("error parsing PR title.")
}
tokens := doc.Tokens()
tok := tokens[1]
// imperative verbs have "VBP" tag
// https://github.com/jdkato/prose/tree/v2#tagging
if tok.Tag != "VBP" {
return fmt.Errorf("PR title must start with an imperative verb (got %q).", tok.Tag)
}
if utf8.RuneCountInString(title) > 72 {
return fmt.Errorf("PR title must not longer than 72 unicode runes")
}
return nil
}
// checkBody checks if PR's body (description) ends with a punctuation mark.
func checkBody(action *githubactions.Action, body string) error {
action.Debugf("checkBody:\n%s", hex.Dump([]byte(body)))
// it does not seem to be documented, but PR bodies use CRLF instead of LF for line breaks
body = strings.ReplaceAll(body, "\r\n", "\n")
// it is allowed to have a completely empty body
if len(body) == 0 {
return nil
}
bodyRegexp := regexp.MustCompile(".+[.!?](\n)?$")
// one \n at the end is allowed, but optional
if match := bodyRegexp.MatchString(body); !match {
return fmt.Errorf("PR body must end with dot or other punctuation mark.")
}
return nil
}
// checkAutoMerge checks if PR's auto-merge is enabled.
func checkAutoMerge(_ *githubactions.Action, pr *graphql.PullRequest, community bool) error {
if pr.Closed || pr.AutoMerge {
return nil
}
msg := `PR should have auto-merge enabled.`
if community {
msg += ` Don't worry, maintainers will enable it for you.`
}
return errors.New(msg)
}