-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcheck.go
More file actions
582 lines (495 loc) · 17 KB
/
check.go
File metadata and controls
582 lines (495 loc) · 17 KB
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package main
import (
"bufio"
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"os"
"regexp"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/google/go-github/v56/github"
"github.com/haproxytech/check-commit/v5/junit"
gitlab "gitlab.com/gitlab-org/api/client-go"
git "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/format/diff"
"github.com/go-git/go-git/v5/plumbing/object"
"golang.org/x/oauth2"
yaml "gopkg.in/yaml.v3"
)
type patchTypeT struct {
Values []string `yaml:"Values"`
Scope string `yaml:"Scope"`
}
type tagAlternativesT struct {
PatchTypes []string `yaml:"PatchTypes"`
Optional bool `yaml:"Optional"`
}
type CommitPolicyConfig struct {
PatchScopes map[string][]string `yaml:"PatchScopes"`
PatchTypes map[string]patchTypeT `yaml:"PatchTypes"`
TagOrder []tagAlternativesT `yaml:"TagOrder"`
HelpText string `yaml:"HelpText"`
}
const (
defaultConfig = `
---
HelpText: "Please refer to https://github.com/haproxy/haproxy/blob/master/CONTRIBUTING#L632"
PatchScopes:
HAProxy Standard Scope:
- MINOR
- MEDIUM
- MAJOR
- CRITICAL
PatchTypes:
HAProxy Standard Patch:
Values:
- BUG
- BUILD
- CLEANUP
- DOC
- LICENSE
- OPTIM
- RELEASE
- REORG
- TEST
- REVERT
Scope: HAProxy Standard Scope
HAProxy Standard Feature Commit:
Values:
- MINOR
- MEDIUM
- MAJOR
- CRITICAL
TagOrder:
- PatchTypes:
- HAProxy Standard Patch
- HAProxy Standard Feature Commit
`
MINSUBJECTPARTS = 3
MAXSUBJECTPARTS = 15
MINSUBJECTLEN = 15
MAXSUBJECTLEN = 100
GITHUB = "Github"
GITLAB = "Gitlab"
LOCAL = "local"
)
var ErrSubjectMessageFormat = errors.New("invalid subject message format")
func checkSubjectText(subject string, junitSuite junit.Interface) error {
subjectLen := utf8.RuneCountInString(subject)
subjectParts := strings.Fields(subject)
subjectPartsLen := len(subjectParts)
if subject != strings.Join(subjectParts, " ") {
junitSuite.AddMessageFailed(ErrSubjectMessageFormat.Error(), "malformatted subject string (trailing or double spaces?)", fmt.Sprintf("subject: %s", subject))
return fmt.Errorf(
"malformatted subject string (trailing or double spaces?): '%s' (%w)",
subject, ErrSubjectMessageFormat)
}
if subjectPartsLen < MINSUBJECTPARTS || subjectPartsLen > MAXSUBJECTPARTS {
junitSuite.AddMessageFailed(
ErrSubjectMessageFormat.Error(),
fmt.Sprintf("subject word count out of bounds [words %d < %d < %d]", MINSUBJECTPARTS, subjectPartsLen, MAXSUBJECTPARTS),
fmt.Sprintf("subject: %s", subject))
return fmt.Errorf(
"subject word count out of bounds [words %d < %d < %d] '%s': %w",
MINSUBJECTPARTS, subjectPartsLen, MAXSUBJECTPARTS, subjectParts, ErrSubjectMessageFormat)
}
if subjectLen < MINSUBJECTLEN || subjectLen > MAXSUBJECTLEN {
junitSuite.AddMessageFailed(
ErrSubjectMessageFormat.Error(),
fmt.Sprintf("subject length out of bounds [len %d < %d < %d]", MINSUBJECTLEN, subjectLen, MAXSUBJECTLEN),
fmt.Sprintf("subject: %s", subject))
return fmt.Errorf(
"subject length out of bounds [len %d < %d < %d] '%s': %w",
MINSUBJECTLEN, subjectLen, MAXSUBJECTLEN, subject, ErrSubjectMessageFormat)
}
return nil
}
func (c CommitPolicyConfig) CheckPatchTypes(tag, severity string, patchTypeName string) bool {
tagScopeOK := false
for _, allowedTag := range c.PatchTypes[patchTypeName].Values {
if tag == allowedTag {
if severity == "" {
tagScopeOK = true
break
}
if c.PatchTypes[patchTypeName].Scope == "" {
log.Printf("unable to verify severity %s without definitions", severity)
break // subject has severity but there is no definition to verify it
}
for _, allowedScope := range c.PatchScopes[c.PatchTypes[patchTypeName].Scope] {
if severity == allowedScope {
tagScopeOK = true
break
}
}
}
}
return tagScopeOK
}
var ErrTagScope = errors.New("invalid tag and or severity")
func (c CommitPolicyConfig) CheckSubject(rawSubject []byte, junitSuite junit.Interface) error {
// check for ascii-only before anything else
for i := 0; i < len(rawSubject); i++ {
if rawSubject[i] > unicode.MaxASCII {
junitSuite.AddMessageFailed("", "non-ascii characters detected in commit subject", fmt.Sprintf("subject: %s", rawSubject))
log.Printf("non-ascii characters detected in in subject:\n%s", hex.Dump(rawSubject))
return fmt.Errorf("non-ascii characters in commit subject: %w", ErrTagScope)
}
}
// 5 subgroups, 4. is "/severity", 5. is "severity"
r := regexp.MustCompile(`^(?P<match>(?P<tag>[A-Z]+)(\/(?P<severity>[A-Z]+))?: )`)
tTag := []byte("$tag")
tScope := []byte("$severity")
result := []byte{}
candidates := []string{}
var tag, severity string
for _, tagAlternative := range c.TagOrder {
tagOK := tagAlternative.Optional
submatch := r.FindSubmatchIndex(rawSubject)
if len(submatch) == 0 { // no match
if !tagOK {
junitSuite.AddMessageFailed("", "invalid or missing tag/severity in commit message", fmt.Sprintf("subject: %s", rawSubject))
log.Printf("unable to find match in %s\n", rawSubject)
return fmt.Errorf("invalid tag or no tag found, searched through [%s]: %w",
strings.Join(tagAlternative.PatchTypes, ", "), ErrTagScope)
}
continue
}
tagPart := rawSubject[submatch[0]:submatch[1]]
tag = string(r.Expand(result, tTag, tagPart, submatch))
severity = string(r.Expand(result, tScope, tagPart, submatch))
for _, pType := range tagAlternative.PatchTypes { // we allow more than one set of tags in a position
if c.CheckPatchTypes(tag, severity, pType) { // we found what we were looking for, so consume input
rawSubject = rawSubject[submatch[1]:]
tagOK = tagOK || true
break
}
}
candidates = append(candidates, string(tagPart))
if !tagOK {
junitSuite.AddMessageFailed("", "invalid tag/severity in commit message", fmt.Sprintf("subject: %s", rawSubject))
log.Printf("unable to find match in %s\n", candidates)
return fmt.Errorf("invalid tag or no tag found, searched through [%s]: %w",
strings.Join(tagAlternative.PatchTypes, ", "), ErrTagScope)
}
}
submatch := r.FindSubmatchIndex(rawSubject)
if len(submatch) != 0 { // no match
junitSuite.AddMessageFailed("", "unprocessed tags detected in commit message", fmt.Sprintf("subject: %s", rawSubject))
return fmt.Errorf("detected unprocessed tags, %w", ErrTagScope)
}
return checkSubjectText(string(rawSubject), junitSuite)
}
func (c CommitPolicyConfig) IsEmpty() bool {
c1, _ := yaml.Marshal(c)
c2, _ := yaml.Marshal(new(CommitPolicyConfig)) // empty config
return string(c1) == string(c2)
}
var ErrGitEnvironment = errors.New("git environment error")
func readGitEnvironment() (string, error) {
if os.Getenv("CHECK") == LOCAL {
return LOCAL, nil
}
url := os.Getenv("GITHUB_API_URL")
if url != "" {
log.Printf("detected %s environment\n", GITHUB)
log.Printf("using api url '%s'\n", url)
return GITHUB, nil
} else {
url = os.Getenv("CI_API_V4_URL")
if url != "" {
log.Printf("detected %s environment\n", GITLAB)
log.Printf("using api url '%s'\n", url)
return GITLAB, nil
} else {
return LOCAL, nil
// return "", fmt.Errorf("no suitable git environment variables found: %w", ErrGitEnvironment)
}
}
}
func LoadCommitPolicy(filename string) (CommitPolicyConfig, error) {
var commitPolicy CommitPolicyConfig
var config string
if data, err := os.ReadFile(filename); err != nil {
log.Printf("warning: using built-in fallback configuration with HAProxy defaults (%s)", err)
config = defaultConfig
} else {
config = string(data)
}
if err := yaml.Unmarshal([]byte(config), &commitPolicy); err != nil {
return CommitPolicyConfig{}, fmt.Errorf("error loading commit policy: %w", err)
}
return commitPolicy, nil
}
func getGithubCommitData(junitSuite junit.Interface) ([]string, []string, []map[string]string, error) {
token := getAPIToken("GITHUB_TOKEN")
repo := os.Getenv("GITHUB_REPOSITORY")
ref := os.Getenv("GITHUB_REF")
event := os.Getenv("GITHUB_EVENT_NAME")
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
githubClient := github.NewClient(tc)
if event == "pull_request" {
repoSlice := strings.SplitN(repo, "/", 2)
if len(repoSlice) < 2 {
junitSuite.AddMessageFailed("", "error fetching owner and project from repo", fmt.Sprintf("invalid repository format: %s", repo))
return nil, nil, nil, fmt.Errorf("error fetching owner and project from repo %s", repo)
}
owner := repoSlice[0]
project := repoSlice[1]
refSlice := strings.SplitN(ref, "/", 4)
if len(refSlice) < 3 {
junitSuite.AddMessageFailed("", "error fetching PR number from ref", fmt.Sprintf("invalid ref format: %s", ref))
return nil, nil, nil, fmt.Errorf("error fetching PR from ref %s", ref)
}
prNo, err := strconv.Atoi(refSlice[2])
if err != nil {
junitSuite.AddMessageFailed("", "error fetching PR number from ref", fmt.Sprintf("invalid pr number: %s", refSlice[2]))
return nil, nil, nil, fmt.Errorf("Error fetching PR number from %s: %w", refSlice[2], err)
}
commits, _, err := githubClient.PullRequests.ListCommits(ctx, owner, project, prNo, &github.ListOptions{})
if err != nil {
junitSuite.AddMessageFailed("", "error fetching commits", err.Error())
return nil, nil, nil, fmt.Errorf("error fetching commits: %w", err)
}
subjects := []string{}
messages := []string{}
diffs := []map[string]string{}
for _, c := range commits {
l := strings.SplitN(c.Commit.GetMessage(), "\n", 3)
hash := c.Commit.GetSHA()
if len(hash) > 8 {
hash = hash[:8]
}
if len(l) > 1 {
if l[1] != "" {
junitSuite.AddMessageFailed("", "empty line between subject and body is required", fmt.Sprintf("%s %s", hash, l[0]))
return nil, nil, nil, fmt.Errorf("empty line between subject and body is required: %s %s", hash, l[0])
}
}
if len(l) > 0 {
log.Printf("detected message %s from commit %s", l[0], hash)
subjects = append(subjects, l[0])
messages = append(messages, c.Commit.GetMessage())
}
files, _, err := githubClient.PullRequests.ListFiles(ctx, owner, project, prNo, &github.ListOptions{})
if err != nil {
junitSuite.AddMessageFailed("", "error fetching files", err.Error())
return nil, nil, nil, fmt.Errorf("error fetching files: %w", err)
}
content := map[string]string{}
for _, file := range files {
if _, ok := content[file.GetFilename()]; ok {
continue
}
content[file.GetFilename()] = cleanGitPatch(file.GetPatch())
}
diffs = append(diffs, content)
}
return subjects, messages, diffs, nil
} else {
junitSuite.AddMessageFailed("", "unsupported event name", fmt.Sprintf("unsupported event name: %s", event))
return nil, nil, nil, fmt.Errorf("unsupported event name: %s", event)
}
}
func getLocalCommitData(junitSuite junit.Interface) ([]string, []string, []map[string]string, error) {
repo, err := git.PlainOpen(".")
if err != nil {
junitSuite.AddMessageFailed("", "error opening local git repository", err.Error())
return nil, nil, nil, err
}
iter, err := repo.Log(&git.LogOptions{
Order: git.LogOrderCommitterTime,
})
if err != nil {
junitSuite.AddMessageFailed("", "error getting git log iterator", err.Error())
return nil, nil, nil, err
}
subjects := []string{}
messages := []string{}
diffs := []map[string]string{}
committer := ""
var commit1 *object.Commit
var oldestCommit *object.Commit
var commit2 *object.Commit
for {
commit, err := iter.Next()
if commit != nil {
oldestCommit = commit
}
if err == io.EOF {
break
}
if err != nil {
junitSuite.AddMessageFailed("", "error iterating through git commits", err.Error())
return nil, nil, nil, err
}
if committer == "" {
committer = commit.Author.Name
commit1 = commit
}
if commit.Author.Name != committer {
commit2 = commit
break
}
commitBody := commit.Message
l := strings.SplitN(string(commitBody), "\n", 3)
commitHash := commit.Hash.String()
if len(commitHash) > 8 {
commitHash = commitHash[:8]
}
if len(l) > 1 {
if l[1] != "" {
junitSuite.AddMessageFailed("", "empty line between subject and body is required", fmt.Sprintf("%s %s", commitHash, l[0]))
return nil, nil, nil, fmt.Errorf("empty line between subject and body is required: %s %s", commitHash, l[0])
}
}
if len(l) > 0 {
subjects = append(subjects, l[0])
messages = append(messages, string(commitBody))
}
}
// Get the changes (diff) between the two commits
tree1, _ := commit1.Tree()
if commit2 == nil {
commit2 = oldestCommit
}
tree2, _ := commit2.Tree()
changes, err := object.DiffTree(tree2, tree1)
if err != nil {
junitSuite.AddMessageFailed("", "error getting git commit changes", err.Error())
return nil, nil, nil, err
}
// Print the list of changed files and their content (patch)
for _, change := range changes {
patch, err := change.Patch()
if err != nil {
junitSuite.AddMessageFailed("", "error getting git patch", err.Error())
return nil, nil, nil, err
}
for _, file := range patch.FilePatches() {
chunks := file.Chunks()
fileChanges := ``
for _, chunk := range chunks {
if chunk.Type() == diff.Delete {
continue
}
if chunk.Type() == diff.Equal {
continue
}
fileChanges += chunk.Content() + "\n"
}
if fileChanges == "" {
continue
}
diffs = append(diffs, map[string]string{change.To.Name: fileChanges})
}
}
return subjects, messages, diffs, nil
}
func cleanGitPatch(patch string) string {
var cleanedPatch strings.Builder
scanner := bufio.NewScanner(strings.NewReader(patch))
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "+") {
cleanedPatch.WriteString(line)
cleanedPatch.WriteString("\n")
}
}
patch = cleanedPatch.String()
return patch
}
func getGitlabCommitData(junitSuite junit.Interface) ([]string, []string, []map[string]string, error) {
gitlabURL := os.Getenv("CI_API_V4_URL")
token := getAPIToken("GITLAB_TOKEN")
mri := os.Getenv("CI_MERGE_REQUEST_IID")
project := os.Getenv("CI_MERGE_REQUEST_PROJECT_ID")
gitlabClient, err := gitlab.NewClient(token, gitlab.WithBaseURL(gitlabURL))
if err != nil {
junitSuite.AddMessageFailed("", "failed to create gitlab client", err.Error())
return nil, nil, nil, fmt.Errorf("failed to create gitlab client: %w", err)
}
mrIID, err := strconv.Atoi(mri)
if err != nil {
junitSuite.AddMessageFailed("", "invalid merge request id", err.Error())
return nil, nil, nil, fmt.Errorf("invalid merge request id %s", mri)
}
projectID, err := strconv.Atoi(project)
if err != nil {
junitSuite.AddMessageFailed("", "invalid project id", err.Error())
return nil, nil, nil, fmt.Errorf("invalid project id %s", project)
}
commits, _, err := gitlabClient.MergeRequests.GetMergeRequestCommits(projectID, int64(mrIID), &gitlab.GetMergeRequestCommitsOptions{})
if err != nil {
junitSuite.AddMessageFailed("", "error fetching commits", err.Error())
return nil, nil, nil, fmt.Errorf("error fetching commits: %w", err)
}
subjects := []string{}
messages := []string{}
diffs := []map[string]string{}
for _, c := range commits {
l := strings.SplitN(c.Message, "\n", 3)
hash := c.ShortID
if len(l) > 0 {
if len(l) > 1 {
if l[1] != "" {
junitSuite.AddMessageFailed("", "empty line between subject and body is required", fmt.Sprintf("%s %s", hash, l[0]))
return nil, nil, nil, fmt.Errorf("empty line between subject and body is required: %s %s", hash, l[0])
}
}
log.Printf("detected message %s from commit %s", l[0], hash)
subjects = append(subjects, l[0])
messages = append(messages, c.Message)
diff, _, err := gitlabClient.MergeRequests.ListMergeRequestDiffs(projectID, int64(mrIID), &gitlab.ListMergeRequestDiffsOptions{})
if err != nil {
junitSuite.AddMessageFailed("", "error fetching commit changes", err.Error())
return nil, nil, nil, fmt.Errorf("error fetching commit changes: %w", err)
}
content := map[string]string{}
for _, d := range diff {
if _, ok := content[d.NewPath]; ok {
continue
}
content[d.NewPath] = cleanGitPatch(d.Diff)
}
diffs = append(diffs, content)
}
}
return subjects, messages, diffs, nil
}
func getCommitData(repoEnv string, junitSuite junit.Interface) ([]string, []string, []map[string]string, error) {
if repoEnv == GITHUB {
return getGithubCommitData(junitSuite)
} else if repoEnv == GITLAB {
return getGitlabCommitData(junitSuite)
} else if repoEnv == LOCAL {
return getLocalCommitData(junitSuite)
}
return nil, nil, nil, fmt.Errorf("unrecognized git environment %s", repoEnv)
}
var ErrSubjectList = errors.New("subjects contain errors")
func (c CommitPolicyConfig) CheckSubjectList(subjects []string, junitSuite junit.Interface) error {
errors := false
for _, subject := range subjects {
subject = strings.Trim(subject, "'")
if err := c.CheckSubject([]byte(subject), junitSuite); err != nil {
log.Printf("%s, original subject message '%s'", err, subject)
errors = true
}
}
if errors {
return ErrSubjectList
}
return nil
}
const requiredCmdlineArgs = 2