/
go_value.go
119 lines (92 loc) · 2.6 KB
/
go_value.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// Copyright 2024 The Carvel Authors.
// SPDX-License-Identifier: Apache-2.0
package core
import (
"fmt"
"carvel.dev/ytt/pkg/orderedmap"
"github.com/k14s/starlark-go/starlark"
)
type GoValueToStarlarkValueConversion interface {
AsStarlarkValue() starlark.Value
}
type GoValue struct {
val interface{}
opts GoValueOpts
}
type GoValueOpts struct {
MapIsStruct bool
Convert func(interface{}) (starlark.Value, bool)
}
func NewGoValue(val interface{}) GoValue {
return GoValue{val, GoValueOpts{}}
}
func NewGoValueWithOpts(val interface{}, opts GoValueOpts) GoValue {
return GoValue{val, opts}
}
func (e GoValue) AsStarlarkValue() starlark.Value {
return e.asStarlarkValue(e.val)
}
func (e GoValue) asStarlarkValue(val interface{}) starlark.Value {
if e.opts.Convert != nil {
converted, ok := e.opts.Convert(val)
if ok {
return converted
}
}
if obj, ok := val.(GoValueToStarlarkValueConversion); ok {
return obj.AsStarlarkValue()
}
switch typedVal := val.(type) {
case nil:
return starlark.None // TODO is it nil or is it None
case bool:
return starlark.Bool(typedVal)
case string:
return starlark.String(typedVal)
case int:
return starlark.MakeInt(typedVal)
case int64:
return starlark.MakeInt64(typedVal)
case uint:
return starlark.MakeUint(typedVal)
case uint64:
return starlark.MakeUint64(typedVal)
case float64:
return starlark.Float(typedVal)
case map[string]interface{}:
panic("Expected *orderedmap.Map instead of map[string]interface{} for conversion to starlark value")
case map[interface{}]interface{}:
panic("Expected *orderedmap.Map instead of map[interface{}]interface{} for conversion to starlark value")
case *orderedmap.Map:
return e.dictAsStarlarkValue(typedVal)
case []interface{}:
return e.listAsStarlarkValue(typedVal)
default:
panic(fmt.Sprintf("unknown type %T for conversion to starlark value", val))
}
}
func (e GoValue) dictAsStarlarkValue(val *orderedmap.Map) starlark.Value {
if e.opts.MapIsStruct {
data := orderedmap.NewMap()
val.Iterate(func(k, v interface{}) {
if keyStr, ok := k.(string); ok {
data.Set(keyStr, e.asStarlarkValue(v))
} else {
panic(fmt.Sprintf("expected struct key %s to be string", k)) // TODO
}
})
return &StarlarkStruct{data}
}
result := &starlark.Dict{}
val.Iterate(func(k, v interface{}) {
result.SetKey(e.asStarlarkValue(k), e.asStarlarkValue(v))
})
return result
}
func (e GoValue) listAsStarlarkValue(val []interface{}) *starlark.List {
result := []starlark.Value{}
for _, v := range val {
result = append(result, e.asStarlarkValue(v))
}
return starlark.NewList(result)
}