-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaction.go
54 lines (45 loc) · 1.01 KB
/
action.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
package terrapi
import (
"reflect"
)
type Action interface {
unmarshal() ([]string, error)
setOutErr([]byte, []byte)
GetOutErr() ([]byte, []byte)
}
func unmarshalAction(a Action) ([]string, error) {
v := reflect.ValueOf(a)
if v.Kind() == reflect.Ptr && !v.IsNil() {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return nil, &InvalidActionError{Type: v.Type()}
}
c := v.NumField()
b := []string{v.Field(0).String()}
// we count from 1 to bypass action name
for i := 1; i < c; i++ {
fieldValue := v.Field(i)
fieldType := v.Type().Field(i)
switch fieldValue.Kind() {
case reflect.Bool:
if fieldValue.Bool() {
b = append(b, fieldType.Tag.Get("cli"))
}
case reflect.String:
if !fieldValue.IsZero() {
b = append(b, fieldType.Tag.Get("cli") + fieldValue.String())
}
case reflect.Slice:
s, ok := fieldValue.Interface().([]string)
if ok {
for _, j := range s {
if j != "" {
b = append(b, fieldType.Tag.Get("cli") + j)
}
}
}
}
}
return b, nil
}