...
1 package internal
2
3 import (
4 "fmt"
5 "regexp"
6 "strings"
7
8 "sigs.k8s.io/kustomize/kyaml/yaml"
9
10 "edge-infra.dev/pkg/f8n/warehouse/capability"
11 "edge-infra.dev/pkg/f8n/warehouse/lift"
12 )
13
14
15
16 type Capability struct {
17 Name capability.Capability
18
19
20
21 regexps []*regexp.Regexp
22
23 ignoreKinds map[string]bool
24 ignoreAPIGroups map[string]bool
25 }
26
27 func (c Capability) Matches(y *yaml.RNode) bool {
28 apiVersion := y.GetApiVersion()
29 if apiVersion == "" {
30 return false
31 }
32
33 apiGroup := strings.ToLower(strings.Split(apiVersion, "/")[0])
34 if !matchesAny(c.regexps, apiGroup) {
35 return false
36 }
37
38
39 kind := strings.ToLower(y.GetKind())
40
41 return !(c.ignoreKinds[kind] || c.ignoreAPIGroups[apiGroup])
42 }
43
44 func NewCapability(name capability.Capability, cfg lift.CapabilityConfig) (Capability, error) {
45 c := Capability{
46 Name: name,
47 regexps: make([]*regexp.Regexp, len(cfg.ResourceMatcher.APIGroups)),
48 ignoreKinds: make(map[string]bool, len(cfg.ResourceMatcher.Ignore.Kinds)),
49 ignoreAPIGroups: make(map[string]bool, len(cfg.ResourceMatcher.Ignore.APIGroups)),
50 }
51
52 for _, i := range cfg.ResourceMatcher.Ignore.Kinds {
53 c.ignoreKinds[strings.ToLower(i)] = true
54 }
55
56 for _, i := range cfg.ResourceMatcher.Ignore.APIGroups {
57 c.ignoreAPIGroups[strings.ToLower(i)] = true
58 }
59
60 for i, a := range cfg.ResourceMatcher.APIGroups {
61 r, err := regexp.Compile(strings.ToLower(a))
62 if err != nil {
63 return Capability{}, fmt.Errorf("invalid capability provider: invalid APIGroup "+
64 "regular expression %s: %w", a, err)
65 }
66 c.regexps[i] = r
67 }
68
69 return c, nil
70 }
71
72 func matchesAny(rr []*regexp.Regexp, s string) bool {
73 for _, r := range rr {
74 if r.MatchString(strings.ToLower(s)) {
75 return true
76 }
77 }
78 return false
79 }
80
View as plain text