grafana/pkg/kindsysreport/codeowners.go
Kristin Laemmert 8745d7ef1b
extract kindsys to external library (#64562)
* extract kindsys

* reinstate kindsys report

This may end up living somewhere else (or not! who knows!), but the important part is that I don't get rid of it right now :)

I hate the package layout (kindsysreport/codegen) for the main function and will take pretty much any alternative suggestion, but we can change also change it later.

Note that the generated report.json is in a different location - anything using this (ops something) needs to be updated.

* kindsysreport in codeowners
2023-03-15 12:04:28 -04:00

62 lines
1.0 KiB
Go

package kindsysreport
import (
"os"
"path/filepath"
"github.com/hmarr/codeowners"
)
type CodeOwnersFinder struct {
ruleset codeowners.Ruleset
}
func NewCodeOwnersFinder(groot string) (CodeOwnersFinder, error) {
//nolint:gosec
file, err := os.Open(filepath.Join(groot, ".github", "CODEOWNERS"))
if err != nil {
return CodeOwnersFinder{}, err
}
ruleset, err := codeowners.ParseFile(file)
if err != nil {
return CodeOwnersFinder{}, err
}
return CodeOwnersFinder{
ruleset: ruleset,
}, nil
}
func (f CodeOwnersFinder) FindFor(pp ...string) ([]string, error) {
if len(f.ruleset) == 0 {
return nil, nil
}
// Set, to avoid duplicates
m := make(map[string]struct{})
for _, p := range pp {
r, err := f.ruleset.Match(p)
if err != nil {
return nil, err
}
// No rule found for path p
if r == nil {
continue
}
for _, o := range r.Owners {
m[o.Value] = struct{}{}
}
}
result := make([]string, 0, len(m))
for k := range m {
result = append(result, k)
}
return result, nil
}