generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 98
/
repoowners.go
938 lines (820 loc) · 30.3 KB
/
repoowners.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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
/*
Copyright 2017 The Kubernetes 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.
*/
package repoowners
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/sirupsen/logrus"
"sigs.k8s.io/yaml"
"k8s.io/apimachinery/pkg/util/sets"
"sigs.k8s.io/prow/pkg/git/v2"
"sigs.k8s.io/prow/pkg/github"
"sigs.k8s.io/prow/pkg/layeredsets"
"sigs.k8s.io/prow/pkg/plugins/ownersconfig"
prowConf "sigs.k8s.io/prow/pkg/config"
)
const (
// GitHub's api uses "" (empty) string as basedir by convention but it's clearer to use "/"
baseDirConvention = ""
)
type dirOptions struct {
NoParentOwners bool `json:"no_parent_owners,omitempty"`
// AutoApproveUnownedSubfolders will result in changes to a subpath of a given path
// that does not have an OWNERS file being auto-approved. This should be
// enabled with caution.
AutoApproveUnownedSubfolders bool `json:"auto_approve_unowned_subfolders,omitempty"`
}
// Config holds roles+usernames and labels for a directory considered as a unit of independent code
type Config struct {
Approvers []string `json:"approvers,omitempty"`
Reviewers []string `json:"reviewers,omitempty"`
RequiredReviewers []string `json:"required_reviewers,omitempty"`
Labels []string `json:"labels,omitempty"`
}
// SimpleConfig holds options and Config applied to everything under the containing directory
type SimpleConfig struct {
Options dirOptions `json:"options,omitempty"`
Config `json:",inline"`
}
// Empty checks if a SimpleConfig could be considered empty
func (s *SimpleConfig) Empty() bool {
return len(s.Approvers) == 0 && len(s.Reviewers) == 0 && len(s.RequiredReviewers) == 0 && len(s.Labels) == 0
}
// FullConfig contains Filters which apply specific Config to files matching its regexp
type FullConfig struct {
Options dirOptions `json:"options,omitempty"`
Filters map[string]Config `json:"filters,omitempty"`
}
type githubClient interface {
ListCollaborators(org, repo string) ([]github.User, error)
GetRef(org, repo, ref string) (string, error)
}
func newCache() *cache {
return &cache{
lockMapLock: &sync.Mutex{},
lockMap: map[string]*sync.Mutex{},
dataLock: &sync.Mutex{},
data: map[string]cacheEntry{},
}
}
type cache struct {
// These are used to lock access to individual keys to avoid wasted tokens
// on concurrent requests. This has no effect when using ghproxy, as ghproxy
// serializes identical requests anyways. This should be removed once ghproxy
// is made mandatory.
lockMapLock *sync.Mutex
lockMap map[string]*sync.Mutex
dataLock *sync.Mutex
data map[string]cacheEntry
}
// getEntry returns the data for the key, a boolean indicating if data existed and a lock.
// The lock is already locked, it must be unlocked by the caller.
func (c *cache) getEntry(key string) (cacheEntry, bool, *sync.Mutex) {
c.lockMapLock.Lock()
entryLock, ok := c.lockMap[key]
if !ok {
c.lockMap[key] = &sync.Mutex{}
entryLock = c.lockMap[key]
}
c.lockMapLock.Unlock()
entryLock.Lock()
c.dataLock.Lock()
defer c.dataLock.Unlock()
entry, ok := c.data[key]
return entry, ok, entryLock
}
func (c *cache) setEntry(key string, data cacheEntry) {
c.dataLock.Lock()
c.data[key] = data
c.dataLock.Unlock()
}
type cacheEntry struct {
sha string
aliases RepoAliases
owners *RepoOwners
}
func (entry cacheEntry) matchesMDYAML(mdYAML bool) bool {
return entry.owners.enableMDYAML == mdYAML
}
func (entry cacheEntry) fullyLoaded() bool {
return entry.sha != "" && entry.aliases != nil && entry.owners != nil
}
// Interface is an interface to work with OWNERS files.
type Interface interface {
LoadRepoOwners(org, repo, base string) (RepoOwner, error)
LoadRepoOwnersSha(org, repo, base, sha string, updateCache bool) (RepoOwner, error)
WithFields(fields logrus.Fields) Interface
WithGitHubClient(client github.Client) Interface
ForPlugin(plugin string) Interface
Used() bool
}
// Client is an implementation of the Interface.
var _ Interface = &Client{}
// Client is the repoowners client
type Client struct {
logger *logrus.Entry
ghc githubClient
used bool
*delegate
}
type delegate struct {
git git.ClientFactory
mdYAMLEnabled func(org, repo string) bool
skipCollaborators func(org, repo string) bool
ownersDirDenylist func() *prowConf.OwnersDirDenylist
filenames ownersconfig.Resolver
cache *cache
}
// WithFields clones the client, keeping the underlying delegate the same but adding
// fields to the logging context
func (c *Client) WithFields(fields logrus.Fields) Interface {
return &Client{
logger: c.logger.WithFields(fields),
delegate: c.delegate,
}
}
// WithGitHubClient clones the client, keeping the underlying delegate the same but adding
// a new GitHub Client. This is useful when making use a context-local client
func (c *Client) WithGitHubClient(client github.Client) Interface {
return &Client{
logger: c.logger,
ghc: client,
delegate: c.delegate,
}
}
// ForPlugin clones the client, keeping the underlying delegate the same but adding
// a log field
func (c *Client) ForPlugin(plugin string) Interface {
return c.forKeyValue("plugin", plugin)
}
func (c *Client) forKeyValue(key, value string) Interface {
return &Client{
logger: c.logger.WithField(key, value),
ghc: c.ghc,
delegate: c.delegate,
}
}
// Used determines whether the client has been used
func (c *Client) Used() bool {
return c.used
}
// NewClient is the constructor for Client
func NewClient(
gc git.ClientFactory,
ghc github.Client,
mdYAMLEnabled func(org, repo string) bool,
skipCollaborators func(org, repo string) bool,
ownersDirDenylist func() *prowConf.OwnersDirDenylist,
filenames ownersconfig.Resolver,
) *Client {
return &Client{
logger: logrus.WithField("client", "repoowners"),
ghc: ghc,
delegate: &delegate{
git: gc,
cache: newCache(),
mdYAMLEnabled: mdYAMLEnabled,
skipCollaborators: skipCollaborators,
ownersDirDenylist: ownersDirDenylist,
filenames: filenames,
},
}
}
// RepoAliases defines groups of people to be used in OWNERS files
type RepoAliases map[string]sets.Set[string]
// RepoOwner is an interface to work with repoowners
type RepoOwner interface {
FindApproverOwnersForFile(path string) string
FindReviewersOwnersForFile(path string) string
FindLabelsForFile(path string) sets.Set[string]
IsNoParentOwners(path string) bool
IsAutoApproveUnownedSubfolders(directory string) bool
LeafApprovers(path string) sets.Set[string]
Approvers(path string) layeredsets.String
LeafReviewers(path string) sets.Set[string]
Reviewers(path string) layeredsets.String
RequiredReviewers(path string) sets.Set[string]
ParseSimpleConfig(path string) (SimpleConfig, error)
ParseFullConfig(path string) (FullConfig, error)
TopLevelApprovers() sets.Set[string]
Filenames() ownersconfig.Filenames
AllOwners() sets.Set[string]
AllApprovers() sets.Set[string]
AllReviewers() sets.Set[string]
}
var _ RepoOwner = &RepoOwners{}
// RepoOwners contains the parsed OWNERS config.
type RepoOwners struct {
RepoAliases
approvers map[string]map[*regexp.Regexp]sets.Set[string]
reviewers map[string]map[*regexp.Regexp]sets.Set[string]
requiredReviewers map[string]map[*regexp.Regexp]sets.Set[string]
labels map[string]map[*regexp.Regexp]sets.Set[string]
options map[string]dirOptions
baseDir string
enableMDYAML bool
dirDenylist []*regexp.Regexp
filenames ownersconfig.Filenames
log *logrus.Entry
}
func (r *RepoOwners) Filenames() ownersconfig.Filenames {
return r.filenames
}
// LoadRepoOwners returns an up-to-date RepoOwners struct for the specified repo.
// Note: The returned *RepoOwners should be treated as read only.
func (c *Client) LoadRepoOwners(org, repo, base string) (RepoOwner, error) {
log := c.logger.WithFields(logrus.Fields{"org": org, "repo": repo, "base": base})
cloneRef := fmt.Sprintf("%s/%s", org, repo)
fullName := fmt.Sprintf("%s:%s", cloneRef, base)
start := time.Now()
sha, err := c.ghc.GetRef(org, repo, fmt.Sprintf("heads/%s", base))
if err != nil {
return nil, fmt.Errorf("failed to get current SHA for %s: %w", fullName, err)
}
if sha == "" {
return nil, fmt.Errorf("got an empty SHA for %s@heads/%s", fullName, base)
}
log.WithField("duration", time.Since(start).String()).Debugf("Completed ghc.GetRef(%s, %s, %s)", org, repo, fmt.Sprintf("heads/%s", base))
return c.LoadRepoOwnersSha(org, repo, base, sha, true)
}
func (c *Client) LoadRepoOwnersSha(org, repo, base, sha string, updateCache bool) (RepoOwner, error) {
c.used = true
log := c.logger.WithFields(logrus.Fields{"org": org, "repo": repo, "base": base, "sha": sha})
cloneRef := fmt.Sprintf("%s/%s", org, repo)
fullName := fmt.Sprintf("%s:%s", cloneRef, base)
entry, err := c.cacheEntryFor(org, repo, base, cloneRef, fullName, sha, updateCache, log)
if err != nil {
return nil, err
}
start := time.Now()
if c.skipCollaborators(org, repo) {
log.WithField("duration", time.Since(start).String()).Debugf("Completed c.skipCollaborators(%s, %s)", org, repo)
log.Debugf("Skipping collaborator checks for %s/%s", org, repo)
return entry.owners, nil
}
log.WithField("duration", time.Since(start).String()).Debugf("Completed c.skipCollaborators(%s, %s)", org, repo)
var owners *RepoOwners
// Filter collaborators. We must filter the RepoOwners struct even if it came from the cache
// because the list of collaborators could have changed without the git SHA changing.
start = time.Now()
collaborators, err := c.ghc.ListCollaborators(org, repo)
log.WithField("duration", time.Since(start).String()).Debugf("Completed ghc.ListCollaborators(%s, %s)", org, repo)
if err != nil {
log.WithError(err).Errorf("Failed to list collaborators while loading RepoOwners. Skipping collaborator filtering.")
owners = entry.owners
} else {
start = time.Now()
owners = entry.owners.filterCollaborators(collaborators)
log.WithField("duration", time.Since(start).String()).Debugf("Completed owners.filterCollaborators(collaborators)")
}
return owners, nil
}
func (c *Client) cacheEntryFor(org, repo, base, cloneRef, fullName, sha string, setEntry bool, log *logrus.Entry) (cacheEntry, error) {
mdYaml := c.mdYAMLEnabled(org, repo)
lockStart := time.Now()
defer func() {
log.WithField("duration", time.Since(lockStart).String()).Debug("Locked section of loadRepoOwners completed")
}()
entry, ok, entryLock := c.cache.getEntry(fullName)
defer entryLock.Unlock()
filenames := c.filenames(org, repo)
if !ok || entry.sha != sha || entry.owners == nil || !entry.matchesMDYAML(mdYaml) {
start := time.Now()
gitRepo, err := c.git.ClientFor(org, repo)
if err != nil {
return cacheEntry{}, fmt.Errorf("failed to clone %s: %w", cloneRef, err)
}
log.WithField("duration", time.Since(start).String()).Debugf("Completed git.ClientFor(%s, %s)", org, repo)
defer gitRepo.Clean()
reusable := entry.fullyLoaded() && entry.matchesMDYAML(mdYaml)
// In most sha changed cases, the files associated with the owners are unchanged.
// The cached entry can continue to be used, so need do git diff
if reusable {
start = time.Now()
changes, err := gitRepo.Diff(sha, entry.sha)
if err != nil {
return cacheEntry{}, fmt.Errorf("failed to diff %s with %s", sha, entry.sha)
}
log.WithField("duration", time.Since(start).String()).Debugf("Completed git.Diff(%s, %s)", sha, entry.sha)
start = time.Now()
for _, change := range changes {
if mdYaml && strings.HasSuffix(change, ".md") ||
strings.HasSuffix(change, filenames.OwnersAliases) ||
strings.HasSuffix(change, filenames.Owners) {
reusable = false
log.WithField("duration", time.Since(start).String()).Debugf("Completed owners change verification loop")
break
}
}
log.WithField("duration", time.Since(start).String()).Debugf("Completed owners change verification loop")
}
if reusable {
entry.sha = sha
} else {
start = time.Now()
if err := gitRepo.Checkout(base); err != nil {
return cacheEntry{}, err
}
log.WithField("duration", time.Since(start).String()).Debugf("Completed gitRepo.Checkout(%s)", base)
start = time.Now()
if entry.aliases == nil || entry.sha != sha {
// aliases must be loaded
entry.aliases = loadAliasesFrom(gitRepo.Directory(), filenames.OwnersAliases, log)
}
log.WithField("duration", time.Since(start).String()).Debugf("Completed loadAliasesFrom(%s, log)", gitRepo.Directory())
start = time.Now()
ignoreDirPatterns := c.ownersDirDenylist().ListIgnoredDirs(org, repo)
var dirIgnorelist []*regexp.Regexp
for _, pattern := range ignoreDirPatterns {
re, err := regexp.Compile(pattern)
if err != nil {
log.WithError(err).Errorf("Invalid OWNERS dir denylist regexp %q.", pattern)
continue
}
dirIgnorelist = append(dirIgnorelist, re)
}
log.WithField("duration", time.Since(start).String()).Debugf("Completed dirIgnorelist loading")
start = time.Now()
entry.owners, err = loadOwnersFrom(gitRepo.Directory(), mdYaml, entry.aliases, dirIgnorelist, filenames, log)
if err != nil {
return cacheEntry{}, fmt.Errorf("failed to load RepoOwners for %s: %w", fullName, err)
}
log.WithField("duration", time.Since(start).String()).Debugf("Completed loadOwnersFrom(%s, %t, entry.aliases, dirIgnorelist, log)", gitRepo.Directory(), mdYaml)
entry.sha = sha
if setEntry {
c.cache.setEntry(fullName, entry)
}
}
}
return entry, nil
}
// ExpandAlias returns members of an alias
func (a RepoAliases) ExpandAlias(alias string) sets.Set[string] {
if a == nil {
return nil
}
return a[github.NormLogin(alias)]
}
// ExpandAliases returns members of multiple aliases, duplicates are pruned
func (a RepoAliases) ExpandAliases(logins sets.Set[string]) sets.Set[string] {
if a == nil {
return logins
}
// Make logins a copy of the original set to avoid modifying the original.
logins = logins.Union(nil)
for _, login := range sets.List(logins) {
if expanded, ok := a[github.NormLogin(login)]; ok {
logins.Delete(login)
logins = logins.Union(expanded)
}
}
return logins
}
// ExpandAllAliases returns members of all aliases mentioned, duplicates are pruned
func (a RepoAliases) ExpandAllAliases() sets.Set[string] {
if a == nil {
return nil
}
var result, users sets.Set[string]
for alias := range a {
users = a.ExpandAlias(alias)
result = result.Union(users)
}
return result
}
func loadAliasesFrom(baseDir, filename string, log *logrus.Entry) RepoAliases {
path := filepath.Join(baseDir, filename)
b, err := os.ReadFile(path)
if os.IsNotExist(err) {
log.WithError(err).Infof("No alias file exists at %q. Using empty alias map.", path)
return nil
} else if err != nil {
log.WithError(err).Warnf("Failed to read alias file %q. Using empty alias map.", path)
return nil
}
result, err := ParseAliasesConfig(b)
if err != nil {
log.WithError(err).Errorf("Failed to unmarshal aliases from %q. Using empty alias map.", path)
}
log.Infof("Loaded %d aliases from %q.", len(result), path)
return result
}
func loadOwnersFrom(baseDir string, mdYaml bool, aliases RepoAliases, dirIgnorelist []*regexp.Regexp, filenames ownersconfig.Filenames, log *logrus.Entry) (*RepoOwners, error) {
o := &RepoOwners{
RepoAliases: aliases,
baseDir: baseDir,
enableMDYAML: mdYaml,
filenames: filenames,
log: log,
approvers: make(map[string]map[*regexp.Regexp]sets.Set[string]),
reviewers: make(map[string]map[*regexp.Regexp]sets.Set[string]),
requiredReviewers: make(map[string]map[*regexp.Regexp]sets.Set[string]),
labels: make(map[string]map[*regexp.Regexp]sets.Set[string]),
options: make(map[string]dirOptions),
dirDenylist: dirIgnorelist,
}
return o, filepath.Walk(o.baseDir, o.walkFunc)
}
// by default, github's api doesn't root the project directory at "/" and instead uses the empty string for the base dir
// of the project. And the built-in dir function returns "." for empty strings, so for consistency, we use this
// canonicalize to get the directories of files in a consistent format with NO "/" at the root (a/b/c/ -> a/b/c)
func canonicalize(path string) string {
if path == "." {
return baseDirConvention
}
return strings.TrimSuffix(path, "/")
}
func (o *RepoOwners) walkFunc(path string, info os.FileInfo, err error) error {
log := o.log.WithField("path", path)
if err != nil {
log.WithError(err).Error("Error while walking OWNERS files.")
return nil
}
filename := filepath.Base(path)
relPath, err := filepath.Rel(o.baseDir, path)
if err != nil {
log.WithError(err).Errorf("Unable to find relative path between baseDir: %q and path.", o.baseDir)
return err
}
relPathDir := canonicalize(filepath.Dir(relPath))
if info.Mode().IsDir() {
for _, re := range o.dirDenylist {
if re.MatchString(relPath) {
return filepath.SkipDir
}
}
}
if !info.Mode().IsRegular() {
return nil
}
// '.md' files may contain assignees at the top of the file in a yaml header
// Note that these assignees only apply to the file itself.
if o.enableMDYAML && strings.HasSuffix(filename, ".md") {
// Parse the yaml header from the file if it exists and marshal into the config
simple := &SimpleConfig{}
if err := decodeOwnersMdConfig(path, simple); err != nil {
log.WithError(err).Info("Error decoding OWNERS config from '*.md' file.")
return nil
}
// Set owners for this file (not the directory) using the relative path if they were found
o.applyConfigToPath(relPath, nil, &simple.Config)
o.applyOptionsToPath(relPath, simple.Options)
return nil
}
if filename != o.filenames.Owners {
return nil
}
simple, err := o.ParseSimpleConfig(path)
if err == filepath.SkipDir {
return err
}
if err != nil || simple.Empty() {
c, err := o.ParseFullConfig(path)
if err == filepath.SkipDir {
return err
}
if err != nil {
log.WithError(err).Debugf("Failed to unmarshal %s into either Simple or FullConfig.", path)
} else {
// it's a FullConfig
for pattern, config := range c.Filters {
var re *regexp.Regexp
if pattern != ".*" {
if re, err = regexp.Compile(pattern); err != nil {
log.WithError(err).Debugf("Invalid regexp %q.", pattern)
continue
}
}
o.applyConfigToPath(relPathDir, re, &config)
}
o.applyOptionsToPath(relPathDir, c.Options)
}
} else {
// it's a SimpleConfig
o.applyConfigToPath(relPathDir, nil, &simple.Config)
o.applyOptionsToPath(relPathDir, simple.Options)
}
return nil
}
// ParseFullConfig will unmarshal the content of the OWNERS file at the path into a FullConfig.
// If the OWNERS directory is ignorelisted, it returns filepath.SkipDir.
// Returns an error if the content cannot be unmarshalled.
func (o *RepoOwners) ParseFullConfig(path string) (FullConfig, error) {
// if path is in an ignored directory, ignore it
dir := filepath.Dir(path)
for _, re := range o.dirDenylist {
if re.MatchString(dir) {
return FullConfig{}, filepath.SkipDir
}
}
b, err := os.ReadFile(path)
if err != nil {
return FullConfig{}, err
}
return LoadFullConfig(b)
}
// ParseSimpleConfig will unmarshal the content of the OWNERS file at the path into a SimpleConfig.
// If the OWNERS directory is ignorelisted, it returns filepath.SkipDir.
// Returns an error if the content cannot be unmarshalled.
func (o *RepoOwners) ParseSimpleConfig(path string) (SimpleConfig, error) {
// if path is in a an ignored directory, ignore it
dir := filepath.Dir(path)
for _, re := range o.dirDenylist {
if re.MatchString(dir) {
return SimpleConfig{}, filepath.SkipDir
}
}
b, err := os.ReadFile(path)
if err != nil {
return SimpleConfig{}, err
}
return LoadSimpleConfig(b)
}
// LoadSimpleConfig loads SimpleConfig from bytes `b`
func LoadSimpleConfig(b []byte) (SimpleConfig, error) {
simple := new(SimpleConfig)
err := yaml.Unmarshal(b, simple)
return *simple, err
}
// SaveSimpleConfig writes SimpleConfig to `path`
func SaveSimpleConfig(simple SimpleConfig, path string) error {
b, err := yaml.Marshal(simple)
if err != nil {
return nil
}
return os.WriteFile(path, b, 0644)
}
// LoadFullConfig loads FullConfig from bytes `b`
func LoadFullConfig(b []byte) (FullConfig, error) {
full := new(FullConfig)
err := yaml.Unmarshal(b, full)
return *full, err
}
// SaveFullConfig writes FullConfig to `path`
func SaveFullConfig(full FullConfig, path string) error {
b, err := yaml.Marshal(full)
if err != nil {
return nil
}
return os.WriteFile(path, b, 0644)
}
// ParseAliasesConfig will unmarshal an OWNERS_ALIASES file's content into RepoAliases.
// Returns an error if the content cannot be unmarshalled.
func ParseAliasesConfig(b []byte) (RepoAliases, error) {
result := make(RepoAliases)
config := &struct {
Data map[string][]string `json:"aliases,omitempty"`
}{}
if err := yaml.Unmarshal(b, config); err != nil {
return result, err
}
for alias, expanded := range config.Data {
result[github.NormLogin(alias)] = NormLogins(expanded)
}
return result, nil
}
var mdStructuredHeaderRegex = regexp.MustCompile("^---\n(.|\n)*\n---")
// decodeOwnersMdConfig will parse the yaml header if it exists and unmarshal it into a singleOwnersConfig.
// If no yaml header is found, do nothing
// Returns an error if the file cannot be read or the yaml header is found but cannot be unmarshalled.
func decodeOwnersMdConfig(path string, config *SimpleConfig) error {
fileBytes, err := os.ReadFile(path)
if err != nil {
return err
}
// Parse the yaml header from the top of the file. Will return an empty string if regex does not match.
meta := mdStructuredHeaderRegex.FindString(string(fileBytes))
// Unmarshal the yaml header into the config
return yaml.Unmarshal([]byte(meta), &config)
}
// NormLogins normalizes logins
func NormLogins(logins []string) sets.Set[string] {
normed := sets.New[string]()
for _, login := range logins {
normed.Insert(github.NormLogin(login))
}
return normed
}
var defaultDirOptions = dirOptions{}
func (o *RepoOwners) applyConfigToPath(path string, re *regexp.Regexp, config *Config) {
if len(config.Approvers) > 0 {
if o.approvers[path] == nil {
o.approvers[path] = make(map[*regexp.Regexp]sets.Set[string])
}
o.approvers[path][re] = o.ExpandAliases(NormLogins(config.Approvers))
}
if len(config.Reviewers) > 0 {
if o.reviewers[path] == nil {
o.reviewers[path] = make(map[*regexp.Regexp]sets.Set[string])
}
o.reviewers[path][re] = o.ExpandAliases(NormLogins(config.Reviewers))
}
if len(config.RequiredReviewers) > 0 {
if o.requiredReviewers[path] == nil {
o.requiredReviewers[path] = make(map[*regexp.Regexp]sets.Set[string])
}
o.requiredReviewers[path][re] = o.ExpandAliases(NormLogins(config.RequiredReviewers))
}
if len(config.Labels) > 0 {
if o.labels[path] == nil {
o.labels[path] = make(map[*regexp.Regexp]sets.Set[string])
}
o.labels[path][re] = sets.New[string](config.Labels...)
}
}
func (o *RepoOwners) applyOptionsToPath(path string, opts dirOptions) {
if opts != defaultDirOptions {
o.options[path] = opts
}
}
func (o *RepoOwners) filterCollaborators(toKeep []github.User) *RepoOwners {
collabs := sets.New[string]()
for _, keeper := range toKeep {
collabs.Insert(github.NormLogin(keeper.Login))
}
filter := func(ownerMap map[string]map[*regexp.Regexp]sets.Set[string]) map[string]map[*regexp.Regexp]sets.Set[string] {
filtered := make(map[string]map[*regexp.Regexp]sets.Set[string])
for path, reMap := range ownerMap {
filtered[path] = make(map[*regexp.Regexp]sets.Set[string])
for re, unfiltered := range reMap {
filtered[path][re] = unfiltered.Intersection(collabs)
}
}
return filtered
}
result := *o
result.approvers = filter(o.approvers)
result.reviewers = filter(o.reviewers)
return &result
}
// findOwnersForFile returns the OWNERS file path furthest down the tree for a specified file
// using ownerMap to check for entries
func findOwnersForFile(log *logrus.Entry, path string, ownerMap map[string]map[*regexp.Regexp]sets.Set[string]) string {
d := path
for ; d != baseDirConvention; d = canonicalize(filepath.Dir(d)) {
relative, err := filepath.Rel(d, path)
if err != nil {
log.WithError(err).WithField("path", path).Errorf("Unable to find relative path between %q and path.", d)
return ""
}
for re, n := range ownerMap[d] {
if re != nil && !re.MatchString(relative) {
continue
}
if len(n) != 0 {
return d
}
}
}
return ""
}
// FindApproverOwnersForFile returns the directory containing the OWNERS file furthest down the tree for a specified file
// that contains an approvers section
func (o *RepoOwners) FindApproverOwnersForFile(path string) string {
return findOwnersForFile(o.log, path, o.approvers)
}
// FindReviewersOwnersForFile returns the OWNERS file path furthest down the tree for a specified file
// that contains a reviewers section
func (o *RepoOwners) FindReviewersOwnersForFile(path string) string {
return findOwnersForFile(o.log, path, o.reviewers)
}
// FindLabelsForFile returns a set of labels which should be applied to PRs
// modifying files under the given path.
func (o *RepoOwners) FindLabelsForFile(path string) sets.Set[string] {
return o.entriesForFile(path, o.labels, false).Set()
}
// IsNoParentOwners checks if an OWNERS file path refers to an OWNERS file with NoParentOwners enabled.
func (o *RepoOwners) IsNoParentOwners(path string) bool {
return o.options[path].NoParentOwners
}
func (o *RepoOwners) IsAutoApproveUnownedSubfolders(ownersFilePath string) bool {
return o.options[ownersFilePath].AutoApproveUnownedSubfolders
}
// entriesForFile returns a set of users who are assignees to the
// requested file. The path variable should be a full path to a filename
// and not directory as the final directory will be discounted if enableMDYAML is true
// leafOnly indicates whether only the OWNERS deepest in the tree (closest to the file)
// should be returned or if all OWNERS in filepath should be returned
func (o *RepoOwners) entriesForFile(path string, people map[string]map[*regexp.Regexp]sets.Set[string], leafOnly bool) layeredsets.String {
d := path
if !o.enableMDYAML || !strings.HasSuffix(path, ".md") {
d = canonicalize(d)
}
out := layeredsets.NewString()
var layerID int
for {
relative, err := filepath.Rel(d, path)
if err != nil {
o.log.WithError(err).WithField("path", path).Errorf("Unable to find relative path between %q and path.", d)
return nil
}
for re, s := range people[d] {
if re == nil || re.MatchString(relative) {
out.Insert(layerID, sets.List(s)...)
}
}
if leafOnly && out.Len() > 0 {
break
}
if d == baseDirConvention {
break
}
if o.options[d].NoParentOwners && out.Len() > 0 {
break
}
d = filepath.Dir(d)
d = canonicalize(d)
layerID++
}
return out
}
// LeafApprovers returns a set of users who are the closest approvers to the
// requested file. If pkg/OWNERS has user1 and pkg/util/OWNERS has user2 this
// will only return user2 for the path pkg/util/sets/file.go
func (o *RepoOwners) LeafApprovers(path string) sets.Set[string] {
return o.entriesForFile(path, o.approvers, true).Set()
}
// Approvers returns ALL of the users who are approvers for the
// requested file (including approvers in parent dirs' OWNERS).
// If pkg/OWNERS has user1 and pkg/util/OWNERS has user2 this
// will return both user1 and user2 for the path pkg/util/sets/file.go
func (o *RepoOwners) Approvers(path string) layeredsets.String {
return o.entriesForFile(path, o.approvers, false)
}
// LeafReviewers returns a set of users who are the closest reviewers to the
// requested file. If pkg/OWNERS has user1 and pkg/util/OWNERS has user2 this
// will only return user2 for the path pkg/util/sets/file.go
func (o *RepoOwners) LeafReviewers(path string) sets.Set[string] {
return o.entriesForFile(path, o.reviewers, true).Set()
}
// Reviewers returns ALL of the users who are reviewers for the
// requested file (including reviewers in parent dirs' OWNERS).
// If pkg/OWNERS has user1 and pkg/util/OWNERS has user2 this
// will return both user1 and user2 for the path pkg/util/sets/file.go
func (o *RepoOwners) Reviewers(path string) layeredsets.String {
return o.entriesForFile(path, o.reviewers, false)
}
// RequiredReviewers returns ALL of the users who are required_reviewers for the
// requested file (including required_reviewers in parent dirs' OWNERS).
// If pkg/OWNERS has user1 and pkg/util/OWNERS has user2 this
// will return both user1 and user2 for the path pkg/util/sets/file.go
func (o *RepoOwners) RequiredReviewers(path string) sets.Set[string] {
return o.entriesForFile(path, o.requiredReviewers, false).Set()
}
func (o *RepoOwners) TopLevelApprovers() sets.Set[string] {
return o.entriesForFile(".", o.approvers, true).Set()
}
// AllOwners returns ALL of the users who are approvers or reviewers,
// at least for a file across the structure of the repository.
// If pkg/OWNERS has user1 as approver and user2 as reviewer,
// and pkg/util has user3 as approver and user4 as reviewer,
// the function will return user1, user2, user3, and user4.
func (o *RepoOwners) AllOwners() sets.Set[string] {
allOwners := sets.New[string]()
allOwners = allOwners.Union(o.AllApprovers())
allOwners = allOwners.Union(o.AllReviewers())
return allOwners
}
// AllApprovers returns ALL of the users who are approvers,
// at least for a file across the structure of the repository.
// If pkg/OWNERS has user1 as approver and user2 as reviewer,
// and pkg/util has user3 as approver and user4 as reviewer,
// the function will return user1, and user3.
func (o *RepoOwners) AllApprovers() sets.Set[string] {
allApprovers := sets.New[string]()
for _, pv := range o.approvers {
for _, rv := range pv {
allApprovers = allApprovers.Union(rv)
}
}
return allApprovers
}
// AllReviewers returns ALL of the users who are reviewers,
// at least for a file across the structure of the repository.
// If pkg/OWNERS has user1 as approver and user2 as reviewer,
// and pkg/util has user3 as approver and user4 as reviewer,
// the function will return user2, and user4.
func (o *RepoOwners) AllReviewers() sets.Set[string] {
allReviewers := sets.New[string]()
for _, pv := range o.reviewers {
for _, rv := range pv {
allReviewers = allReviewers.Union(rv)
}
}
return allReviewers
}