cloudflare/pint

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.22.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

internal/discovery/discovery.go

112lines · modecode

1package discovery
2
3import (
4 "os"
5 "regexp"
6 "strings"
7
8 "github.com/prometheus/prometheus/model/rulefmt"
9
10 "github.com/cloudflare/pint/internal/output"
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 if _, errs := rulefmt.Parse(content); len(errs) > 0 {
56 for _, err := range errs {
57 log.Error().
58 Err(err).
59 Str("path", path).
60 Str("lines", output.FormatLineRangeString(contentLines)).
61 Msg("Failed to unmarshal file content")
62 entries = append(entries, Entry{
63 Path: path,
64 PathError: err,
65 Owner: fileOwner.Value,
66 ModifiedLines: contentLines,
67 })
68 return entries, nil
69 }
70 }
71 }
72
73 rules, err := p.Parse(content)
74 if err != nil {
75 log.Error().
76 Err(err).
77 Str("path", path).
78 Str("lines", output.FormatLineRangeString(contentLines)).
79 Msg("Failed to parse file content")
80 entries = append(entries, Entry{
81 Path: path,
82 PathError: err,
83 Owner: fileOwner.Value,
84 ModifiedLines: contentLines,
85 })
86 return entries, nil
87 }
88
89 for _, rule := range rules {
90 owner, ok := rule.GetComment(RuleOwnerComment)
91 if !ok {
92 owner = fileOwner
93 }
94 entries = append(entries, Entry{
95 Path: path,
96 Rule: rule,
97 Owner: owner.Value,
98 })
99 }
100
101 log.Info().Str("path", path).Int("rules", len(entries)).Msg("File parsed")
102 return entries, nil
103}
104
105func matchesAny(re []*regexp.Regexp, s string) bool {
106 for _, r := range re {
107 if v := r.MatchString(s); v {
108 return true
109 }
110 }
111 return false
112}
113