Debian Codegraph @

pkg/detectors/helpers/key_value_regex.go

raw symbols SCIP
1 package helpers
2
3 import (
4 "fmt"
5 "regexp"
6 "strings"
7
8 "github.com/hashicorp/go-multierror"
9 )
10
11 // opt = optional
12 const (
13 multilineFlag = `(?m)`
14 linePrefix = `(?:^|[\t ]+)`
15 optDeclareKeyword = `(?i)(?:(?:var|let|set|dim|declare|export|const|readonly)[\t ]+)?(?-i)`
16 keyOptPrefix = `\[?[\t ]*['"]?`
17 defaultKeyCaptureGroup = `([\t a-zA-Z0-9$\/_-]+)`
18 keyOptSuffix = `['"]?[\t ]*\]?`
19 delimiterCaptureGroup = `\s*(:|=|:=)\s*`
20 delimiterCaptureGroupWithoutNewLines = `[^\S\r\n]*(:|=|:=)[^\S\r\n]*`
21 valueOptPrefix = `\[?[\t ]*['"]?`
22 placeholderCaptureGroup = `(%s)`
23 valueOptSuffix = `['"]?[\t ]*\]?[\t ]*;?`
24 lineSuffix = `(?:[\t ]+|$)`
25
26 // defaultKeyValueRegex = (?m)(?:^|[\t ]+)(?:(?i)(?:(?:var|let|set|dim|declare|export|const|readonly)[\t ]+)?(?-i)\[?[\t ]*['"]?([\t a-zA-Z0-9$\/_-]+)['"]?[\t ]*\]?\s*(:|=|:=)\s*)?\[?[\t ]*['"]?(%s)['"]?[\t ]*\]?[\t ]*;?(?:[\t ]+|$)
27 defaultKeyValueRegex = multilineFlag + linePrefix +
28 `(?:` + optDeclareKeyword + keyOptPrefix + defaultKeyCaptureGroup + keyOptSuffix + delimiterCaptureGroup + `)?` +
29 valueOptPrefix + placeholderCaptureGroup + valueOptSuffix + lineSuffix
30
31 // defaultKeyValueRegexWithoutNewLine = (?m)(?:^|[\t ]+)(?:(?i)(?:(?:var|let|set|dim|declare|export|const|readonly)[\t ]+)?(?-i)\[?[\t ]*['"]?([\t a-zA-Z0-9$\/_-]+)['"]?[\t ]*\]?[^\S\r\n]*(:|=|:=)[^\S\r\n]*)?\[?[\t ]*['"]?(%s)['"]?[\t ]*\]?[\t ]*;?(?:[\t ]+|$)
32 defaultKeyValueRegexWithoutNewLine = multilineFlag + linePrefix +
33 `(?:` + optDeclareKeyword + keyOptPrefix + defaultKeyCaptureGroup + keyOptSuffix + delimiterCaptureGroupWithoutNewLines + `)?` +
34 valueOptPrefix + placeholderCaptureGroup + valueOptSuffix + lineSuffix
35
36 // keyValueRegex = (?m)(?:^|[\t ]+)(?i)(?:(?:var|let|set|dim|declare|export|const|readonly)[\t ]+)?(?-i)\[?[\t ]*['"]?(%s)['"]?[\t ]*\]?\s*(:|=|:=)\s*\[?[\t ]*['"]?(%s)['"]?[\t ]*\]?[\t ]*;?(?:[\t ]+|$)
37 keyValueRegex = multilineFlag + linePrefix +
38 optDeclareKeyword + keyOptPrefix + placeholderCaptureGroup + keyOptSuffix + delimiterCaptureGroup +
39 valueOptPrefix + placeholderCaptureGroup + valueOptSuffix + lineSuffix
40 )
41
42 type MatchResult struct {
43 FullMatch string
44 Key string
45 Delimiter string
46 Value string
47 ValueSubmatches []string
48 }
49
50 // KeyValueRegex should match strings in a structure of key (default or injected via NewKeyValueRegex), a delimiter,
51 //
52 // and value injected via argument.
53 //
54 // Expected pattern examples:
55 //
56 // key: value
57 // "key": "value"
58 // key=value
59 // "key" = 'value'
60 // key := value
61 // [ "key" ] = [ "value" ] ;
62 // value
63 // "value"
64 //
65 // Regex breakdown:
66 //
67 // Key:
68 // (?i)(?:(?:var|let|set|dim|declare|export|const|readonly)[\t ]+)?(?-i)
69 // an optional declaration keyword from commonly used languages like bash, powershell, JS.
70 // supported keywords: var, let, set, dim, declare, export, const, readonly
71 //
72 // \[?[\t ]*['"]? an optional prefix: a square bracket ([) and a single (') or double quote (").
73 // ([\t a-zA-Z0-9\/_-]+) default key name pattern, comprised of letters, digits, spaces, tabs, slash (/),
74 // underscore (_) and dash (-).
75 // captured as capture group #1.
76 // ['"]?[\t ]*\]? an optional suffix: single (') or double quote (") and a square bracket (]).
77 //
78 // Delimiter:
79 // \s* optional whitespaces between key and delimiter.
80 // (:|=|:=) a delimiter: colon (:), equal sign (=), or colon equal sign (:=).
81 // captured as capture group #2.
82 // \s* optional whitespaces between delimiter and value.
83 //
84 // (?: )? key and delimiter regex are surrounded by an optional non-capturing group.
85 // That makes the key and delimiter optional (they are capture only if both exist).
86 //
87 // [^\S\r\n]* the regex without new line uses it, the \S is negative of all whitespaces and by using ^ on this we get all the whitespaces, together with \r\n we have all whitespaces except new lines.
88 //
89 // Value:
90 // \[?[\t ]*['"]? an optional prefix: a square bracket ([) and a single (') or double quote (").
91 // (%s) the value regex will be injected here.
92 // captured as capture group #3.
93 // internal capturing groups inside value regex will be captured as #4-#n.
94 // ['"]?[\t ]*\]?[\t ]*;? an optional suffix: single (') or double quote ("), a square bracket (]) and a semicolon (;).
95 type KeyValueRegex struct {
96 keyValueRegex []*regexp.Regexp
97 }
98
99 func NewDefaultKeyValueRegex(valueRegex ...string) *KeyValueRegex {
100 s := make([]*regexp.Regexp, 0, len(valueRegex))
101 for _, regex := range valueRegex {
102 s = append(s, regexp.MustCompile(fmt.Sprintf(defaultKeyValueRegex, regex)))
103 }
104
105 return &KeyValueRegex{
106 keyValueRegex: s,
107 }
108 }
109
110 func NewDefaultKeyValueRegexWithoutNewLine(valueRegex ...string) *KeyValueRegex {
111 s := make([]*regexp.Regexp, 0, len(valueRegex))
112 for _, regex := range valueRegex {
113 s = append(s, regexp.MustCompile(fmt.Sprintf(defaultKeyValueRegexWithoutNewLine, regex)))
114 }
115
116 return &KeyValueRegex{
117 keyValueRegex: s,
118 }
119 }
120
121 func NewKeyValueRegex(keyRegex, valueRegex string) *KeyValueRegex {
122 return &KeyValueRegex{
123 keyValueRegex: []*regexp.Regexp{
124 regexp.MustCompile(fmt.Sprintf(keyValueRegex, keyRegex, valueRegex)),
125 },
126 }
127 }
128
129 func (r *KeyValueRegex) FindAll(in string) ([]MatchResult, error) {
130 res := make([]MatchResult, 0)
131 var err error
132 for _, regex := range r.keyValueRegex {
133 currRes, currErr := findAll(in, regex)
134 res = append(res, currRes...)
135 if currErr != nil {
136 err = multierror.Append(currErr)
137 }
138 }
139 return res, err
140 }
141
142 func findAll(in string, regex *regexp.Regexp) ([]MatchResult, error) {
143 submatches := regex.FindAllStringSubmatch(in, -1)
144 if len(submatches) == 0 {
145 return nil, nil
146 }
147
148 res := make([]MatchResult, 0, len(submatches))
149 var err error
150 for _, submatch := range submatches {
151 if len(submatch) < 4 {
152 // This should never happen since the base key-value regex have 3 capture groups + first is the full match
153 err = multierror.Append(err,
154 fmt.Errorf("unexpected number of submatches. regex=%s, input=%s, match=%v", regex, in, submatch),
155 )
156 continue
157 }
158
159 result := MatchResult{
160 FullMatch: strings.TrimSpace(submatch[0]),
161 Key: strings.TrimSpace(submatch[1]),
162 Delimiter: strings.TrimSpace(submatch[2]),
163 Value: strings.TrimSpace(submatch[3]),
164 ValueSubmatches: submatch[4:],
165 }
166 res = append(res, result)
167 }
168 return res, err
169 }