Repository navigation
Expand file tree
/
Copy pathjsonnet.go
More file actions
55 lines (52 loc) · 1.56 KB
/
Copy pathjsonnet.go
File metadata and controls
55 lines (52 loc) · 1.56 KB
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
package ecschedule
import (
"fmt"
"os"
"github.com/google/go-jsonnet"
"github.com/google/go-jsonnet/ast"
)
// newJsonnetVM creates a jsonnet VM with native functions registered for
// accessing OS environment variables at jsonnet evaluation time.
//
// Registered native functions:
// - must_env(name): returns env var `name`; errors if unset.
// - env(name, default): returns env var `name`, or `default` if unset.
//
// These mirror the Go template helpers in template.go. They are required
// for setting non-string fields (e.g., `disabled: bool`) conditionally per
// environment, which cannot be done via the post-evaluation Go template
// substitution because that operates on JSON byte streams (string values
// only).
func newJsonnetVM() *jsonnet.VM {
vm := jsonnet.MakeVM()
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "must_env",
Params: []ast.Identifier{"name"},
Func: func(args []interface{}) (interface{}, error) {
key, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("must_env: name must be a string")
}
v, ok := os.LookupEnv(key)
if !ok {
return nil, fmt.Errorf("must_env: environment variable %q is not set", key)
}
return v, nil
},
})
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "env",
Params: []ast.Identifier{"name", "default"},
Func: func(args []interface{}) (interface{}, error) {
key, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("env: name must be a string")
}
if v, ok := os.LookupEnv(key); ok {
return v, nil
}
return args[1], nil
},
})
return vm
}