-
Notifications
You must be signed in to change notification settings - Fork 1
/
multiglob.go
384 lines (329 loc) · 8.62 KB
/
multiglob.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package multiglob
import (
"strings"
"unicode/utf8"
"github.com/pkg/errors"
"github.com/szabado/multiglob/internal/parser"
)
// Builder builds a MultiGlob.
type Builder struct {
patterns map[string]*parser.Node
}
// New returns a new Builder that can be used to create a MultiGlob.
func New() *Builder {
return &Builder{
patterns: make(map[string]*parser.Node),
}
}
// AddPattern adds the provided pattern to the builder and parses it.
func (m *Builder) AddPattern(name, pattern string) error {
p, err := parser.Parse(name, pattern)
if err != nil {
return errors.Wrap(err, "failed to add pattern")
}
m.patterns[name] = p
return err
}
// MustAddPattern wraps AddPattern, and panics if there is an error.
func (m *Builder) MustAddPattern(name, pattern string) {
err := m.AddPattern(name, pattern)
if err != nil {
panic(err)
}
}
// Compile merges all the compiled patterns into one MultiGlob and returns it.
func (m *Builder) Compile() (*MultiGlob, error) {
var final *parser.Node
for _, p := range m.patterns {
if final == nil {
final = p
} else {
final = parser.Merge(final, p)
}
}
patterns := make(map[string]*parser.Node)
for k, v := range m.patterns {
patterns[k] = v
}
return &MultiGlob{
node: final,
patterns: patterns,
}, nil
}
// MustCompile wraps Compile, and panics if there is an error.
func (m *Builder) MustCompile() *MultiGlob {
mg, err := m.Compile()
if err != nil {
panic(err)
}
return mg
}
// MultiGlob is a matcher that is built from a collection of patterns. See Builder.
type MultiGlob struct {
node *parser.Node
patterns map[string]*parser.Node
}
// Match determines if any pattern matches the provided string.
func (mg *MultiGlob) Match(input string) bool {
_, matched := match(mg.node, input, false)
return matched
}
// FindAllPatterns returns a list containing all patterns that matched this input.
func (mg *MultiGlob) FindAllPatterns(input string) []string {
results, _ := match(mg.node, input, true)
duplicates := make(map[string]bool)
cleaned := make([]string, 0, len(results))
for _, result := range results {
if duplicates[result] {
continue
}
duplicates[result] = true
cleaned = append(cleaned, result)
}
return cleaned
}
// FindPattern returns one pattern out of the set of patterns that matches input.
// There is no guarantee as to which of the patterns will be returned. Returns true
// if a pattern was matched.
func (mg *MultiGlob) FindPattern(input string) (string, bool) {
results, ok := match(mg.node, input, false)
if !ok || len(results) < 1 {
return "", false
}
return results[0], true
}
// FindAllGlobs returns a map of pattern names to globs extracted using each pattern.
// It uses all the patterns returned FindAllPatterns. See FindGlobs for an explanation
// of glob extraction.
func (mg *MultiGlob) FindAllGlobs(input string) map[string][]string {
patternNames := mg.FindAllPatterns(input)
globs := make(map[string][]string)
for _, name := range patternNames {
g, _ := extractGlobs(input, mg.patterns[name])
globs[name] = g
}
return globs
}
// FindGlobs finds a matching pattern using FindPattern, and then extracts the globs
// from the input based on that pattern. It also returns the name of the pattern
// matched. This uses a greedy matching algorithm. For example:
//
// Input: "test"
// Pattern Found: "t*t"
// Globs: ["es"]
//
// Input: "pen pineapple apple pen"
// Pattern Found: "*apple*"
// Globs: ["pen pineapple ", " pen"]
func (mg *MultiGlob) FindGlobs(input string) (name string, globs []string, matched bool) {
name, ok := mg.FindPattern(input)
if !ok {
return "", nil, false
}
globs, _ = extractGlobs(input, mg.patterns[name])
return name, globs, true
}
// FindGlobsForPattern extracts the globs from input using the named pattern.
func (mg *MultiGlob) FindGlobsForPattern(input, name string) (globs []string, err error) {
if ast, ok := mg.patterns[name]; !ok {
return nil, errors.New("pattern not found")
} else {
globs, err := extractGlobs(input, ast)
if err != nil {
return nil, errors.New("pattern did not match input")
}
return globs, nil
}
}
var errTextNotFound = errors.New("text not found")
// extractGlobs returns the globs based on the pattern. It either returns a nil error or
// errTextNotFound
func extractGlobs(input string, ast *parser.Node) ([]string, error) {
var globs []string
for leafConsumed := false; !leafConsumed && ast != nil; {
switch ast.Type {
case parser.TypeText:
if !strings.HasPrefix(input, ast.Value) {
return nil, errTextNotFound
}
input = trimString(input, len(ast.Value))
if ast.Leaf {
leafConsumed = true
}
case parser.TypeAny:
// It's globbing time, baby!
if ast.Leaf {
globs = append(globs, input)
leafConsumed = true
break
} else if input == "" {
return nil, errTextNotFound
}
// Consume as much as possible, and then slowly consume less until we find a
// match or can't consume any less
for globbed := input; globbed != ""; {
child := ast.Children[0]
globEnds := child.LastIndex(globbed)
if globEnds < 0 {
return nil, errTextNotFound
}
globbed = globbed[:globEnds]
subglobs, err := extractGlobs(input[globEnds:], child)
if err != nil {
continue
}
// we found our match!
globs = append(globs, globbed)
globs = append(globs, subglobs...)
leafConsumed = true
break
}
case parser.TypeRange:
lastIndex := -1
for i, r := range input {
if !ast.Range.Matches(r) {
break
}
lastIndex = i
if !ast.Range.Repeated {
break
}
}
if lastIndex < 0 {
return nil, errTextNotFound
}
lastIndex++
if ast.Leaf {
if lastIndex == len(input) {
globs = append(globs, input)
leafConsumed = true
break
} else {
return nil, errTextNotFound
}
}
for globbed := input[:lastIndex]; globbed != ""; {
r, size := utf8.DecodeLastRuneInString(globbed)
if r == utf8.RuneError && size < 2 {
return nil, errTextNotFound
}
globEnds := len(globbed) - size + 1
// we've found a match. Recurse on the tail of input
subglobs, err := extractGlobs(input[globEnds:], ast.Children[0])
if err != nil {
// Shrink what is globbed by one
globbed = globbed[:globEnds-1]
continue
}
// We've found our match!
globs = append(globs, globbed)
globs = append(globs, subglobs...)
leafConsumed = true
break
}
}
if !ast.Leaf {
ast = ast.Children[0]
}
}
return globs, nil
}
func match(node *parser.Node, input string, exhaustive bool) ([]string, bool) {
var (
results []string
)
switch node.Type {
case parser.TypeAny:
if node.Leaf {
if !exhaustive {
return node.Name, true
}
results = merge(results, node.Name)
}
for _, child := range node.Children {
tempInput := input
for i := child.Index(tempInput); i >= 0; i = child.Index(tempInput) {
names, ok := match(child, trimString(tempInput, i), exhaustive)
tempInput = trimString(tempInput, i+len(child.Value))
if !ok {
continue
}
if !exhaustive {
return names, true
}
results = merge(results, names)
}
}
case parser.TypeText:
if node.Leaf && node.Value == input {
if !exhaustive {
return node.Name, true
}
results = merge(results, node.Name)
} else if !strings.HasPrefix(input, node.Value) {
return nil, false
}
input = trimString(input, len(node.Value))
for _, c := range node.Children {
names, ok := match(c, input, exhaustive)
if !ok {
continue
}
if !exhaustive {
return names, true
}
results = merge(results, names)
}
case parser.TypeRange:
short := input
for _, r := range input {
if !node.Range.Matches(r) {
break
}
short = strings.TrimPrefix(short, string(r))
for _, child := range node.Children {
names, ok := match(child, short, exhaustive)
if !ok {
continue
}
if !exhaustive {
return names, true
}
results = merge(results, names)
}
if !node.Range.Repeated {
break
}
}
if node.Leaf && short == "" && len(short) != len(input) {
results = append(results, node.Name...)
}
case parser.TypeRoot:
for _, c := range node.Children {
names, ok := match(c, input, exhaustive)
if !ok {
continue
}
if !exhaustive {
return names, true
}
results = merge(results, names)
}
}
return results, len(results) != 0
}
func trimString(s string, prefixLen int) string {
if len(s) <= prefixLen {
return ""
}
return s[prefixLen:]
}
func merge(sl1, sl2 []string) []string {
if sl2 == nil {
return sl1
} else if sl1 == nil {
return sl2
} else {
return append(sl1, sl2...)
}
}