-
Notifications
You must be signed in to change notification settings - Fork 4
/
ancestor.go
49 lines (44 loc) · 1.49 KB
/
ancestor.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
package iamcel
import (
"github.com/google/cel-go/checker/decls"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/interpreter/functions"
"go.einride.tech/aip/resourcename"
expr "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
// AncestorFunction is the name of the CEL ancestor function.
const AncestorFunction = "ancestor"
const ancestorFunctionOverload = "ancestor_string_string"
// NewAncestorFunctionDeclaration creates a new declaration for the ancestor function.
func NewAncestorFunctionDeclaration() *expr.Decl {
return decls.NewFunction(
AncestorFunction,
decls.NewOverload(
ancestorFunctionOverload,
[]*expr.Type{decls.String, decls.String},
decls.String,
),
)
}
// NewAncestorFunctionImplementation creates a new implementation for the ancestor function.
func NewAncestorFunctionImplementation() *functions.Overload {
return &functions.Overload{
Operator: ancestorFunctionOverload,
Binary: func(nameVal, patternVal ref.Val) ref.Val {
name, ok := nameVal.Value().(string)
if !ok {
return types.NewErr("parent: unexpected type of arg 1, expected string but got %T", nameVal.Value())
}
pattern, ok := patternVal.Value().(string)
if !ok {
return types.NewErr("parent: unexpected type of arg 2, expected string but got %T", patternVal.Value())
}
result, ok := resourcename.Ancestor(name, pattern)
if !ok {
return types.String("")
}
return types.String(result)
},
}
}