-
Notifications
You must be signed in to change notification settings - Fork 136
/
replace_annotation.go
67 lines (55 loc) · 1.84 KB
/
replace_annotation.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
package overlay
import (
"fmt"
"github.com/k14s/ytt/pkg/template"
tplcore "github.com/k14s/ytt/pkg/template/core"
"go.starlark.net/starlark"
)
type ReplaceAnnotation struct {
newNode template.EvaluationNode
thread *starlark.Thread
via *starlark.Value
}
func NewReplaceAnnotation(newNode template.EvaluationNode, thread *starlark.Thread) (ReplaceAnnotation, error) {
annotation := ReplaceAnnotation{
newNode: newNode,
thread: thread,
}
kwargs := template.NewAnnotations(newNode).Kwargs(AnnotationReplace)
for _, kwarg := range kwargs {
kwargName := string(kwarg[0].(starlark.String))
switch kwargName {
case "via":
annotation.via = &kwarg[1]
default:
return annotation, fmt.Errorf(
"Unknown '%s' annotation keyword argument '%s'", AnnotationReplace, kwargName)
}
}
return annotation, nil
}
func (a ReplaceAnnotation) Value(existingNode template.EvaluationNode) (interface{}, error) {
// Make sure original nodes are not affected in any way
existingNode = existingNode.DeepCopyAsInterface().(template.EvaluationNode)
newNode := a.newNode.DeepCopyAsInterface().(template.EvaluationNode)
// TODO currently assumes that we can always get at least one value
if a.via == nil {
return newNode.GetValues()[0], nil
}
switch typedVal := (*a.via).(type) {
case starlark.Callable:
viaArgs := starlark.Tuple{
tplcore.NewGoValue(existingNode.GetValues()[0], false).AsStarlarkValue(),
tplcore.NewGoValue(newNode.GetValues()[0], false).AsStarlarkValue(),
}
// TODO check thread correctness
result, err := starlark.Call(a.thread, *a.via, viaArgs, []starlark.Tuple{})
if err != nil {
return nil, err
}
return tplcore.NewStarlarkValue(result).AsInterface(), nil
default:
return nil, fmt.Errorf("Expected '%s' annotation keyword argument 'via'"+
" to be function, but was %T", AnnotationReplace, typedVal)
}
}