forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glob.go
61 lines (48 loc) · 1.25 KB
/
glob.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
package topdown
import (
"fmt"
"sync"
"github.com/gobwas/glob"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/topdown/builtins"
)
var globCacheLock = sync.Mutex{}
var globCache map[string]glob.Glob
func builtinGlobMatch(a, b, c ast.Value) (ast.Value, error) {
pattern, err := builtins.StringOperand(a, 1)
if err != nil {
return nil, err
}
delimiters, err := builtins.RuneSliceOperand(b, 2)
if err != nil {
return nil, err
}
match, err := builtins.StringOperand(c, 3)
if err != nil {
return nil, err
}
id := fmt.Sprintf("%s-%v", pattern, delimiters)
globCacheLock.Lock()
defer globCacheLock.Unlock()
p, ok := globCache[id]
if !ok {
var err error
if p, err = glob.Compile(string(pattern), delimiters...); err != nil {
return nil, err
}
globCache[id] = p
}
return ast.Boolean(p.Match(string(match))), nil
}
func builtinGlobQuoteMeta(a ast.Value) (ast.Value, error) {
pattern, err := builtins.StringOperand(a, 1)
if err != nil {
return nil, err
}
return ast.String(glob.QuoteMeta(string(pattern))), nil
}
func init() {
globCache = map[string]glob.Glob{}
RegisterFunctionalBuiltin3(ast.GlobMatch.Name, builtinGlobMatch)
RegisterFunctionalBuiltin1(ast.GlobQuoteMeta.Name, builtinGlobQuoteMeta)
}