/
utilities.go
253 lines (227 loc) · 6.78 KB
/
utilities.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package hcl
import (
"fmt"
"reflect"
"regexp"
"runtime/debug"
"sort"
"strings"
"github.com/coveo/gotemplate/v3/collections"
)
// flatten converts array of map to single map if there is only one element in the array.
// By default, hc.Unmarshal returns array of map even if there is only a single map in the definition.
func flatten(source interface{}) interface{} {
switch value := source.(type) {
case []map[string]interface{}:
switch len(value) {
case 1:
source = flatten(value[0])
default:
result := make([]map[string]interface{}, len(value))
for i := range value {
result[i] = flatten(value[i]).(map[string]interface{})
}
source = result
}
case map[string]interface{}:
for key := range value {
value[key] = flatten(value[key])
}
source = value
case []interface{}:
for i, sub := range value {
value[i] = flatten(sub)
}
source = value
}
return source
}
func transform(out interface{}) {
result := transformElement(flatten(reflect.ValueOf(out).Elem().Interface()))
if _, isMap := out.(*map[string]interface{}); isMap {
// If the result is expected to be map[string]interface{}, we convert it back from internal dict type.
result = result.(hclIDict).Native()
}
reflect.ValueOf(out).Elem().Set(reflect.ValueOf(result))
}
func transformElement(source interface{}) interface{} {
if value, err := hclHelper.TryAsDictionary(source); err == nil {
for _, key := range value.KeysAsString() {
value.Set(key, transformElement(value.Get(key)))
}
source = value
} else if value, err := hclHelper.TryAsList(source); err == nil {
for i, sub := range value.AsArray() {
value.Set(i, transformElement(sub))
}
source = value
}
return source
}
func marshalHCL(value interface{}, fullHcl, head bool, prefix, indent string) (result string, err error) {
if value == nil {
result = "null"
return
}
ifIndent := func(vTrue, vFalse interface{}) interface{} { return collections.IIf(indent, vTrue, vFalse) }
const specialFormat = "#HCL_ARRAY_MAP#!"
switch value := value.(type) {
case int, uint, int64, uint64, float64, bool:
result = fmt.Sprint(value)
case string:
value = fmt.Sprintf("%q", value)
if indent != "" && strings.Contains(value, "\\n") {
// We unquote the value
unIndented := value[1 : len(value)-1]
// Then replace escaped characters, other escape chars are \a, \b, \f and \v are not managed
unIndented = strings.Replace(unIndented, `\n`, "\n", -1)
unIndented = strings.Replace(unIndented, `\\`, "\\", -1)
unIndented = strings.Replace(unIndented, `\"`, "\"", -1)
unIndented = strings.Replace(unIndented, `\r`, "\r", -1)
unIndented = strings.Replace(unIndented, `\t`, "\t", -1)
unIndented = collections.UnIndent(unIndented)
if strings.HasSuffix(unIndented, "\n") {
value = fmt.Sprintf("<<-EOF\n%sEOF", unIndented)
}
}
result = value
case []interface{}:
results := make([]string, len(value))
if fullHcl && isArrayOfMap(value) {
for i, element := range value {
element := element.(map[string]interface{})
for key := range element {
if results[i], err = marshalHCL(element[key], fullHcl, false, "", indent); err != nil {
return
}
if head {
results[i] = fmt.Sprintf(`%s%s%s`, id(key), ifIndent(" = ", ""), results[i])
} else {
results[i] = fmt.Sprintf(`%s %s %s`, specialFormat, id(key), results[i])
}
}
}
result = strings.Join(results, ifIndent("\n\n", " ").(string))
break
}
var totalLength int
var newLine bool
for i := range value {
if results[i], err = marshalHCL(value[i], fullHcl, false, "", indent); err != nil {
return
}
totalLength += len(results[i])
newLine = newLine || strings.Contains(results[i], "\n")
}
if totalLength > 60 && indent != "" || newLine {
result = fmt.Sprintf("[\n%s,\n]", collections.Indent(strings.Join(results, ",\n"), prefix+indent))
} else {
result = fmt.Sprintf("[%s]", strings.Join(results, ifIndent(", ", ",").(string)))
}
case map[string]interface{}:
if key := singleMap(value); fullHcl && key != "" {
var element string
if element, err = marshalHCL(value[key], fullHcl, false, "", indent); err != nil {
return
}
result = fmt.Sprintf(`%s %s`, id(key), element)
break
}
keys := make([]string, 0, len(value))
for key := range value {
keys = append(keys, key)
}
sort.Strings(keys)
rendered := make(map[string]string, len(keys))
keyLen := 0
for key, val := range value {
if rendered[key], err = marshalHCL(val, fullHcl, false, "", indent); err != nil {
return
}
if strings.Contains(rendered[key], "\n") {
continue
}
if len(key) > keyLen && indent != "" {
keyLen = len(key)
}
}
items := make([]string, 0, len(value)+2)
for _, multiline := range []bool{false, true} {
for _, key := range keys {
rendered := rendered[key]
lines := strings.Split(rendered, "\n")
// We process the multilines elements after the single line one
if len(lines) > 1 && !multiline || len(lines) == 1 && multiline {
continue
}
if multiline && len(items) > 0 {
// Add a blank line between multilines elements
items = append(items, "")
keyLen = 0
}
equal := ifIndent(" = ", "=").(string)
if _, err := hclHelper.TryAsDictionary(value[key]); err == nil {
if multiline {
equal = " "
} else if indent == "" {
equal = ""
}
}
if strings.Contains(rendered, specialFormat) {
items = append(items, strings.Replace(rendered, specialFormat, id(key), -1))
} else {
if indent == "" {
keyLen = 0
if equal == "" && !strings.HasPrefix(rendered, `{`) {
keyLen = len(id(key)) + 1
}
}
items = append(items, fmt.Sprintf("%*s%s%s", -keyLen, id(key), equal, rendered))
}
}
}
if head {
result = strings.Join(items, ifIndent("\n", " ").(string))
break
}
if indent == "" || len(items) == 0 {
result = fmt.Sprintf("{%s}", strings.Join(items, " "))
break
}
result = fmt.Sprintf("{\n%s\n}", collections.Indent(strings.Join(items, "\n"), prefix+indent))
default:
debug.PrintStack()
err = fmt.Errorf("marshalHCL Unknown type %[1]T %[1]v", value)
}
return
}
func isArrayOfMap(array []interface{}) bool {
if len(array) == 0 {
return false
}
for _, item := range array {
if item, isMap := item.([]map[string]interface{}); !isMap || len(item) != 1 {
return false
}
}
return true
}
func singleMap(m map[string]interface{}) string {
if len(m) != 1 {
return ""
}
for k := range m {
if _, isMap := m[k].(map[string]interface{}); isMap {
return k
}
}
return ""
}
var identifierRegex = regexp.MustCompile(`^[A-za-z][\w-]*$`)
func id(key string) string {
if identifierRegex.MatchString(key) {
return key
}
// The identifier contains characters that may be considered invalid, we have to quote it
return fmt.Sprintf("%q", key)
}