forked from digitalocean/atc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode_hook.go
117 lines (98 loc) · 2.14 KB
/
decode_hook.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
package atc
import (
"encoding/json"
"errors"
"reflect"
"strconv"
"strings"
)
const VersionLatest = "latest"
const VersionEvery = "every"
var VersionConfigDecodeHook = func(
srcType reflect.Type,
dstType reflect.Type,
data interface{},
) (interface{}, error) {
if dstType != reflect.TypeOf(VersionConfig{}) {
return data, nil
}
switch {
case srcType.Kind() == reflect.String:
if s, ok := data.(string); ok {
return VersionConfig{
Every: s == VersionEvery,
Latest: s == VersionLatest,
}, nil
}
case srcType.Kind() == reflect.Map:
version := Version{}
if versionConfig, ok := data.(map[interface{}]interface{}); ok {
for key, val := range versionConfig {
if sKey, ok := key.(string); ok {
if sVal, ok := val.(string); ok {
version[sKey] = strings.TrimSpace(sVal)
}
}
}
return VersionConfig{
Pinned: version,
}, nil
}
}
return data, nil
}
var SanitizeDecodeHook = func(
dataKind reflect.Kind,
valKind reflect.Kind,
data interface{},
) (interface{}, error) {
if valKind == reflect.Map {
if dataKind == reflect.Map {
return sanitize(data)
}
}
if valKind == reflect.String {
if dataKind == reflect.String {
return data, nil
}
if dataKind == reflect.Float64 {
if f, ok := data.(float64); ok {
return strconv.FormatFloat(f, 'f', -1, 64), nil
}
return nil, errors.New("impossible: float64 != float64")
}
// format it as JSON/YAML would
return json.Marshal(data)
}
return data, nil
}
func sanitize(root interface{}) (interface{}, error) {
switch rootVal := root.(type) {
case map[interface{}]interface{}:
sanitized := map[string]interface{}{}
for key, val := range rootVal {
str, ok := key.(string)
if !ok {
return nil, errors.New("non-string key")
}
sub, err := sanitize(val)
if err != nil {
return nil, err
}
sanitized[str] = sub
}
return sanitized, nil
case []interface{}:
sanitized := make([]interface{}, len(rootVal))
for i, val := range rootVal {
sub, err := sanitize(val)
if err != nil {
return nil, err
}
sanitized[i] = sub
}
return sanitized, nil
default:
return rootVal, nil
}
}