cloudflare/pint

Public

mirrored from https://github.com/cloudflare/pintAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.18.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

internal/discovery/discovery.go

103lines · modecode

1package discovery
2
3import (
4 "os"
5 "regexp"
6 "strings"
7
8 "github.com/prometheus/prometheus/model/rulefmt"
9 "gopkg.in/yaml.v3"
10
11 "github.com/cloudflare/pint/internal/parser"
12
13 "github.com/rs/zerolog/log"
14)
15
16const (
17 FileOwnerComment = "file/owner"
18 RuleOwnerComment = "rule/owner"
19)
20
21type RuleFinder interface {
22 Find() ([]Entry, error)
23}
24
25type Entry struct {
26 Path string
27 PathError error
28 ModifiedLines []int
29 Rule parser.Rule
30 Owner string
31}
32
33func readFile(path string, isStrict bool) (entries []Entry, err error) {
34 p := parser.NewParser()
35
36 f, err := os.Open(path)
37 if err != nil {
38 return nil, err
39 }
40
41 content, err := parser.ReadContent(f)
42 f.Close()
43 if err != nil {
44 return nil, err
45 }
46
47 contentLines := []int{}
48 for i := 1; i <= strings.Count(string(content), "\n"); i++ {
49 contentLines = append(contentLines, i)
50 }
51
52 fileOwner, _ := parser.GetComment(string(content), FileOwnerComment)
53
54 if isStrict {
55 var r rulefmt.RuleGroups
56 if err = yaml.Unmarshal(content, &r); err != nil {
57 log.Error().Str("path", path).Err(err).Msg("Failed to unmarshal file content")
58 entries = append(entries, Entry{
59 Path: path,
60 PathError: err,
61 Owner: fileOwner.Value,
62 ModifiedLines: contentLines,
63 })
64 return entries, nil
65 }
66 }
67
68 rules, err := p.Parse(content)
69 if err != nil {
70 log.Error().Str("path", path).Err(err).Msg("Failed to parse file content")
71 entries = append(entries, Entry{
72 Path: path,
73 PathError: err,
74 Owner: fileOwner.Value,
75 ModifiedLines: contentLines,
76 })
77 return entries, nil
78 }
79
80 for _, rule := range rules {
81 owner, ok := rule.GetComment(RuleOwnerComment)
82 if !ok {
83 owner = fileOwner
84 }
85 entries = append(entries, Entry{
86 Path: path,
87 Rule: rule,
88 Owner: owner.Value,
89 })
90 }
91
92 log.Info().Str("path", path).Int("rules", len(entries)).Msg("File parsed")
93 return entries, nil
94}
95
96func matchesAny(re []*regexp.Regexp, s string) bool {
97 for _, r := range re {
98 if v := r.MatchString(s); v {
99 return true
100 }
101 }
102 return false
103}
104