-
Notifications
You must be signed in to change notification settings - Fork 293
/
string.go
76 lines (63 loc) · 1.45 KB
/
string.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
package value
import (
"fmt"
"go.starlark.net/starlark"
)
type Stringable struct {
Value string
}
func (s *Stringable) Unpack(v starlark.Value) error {
str, ok := AsString(v)
if !ok {
return fmt.Errorf("Value should be convertible to string, but is type %s", v.Type())
}
s.Value = str
return nil
}
type ImplicitStringer interface {
ImplicitString() string
}
// Wrapper around starlark.AsString
func AsString(x starlark.Value) (string, bool) {
is, ok := x.(ImplicitStringer)
if ok {
return is.ImplicitString(), true
}
return starlark.AsString(x)
}
type StringOrStringList struct {
Values []string
}
var _ starlark.Unpacker = &StringOrStringList{}
// Unpack an argument that can either be expressed as
// a string or as a list of strings.
func (s *StringOrStringList) Unpack(v starlark.Value) error {
s.Values = nil
if v == nil {
return nil
}
vs, ok := AsString(v)
if ok {
s.Values = []string{vs}
return nil
}
var iter starlark.Iterator
switch x := v.(type) {
case *starlark.List:
iter = x.Iterate()
case starlark.Tuple:
iter = x.Iterate()
default:
return fmt.Errorf("value should be a string or List or Tuple of strings, but is of type %s", v.Type())
}
defer iter.Done()
var item starlark.Value
for iter.Next(&item) {
sv, ok := AsString(item)
if !ok {
return fmt.Errorf("list should contain only strings, but element %q was of type %s", item.String(), item.Type())
}
s.Values = append(s.Values, sv)
}
return nil
}