-
Notifications
You must be signed in to change notification settings - Fork 77
/
op_empty.go
69 lines (58 loc) · 1.46 KB
/
op_empty.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
package spruce
import (
"fmt"
"strings"
"github.com/starkandwayne/goutils/tree"
)
// EmptyOperator allows the user to emplace an empty array, hash, or string into
// the YAML datastructure.
type EmptyOperator struct{}
// Setup ...
func (EmptyOperator) Setup() error {
return nil
}
// Phase ...
func (EmptyOperator) Phase() OperatorPhase {
return EvalPhase
}
// Dependencies ...
func (EmptyOperator) Dependencies(_ *Evaluator, _ []*Expr, _ []*tree.Cursor, _ []*tree.Cursor) []*tree.Cursor {
return nil
}
// Run ...
func (EmptyOperator) Run(ev *Evaluator, args []*Expr) (*Response, error) {
if len(args) != 1 {
return nil, fmt.Errorf("empty operator expects 1 argument, received %d", len(args))
}
var emptyType string
switch args[0].Type {
case Literal:
var isString bool
emptyType, isString = args[0].Literal.(string)
if !isString {
return nil, fmt.Errorf("cannot interpret argument for empty operator")
}
case Reference:
emptyType = strings.TrimPrefix(args[0].Reference.String(), ".")
default:
return nil, fmt.Errorf("cannot interpret argument for empty operator")
}
var value interface{}
switch emptyType {
case "hash", "map":
value = map[string]interface{}{}
case "array", "list":
value = []interface{}{}
case "string":
value = ""
default:
return nil, fmt.Errorf("unknown type for empty operator: %s", emptyType)
}
return &Response{
Type: Replace,
Value: value,
}, nil
}
func init() {
RegisterOp("empty", EmptyOperator{})
}