-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathapp.go
More file actions
441 lines (379 loc) · 13.3 KB
/
Copy pathapp.go
File metadata and controls
441 lines (379 loc) · 13.3 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
package app
import (
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"time"
owners "github.com/multimediallc/codeowners-plus/internal/config"
"github.com/multimediallc/codeowners-plus/internal/git"
gh "github.com/multimediallc/codeowners-plus/internal/github"
"github.com/multimediallc/codeowners-plus/pkg/codeowners"
f "github.com/multimediallc/codeowners-plus/pkg/functional"
"github.com/multimediallc/codeowners-plus/pkg/inlineowners"
)
// Config holds the application configuration
type Config struct {
Token string
RepoDir string
PR int
Repo string
Verbose bool
Quiet bool
InfoBuffer io.Writer
WarningBuffer io.Writer
}
// App represents the application with its dependencies
type App struct {
Conf *owners.Config
config *Config
client gh.Client
codeowners codeowners.CodeOwners
gitDiff git.Diff
}
// New creates a new App instance with the given configuration
func New(cfg Config) (*App, error) {
repoSplit := strings.Split(cfg.Repo, "/")
if len(repoSplit) != 2 {
return nil, fmt.Errorf("invalid repo name: %s", cfg.Repo)
}
owner := repoSplit[0]
repo := repoSplit[1]
client := gh.NewClient(owner, repo, cfg.Token)
app := &App{
config: &cfg,
client: client,
}
return app, nil
}
func (a *App) printDebug(format string, args ...interface{}) {
if a.config.Verbose {
_, _ = fmt.Fprintf(a.config.InfoBuffer, format, args...)
}
}
func (a *App) printWarn(format string, args ...interface{}) {
_, _ = fmt.Fprintf(a.config.WarningBuffer, format, args...)
}
// Run executes the application logic
func (a *App) Run() (bool, string, error) {
// Initialize PR
if err := a.client.InitPR(a.config.PR); err != nil {
return false, "", fmt.Errorf("InitPR Error: %v", err)
}
a.printDebug("PR: %d\n", a.client.PR().GetNumber())
// Read config
conf, err := owners.ReadConfig(a.config.RepoDir)
if err != nil {
a.printWarn("Error reading codeowners.toml - using default config\n")
}
a.Conf = conf
// Setup diff context
diffContext := git.DiffContext{
Base: a.client.PR().Base.GetSHA(),
Head: a.client.PR().Head.GetSHA(),
Dir: a.config.RepoDir,
IgnoreDirs: conf.Ignore,
}
// Get the diff of the PR
a.printDebug("Getting diff for %s...%s\n", diffContext.Base, diffContext.Head)
gitDiff, err := git.NewDiff(diffContext)
if err != nil {
return false, "", fmt.Errorf("NewGitDiff Error: %v", err)
}
a.gitDiff = gitDiff
// Initialize codeowners
codeOwners, err := codeowners.New(a.config.RepoDir, gitDiff.AllChanges(), a.config.WarningBuffer)
if err != nil {
return false, "", fmt.Errorf("NewCodeOwners Error: %v", err)
}
a.codeowners = codeOwners
// Inline ownership integration
if a.Conf != nil && a.Conf.InlineOwnershipEnabled {
oracle := inlineowners.Oracle{}
// build oracle blocks per file
for _, df := range gitDiff.AllChanges() {
abs := filepath.Join(a.config.RepoDir, df.FileName)
data, err := os.ReadFile(abs)
if err != nil {
a.printWarn("WARNING: unable to read file %s: %v\n", df.FileName, err)
continue
}
blks, _ := inlineowners.Parse(string(data), a.config.WarningBuffer)
if len(blks) > 0 {
// convert to Block type
b2 := make([]inlineowners.Block, 0, len(blks))
for _, pb := range blks {
b2 = append(b2, inlineowners.Block{Owners: pb.Owners, Start: pb.StartLine, End: pb.EndLine})
}
oracle[df.FileName] = b2
}
}
overrides := make(map[string]codeowners.ReviewerGroups)
for _, df := range gitDiff.AllChanges() {
// aggregate owners from hunks via oracle
rgs := codeowners.ReviewerGroups{}
for _, h := range df.Hunks {
lists := oracle.OwnersForRange(df.FileName, h.Start, h.End)
if lists == nil {
continue
}
for _, lst := range lists {
rgs = append(rgs, &codeowners.ReviewerGroup{Names: lst, Approved: false})
}
}
if len(rgs) == 0 {
// fallback to file-level
if baseGroups, ok := codeOwners.FileRequired()[df.FileName]; ok {
rgs = append(rgs, baseGroups...)
}
} else {
rgs = f.RemoveDuplicates(rgs)
}
overrides[df.FileName] = rgs
}
a.codeowners = newOverlayOwners(codeOwners, overrides)
} else {
// feature disabled, keep original codeOwners
a.codeowners = codeOwners
}
// Set author
author := fmt.Sprintf("@%s", a.client.PR().User.GetLogin())
a.codeowners.SetAuthor(author)
// Warn about unowned files
for _, uFile := range a.codeowners.UnownedFiles() {
a.printWarn("WARNING: Unowned File: %s\n", uFile)
}
// Print file owners if verbose
if a.config.Verbose {
a.printFileOwners(a.codeowners)
}
// Process approvals and reviewers
return a.processApprovalsAndReviewers()
}
func (a *App) processApprovalsAndReviewers() (bool, string, error) {
message := ""
// Get all required owners before filtering
allRequiredOwners := a.codeowners.AllRequired()
allRequiredOwnerNames := allRequiredOwners.Flatten()
a.printDebug("All Required Owners: %s\n", allRequiredOwnerNames)
// Get optional reviewers
allOptionalReviewerNames := a.codeowners.AllOptional().Flatten()
allOptionalReviewerNames = f.Filtered(allOptionalReviewerNames, func(name string) bool {
return !slices.Contains(allRequiredOwnerNames, name)
})
a.printDebug("All Optional Reviewers: %s\n", allOptionalReviewerNames)
// Initialize user reviewer map
if err := a.client.InitUserReviewerMap(allRequiredOwnerNames); err != nil {
return false, message, fmt.Errorf("InitUserReviewerMap Error: %v", err)
}
// Get current approvals
ghApprovals, err := a.client.GetCurrentReviewerApprovals()
if err != nil {
return false, message, fmt.Errorf("GetCurrentApprovals Error: %v", err)
}
a.printDebug("Current Approvals: %+v\n", ghApprovals)
// Process token owner approval if enabled
var tokenOwnerApproval *gh.CurrentApproval
if a.Conf.Enforcement.Approval {
tokenOwnerApproval, err = a.processTokenOwnerApproval()
if err != nil {
return false, message, err
}
}
// Process approvals and dismiss stale ones
validApprovalCount, err := a.processApprovals(ghApprovals)
if err != nil {
return false, message, err
}
// Request reviews from required owners
err = a.requestReviews()
if err != nil {
return false, message, err
}
unapprovedOwners := a.codeowners.AllRequired()
maxReviewsMet := false
if a.Conf.MaxReviews != nil && *a.Conf.MaxReviews > 0 {
if validApprovalCount >= *a.Conf.MaxReviews && len(f.Intersection(unapprovedOwners.Flatten(), a.Conf.UnskippableReviewers)) == 0 {
maxReviewsMet = true
}
}
// Add comments to the PR if necessary
err = a.addReviewStatusComment(allRequiredOwners, maxReviewsMet)
if err != nil {
return false, message, fmt.Errorf("failed to add review status comment: %w", err)
}
err = a.addOptionalCcComment(allOptionalReviewerNames)
if err != nil {
return false, message, fmt.Errorf("failed to add optional CC comment: %w", err)
}
// Exit if there are any unapproved codeowner teams
if len(unapprovedOwners) > 0 && !maxReviewsMet {
// Return failed status if any codeowner team has not approved the PR
unapprovedCommentString := unapprovedOwners.ToCommentString(false)
if a.Conf.Enforcement.Approval && tokenOwnerApproval != nil {
_ = a.client.DismissStaleReviews([]*gh.CurrentApproval{tokenOwnerApproval})
}
message = fmt.Sprintf(
"FAIL: Codeowners reviews not satisfied\nStill required:\n%s",
unapprovedCommentString,
)
return false, message, nil
}
// Exit if there are not enough reviews
if a.Conf.MinReviews != nil && *a.Conf.MinReviews > 0 {
if validApprovalCount < *a.Conf.MinReviews {
message = fmt.Sprintf("FAIL: Min Reviews not satisfied. Need %d, found %d", *a.Conf.MinReviews, validApprovalCount)
return false, message, nil
}
}
message = "Codeowners reviews satisfied"
if a.Conf.Enforcement.Approval && tokenOwnerApproval == nil {
// Approve the PR since all codeowner teams have approved
err = a.client.ApprovePR()
if err != nil {
return true, message, fmt.Errorf("ApprovePR Error: %v", err)
}
}
return true, message, nil
}
func (a *App) addReviewStatusComment(allRequiredOwners codeowners.ReviewerGroups, maxReviewsMet bool) error {
// Comment on the PR with the codeowner teams required for review
if a.config.Quiet || len(allRequiredOwners) == 0 {
a.printDebug("Skipping review status comment (disabled or no unapproved owners).\n")
return nil
}
var commentPrefix = "Codeowners approval required for this PR:\n"
hasHighPriority, err := a.client.IsInLabels(a.Conf.HighPriorityLabels)
if err != nil {
a.printWarn("WARNING: Error checking high priority labels: %v\n", err)
} else if hasHighPriority {
commentPrefix = "❗High Prio❗\n\n" + commentPrefix
}
comment := commentPrefix + allRequiredOwners.ToCommentString(true)
if maxReviewsMet {
comment += "\n\nThe PR has received the max number of required reviews. No further action is required."
}
fiveDaysAgo := time.Now().AddDate(0, 0, -5)
existingComment, existingFound, err := a.client.FindExistingComment(commentPrefix, &fiveDaysAgo)
if err != nil {
return fmt.Errorf("FindExistingComment Error: %v", err)
}
if existingFound {
if found, _ := a.client.IsInComments(comment, &fiveDaysAgo); found {
// we don't need to update the comment
return nil
}
a.printDebug("Updating existing review status comment\n")
err = a.client.UpdateComment(existingComment, comment)
if err != nil {
return fmt.Errorf("UpdateComment Error: %v", err)
}
} else {
a.printDebug("Adding new review status comment: %q\n", comment)
err = a.client.AddComment(comment)
if err != nil {
return fmt.Errorf("AddComment Error: %v", err)
}
}
return nil
}
func (a *App) addOptionalCcComment(allOptionalReviewerNames []string) error {
// Add CC comment to the PR with the optional reviewers that have not already been mentioned in the PR comments
if a.config.Quiet || len(allOptionalReviewerNames) == 0 {
return nil
}
var isInCommentsError error
viewersToPing := f.Filtered(allOptionalReviewerNames, func(name string) bool {
if isInCommentsError != nil {
return false
}
found, err := a.client.IsSubstringInComments(name, nil)
if err != nil {
a.printWarn("WARNING: Error checking comments for substring '%s': %v\n", name, err)
isInCommentsError = err
return false
}
return !found
})
if isInCommentsError != nil {
return fmt.Errorf("IsInComments Error: %v", isInCommentsError)
}
// Add the CC comment if there are any viewers to ping
if len(viewersToPing) > 0 {
comment := fmt.Sprintf("cc %s", strings.Join(viewersToPing, " "))
a.printDebug("Adding CC comment: %q\n", comment)
err := a.client.AddComment(comment)
if err != nil {
return fmt.Errorf("AddComment Error: %v", err)
}
} else {
a.printDebug("No new optional reviewers to CC.\n")
}
return nil
}
func (a *App) processTokenOwnerApproval() (*gh.CurrentApproval, error) {
tokenOwner, err := a.client.GetTokenUser()
if err != nil {
a.printWarn("WARNING: You might be trying to use a bot as an Enforcement.Approval user," +
" but this will not work due to GitHub CODEOWNERS not allowing bots as code owners." +
" To use the Enforcement.Approval feature, the token must belong to a GitHub user account")
a.Conf.Enforcement.Approval = false
return nil, nil
}
tokenOwnerApproval, _ := a.client.FindUserApproval(tokenOwner)
return tokenOwnerApproval, nil
}
func (a *App) processApprovals(ghApprovals []*gh.CurrentApproval) (int, error) {
fileReviewers := f.MapMap(a.codeowners.FileRequired(), func(reviewers codeowners.ReviewerGroups) []string { return reviewers.Flatten() })
approvers, approvalsToDismiss := a.client.CheckApprovals(fileReviewers, ghApprovals, a.gitDiff)
a.codeowners.ApplyApprovals(approvers)
if len(approvalsToDismiss) > 0 {
a.printDebug("Dismissing Stale Approvals: %+v\n", approvalsToDismiss)
if err := a.client.DismissStaleReviews(approvalsToDismiss); err != nil {
return 0, fmt.Errorf("DismissStaleReviews Error: %v", err)
}
}
return len(ghApprovals) - len(approvalsToDismiss), nil
}
func (a *App) requestReviews() error {
if a.config.Quiet {
return nil
}
unapprovedOwners := a.codeowners.AllRequired()
unapprovedOwnerNames := unapprovedOwners.Flatten()
a.printDebug("Remaining Required Owners: %s\n", unapprovedOwnerNames)
currentlyRequestedOwners, err := a.client.GetCurrentlyRequested()
if err != nil {
return fmt.Errorf("GetCurrentlyRequested Error: %v", err)
}
a.printDebug("Currently Requested Owners: %s\n", currentlyRequestedOwners)
previousReviewers, err := a.client.GetAlreadyReviewed()
if err != nil {
return fmt.Errorf("GetAlreadyReviewed Error: %v", err)
}
a.printDebug("Already Reviewed Owners: %s\n", previousReviewers)
filteredOwners := unapprovedOwners.FilterOut(currentlyRequestedOwners...)
filteredOwners = filteredOwners.FilterOut(previousReviewers...)
filteredOwnerNames := filteredOwners.Flatten()
if len(filteredOwners) > 0 {
a.printDebug("Requesting Reviews from: %s\n", filteredOwnerNames)
if err := a.client.RequestReviewers(filteredOwnerNames); err != nil {
return fmt.Errorf("RequestReviewers Error: %v", err)
}
}
return nil
}
func (a *App) printFileOwners(codeOwners codeowners.CodeOwners) {
fileRequired := codeOwners.FileRequired()
a.printDebug("File Reviewers:\n")
for file, reviewers := range fileRequired {
a.printDebug("- %s: %+v\n", file, reviewers.Flatten())
}
fileOptional := codeOwners.FileOptional()
a.printDebug("File Optional:\n")
for file, reviewers := range fileOptional {
a.printDebug("- %s: %+v\n", file, reviewers.Flatten())
}
}