1
1
mirror of https://github.com/mcuadros/ascode synced 2024-11-23 01:11:59 +01:00

starlark/types: evaluate dict predeclared support

This commit is contained in:
Máximo Cuadros 2020-03-22 05:51:05 +01:00
parent 7b759a48ce
commit 505355fbf4
No known key found for this signature in database
GPG Key ID: 17A5DFEDC735AE4B
2 changed files with 51 additions and 4 deletions

@ -8,10 +8,42 @@ import (
"go.starlark.net/starlarkstruct"
)
// BuiltinEvaluate returns a starlak.Builtin function to evalute Starlark files.
//
// outline: types
// functions:
// evaluate(filename, predeclared=None) dict
// Evaluates a Starlark file and returns it's global context. Kwargs may
// be used to set predeclared.
// params:
// filename string
// Name of the file to execute.
// predeclared? dict
// Defines the predeclared context for the execution. Execution does
// not modify this dictionary
//
func BuiltinEvaluate() starlark.Value {
return starlark.NewBuiltin("evaluate", func(t *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var raw starlark.String
predeclared := starlark.StringDict{}
switch len(args) {
case 2:
dict, ok := args.Index(1).(*starlark.Dict)
if !ok {
return nil, fmt.Errorf("expected dict, got %s", args.Index(1).Type())
}
for i, key := range dict.Keys() {
if _, ok := key.(starlark.String); ok {
continue
}
return nil, fmt.Errorf("expected string keys in dict, got %s at index %d", key.Type(), i)
}
kwargs = append(dict.Items(), kwargs...)
fallthrough
case 1:
var ok bool
raw, ok = args.Index(0).(starlark.String)
@ -22,9 +54,8 @@ func BuiltinEvaluate() starlark.Value {
return nil, fmt.Errorf("unexpected positional arguments count")
}
dict := starlark.StringDict{}
for _, kwarg := range kwargs {
dict[kwarg.Index(0).(starlark.String).GoString()] = kwarg.Index(1)
predeclared[kwarg.Index(0).(starlark.String).GoString()] = kwarg.Index(1)
}
filename := raw.GoString()
@ -35,7 +66,7 @@ func BuiltinEvaluate() starlark.Value {
_, file := filepath.Split(filename)
name := file[:len(file)-len(filepath.Ext(file))]
global, err := starlark.ExecFile(t, filename, nil, dict)
global, err := starlark.ExecFile(t, filename, nil, predeclared)
return &starlarkstruct.Module{
Name: name,
Members: global,

@ -1,6 +1,22 @@
load("assert.star", "assert")
bar = "bar"
# context by kwargs
module = evaluate("evaluate/test.star", bar=bar)
assert.eq(str(module), '<module "test">')
assert.eq(module.foo, bar)
assert.eq(module.foo, bar)
# context by dict
module = evaluate("evaluate/test.star", {"bar": bar})
assert.eq(str(module), '<module "test">')
assert.eq(module.foo, bar)
# context dict overrided by kwargs
module = evaluate("evaluate/test.star", {"bar": bar}, bar="foo")
assert.eq(str(module), '<module "test">')
assert.eq(module.foo, "foo")
# context dict with non strings
def contextNonString(): evaluate("evaluate/test.star", {1: bar})
assert.fails(contextNonString, "expected string keys in dict, got int at index 0")