diff options
author | alandonovan <adonovan@google.com> | 2019-05-28 16:29:25 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-05-28 16:29:25 -0400 |
commit | 30ae18b8564f6cd89b550b19dbdae92e0ec5b0a3 (patch) | |
tree | 4dc401c332185e222fe4c11bc8f67726467c2f6b /starlark | |
parent | 30b8578fa64c28cd0eba7c928f27a535ac0f81b8 (diff) | |
download | starlark-go-30ae18b8564f6cd89b550b19dbdae92e0ec5b0a3.tar.gz |
starlark: add a fail function (#210)
Updates bazelbuild/starlark#47
Diffstat (limited to 'starlark')
-rw-r--r-- | starlark/library.go | 24 | ||||
-rw-r--r-- | starlark/testdata/builtins.star | 11 |
2 files changed, 35 insertions, 0 deletions
diff --git a/starlark/library.go b/starlark/library.go index b747a63..54f1528 100644 --- a/starlark/library.go +++ b/starlark/library.go @@ -10,6 +10,7 @@ package starlark // mutable types such as lists and dicts. import ( + "errors" "fmt" "log" "math/big" @@ -46,6 +47,7 @@ func init() { "dict": NewBuiltin("dict", dict), "dir": NewBuiltin("dir", dir), "enumerate": NewBuiltin("enumerate", enumerate), + "fail": NewBuiltin("fail", fail), "float": NewBuiltin("float", float), // requires resolve.AllowFloat "getattr": NewBuiltin("getattr", getattr), "hasattr": NewBuiltin("hasattr", hasattr), @@ -501,6 +503,28 @@ func enumerate(thread *Thread, _ *Builtin, args Tuple, kwargs []Tuple) (Value, e return NewList(pairs), nil } +// https://github.com/google/starlark-go/blob/master/doc/spec.md#fail +func fail(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { + sep := " " + if err := UnpackArgs("fail", nil, kwargs, "sep?", &sep); err != nil { + return nil, err + } + buf := new(strings.Builder) + buf.WriteString("fail: ") + for i, v := range args { + if i > 0 { + buf.WriteString(sep) + } + if s, ok := AsString(v); ok { + buf.WriteString(s) + } else { + writeValue(buf, v, nil) + } + } + + return nil, errors.New(buf.String()) +} + func float(thread *Thread, b *Builtin, args Tuple, kwargs []Tuple) (Value, error) { if len(kwargs) > 0 { return nil, fmt.Errorf("float does not accept keyword arguments") diff --git a/starlark/testdata/builtins.star b/starlark/testdata/builtins.star index 90b06b1..2385c16 100644 --- a/starlark/testdata/builtins.star +++ b/starlark/testdata/builtins.star @@ -211,3 +211,14 @@ assert.fails(setfield, 'no .noForty_Five field.*did you mean .forty_five') assert.eq(repr(1), "1") assert.eq(repr("x"), '"x"') assert.eq(repr(["x", 1]), '["x", 1]') + +# fail +--- +fail() ### `fail: $` +x = 1//0 # unreachable +--- +fail(1) ### `fail: 1` +--- +fail(1, 2, 3) ### `fail: 1 2 3` +--- +fail(1, 2, 3, sep="/") ### `fail: 1/2/3` |