-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy patheval.go
100 lines (83 loc) · 2.41 KB
/
eval.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
package jsonnet
import (
jsonnet "github.com/google/go-jsonnet"
"github.com/pkg/errors"
"github.com/grafana/tanka/pkg/jsonnet/jpath"
"github.com/grafana/tanka/pkg/jsonnet/native"
)
// Modifier allows to set optional parameters on the Jsonnet VM.
// See jsonnet.With* for this.
type Modifier func(vm *jsonnet.VM) error
// InjectedCode holds data that is "late-bound" into the VM
type InjectedCode map[string]string
// Set allows to set values on an InjectedCode, even when it is nil
func (i *InjectedCode) Set(key, value string) {
if *i == nil {
*i = make(InjectedCode)
}
(*i)[key] = value
}
// Opts are additional properties for the Jsonnet VM
type Opts struct {
ExtCode InjectedCode
TLACode InjectedCode
ImportPaths []string
EvalScript string
}
// Clone returns a deep copy of Opts
func (o Opts) Clone() Opts {
var extCode, tlaCode InjectedCode
for k, v := range o.ExtCode {
extCode[k] = v
}
for k, v := range o.TLACode {
tlaCode[k] = v
}
return Opts{
TLACode: tlaCode,
ExtCode: extCode,
ImportPaths: append([]string{}, o.ImportPaths...),
EvalScript: o.EvalScript,
}
}
// MakeVM returns a Jsonnet VM with some extensions of Tanka, including:
// - extended importer
// - extCode and tlaCode applied
// - native functions registered
func MakeVM(opts Opts) *jsonnet.VM {
vm := jsonnet.MakeVM()
vm.Importer(NewExtendedImporter(opts.ImportPaths))
for k, v := range opts.ExtCode {
vm.ExtCode(k, v)
}
for k, v := range opts.TLACode {
vm.TLACode(k, v)
}
for _, nf := range native.Funcs() {
vm.NativeFunction(nf)
}
return vm
}
// EvaluateFile evaluates the Jsonnet code in the given file and returns the
// result in JSON form. It disregards opts.ImportPaths in favor of automatically
// resolving these according to the specified file.
func EvaluateFile(jsonnetFile string, opts Opts) (string, error) {
jpath, _, _, err := jpath.Resolve(jsonnetFile)
if err != nil {
return "", errors.Wrap(err, "resolving import paths")
}
opts.ImportPaths = jpath
vm := MakeVM(opts)
return vm.EvaluateFile(jsonnetFile)
}
// Evaluate renders the given jsonnet into a string
// TODO: don't resolve jpath, this is ANONYMOUS AFTER ALL
func Evaluate(path, data string, opts Opts) (string, error) {
jpath, _, _, err := jpath.Resolve(path)
if err != nil {
return "", errors.Wrap(err, "resolving import paths")
}
opts.ImportPaths = jpath
vm := MakeVM(opts)
return vm.EvaluateAnonymousSnippet(path, data)
}