-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
prefix.go
96 lines (80 loc) · 2.17 KB
/
prefix.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
package fileglob
import (
"fmt"
"strings"
"github.com/gobwas/glob/syntax/ast"
"github.com/gobwas/glob/syntax/lexer"
)
// ValidPattern determines whether a pattern is valid. It returns the parser
// error if the pattern is invalid and nil otherwise.
func ValidPattern(pattern string) error {
_, err := ast.Parse(lexer.NewLexer(pattern))
return err // nolint:wrapcheck
}
// ContainsMatchers determines whether the pattern contains any type of glob
// matcher. It will also return false if the pattern is an invalid expression.
func ContainsMatchers(pattern string) bool {
rootNode, err := ast.Parse(lexer.NewLexer(pattern))
if err != nil {
return false
}
_, isStatic := staticText(rootNode)
return !isStatic
}
// staticText returns the static string matcher represented by the AST unless
// it contains dynamic matchers (wildcards, etc.). In this case the ok return
// value is false.
func staticText(node *ast.Node) (text string, ok bool) {
// nolint:exhaustive
switch node.Kind {
case ast.KindPattern:
text := ""
for _, child := range node.Children {
childText, ok := staticText(child)
if !ok {
return "", false
}
text += childText
}
return text, true
case ast.KindText:
t, ok := node.Value.(ast.Text)
if !ok {
return "", false
}
return t.Text, true
case ast.KindNothing:
return "", true
default:
return "", false
}
}
// staticPrefix returns the file path inside the pattern up
// to the first path element that contains a wildcard.
func staticPrefix(pattern string) (string, error) {
parts := strings.Split(pattern, separatorString)
// nolint:prealloc
var prefixPath []string
for _, part := range parts {
if part == "" {
continue
}
rootNode, err := ast.Parse(lexer.NewLexer(part))
if err != nil {
return "", fmt.Errorf("parse glob pattern: %w", err)
}
staticPart, ok := staticText(rootNode)
if !ok {
break
}
prefixPath = append(prefixPath, staticPart)
}
prefix := strings.Join(prefixPath, separatorString)
if len(pattern) > 0 && rune(pattern[0]) == separatorRune && !strings.HasPrefix(prefix, separatorString) {
prefix = separatorString + prefix
}
if prefix == "" {
prefix = "."
}
return prefix, nil
}