-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
decode_shim.go
108 lines (101 loc) · 2.16 KB
/
decode_shim.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
package write
import (
"encoding/json"
"unicode"
"unicode/utf8"
"github.com/hashicorp/hcl"
)
// hclDecode is a modified version of hcl.Decode just for the super general
// purposes here. There's some strange bug in how hcl.Decode decodes json where
//
// { "sub" : { "v1" : { "field" : "value1" }, "v2" : { "field" : "value2" } } }
//
// hcl.Decode-s into:
//
// map[string]interface {}{
// "sub":[]map[string]interface {}{
// map[string]interface {}{
// "v1":[]map[string]interface {}{
// map[string]interface {}{
// "field":"value1"
// }
// }
// },
// map[string]interface {}{
// "v2":[]map[string]interface {}{
// map[string]interface {}{
// "field":"value2"
// }
// }
// }
// }
// }
//
// but json.Unmarshal-s into the more expected:
//
// map[string]interface {}{
// "sub":map[string]interface {}{
// "v1":map[string]interface {}{
// "field":"value1"
// },
// "v2":map[string]interface {}{
// "field":"value2"
// }
// }
// }
//
// The strange part is that the following HCL:
//
// sub { "v1" = { field = "value1" }, "v2" = { field = "value2" } }
//
// hcl.Decode-s into:
//
// map[string]interface {}{
// "sub":[]map[string]interface {}{
// map[string]interface {}{
// "v1":[]map[string]interface {}{
// map[string]interface {}{
// "field":"value1"
// }
// },
// "v2":[]map[string]interface {}{
// map[string]interface {}{
// "field":"value2"
// }
// }
// }
// }
// }
//
// Which is the "correct" value assuming you did the patch-slice-of-maps correction.
//
// Given that HCLv1 is basically frozen and the HCL part of it is fine instead
// of trying to track down a weird bug we'll bypass the weird JSON decoder and just use
// the stdlib one.
func hclDecode(out interface{}, in string) error {
data := []byte(in)
if isHCL(data) {
return hcl.Decode(out, in)
}
return json.Unmarshal(data, out)
}
// this is an inlined variant of hcl.lexMode()
func isHCL(v []byte) bool {
var (
r rune
w int
offset int
)
for {
r, w = utf8.DecodeRune(v[offset:])
offset += w
if unicode.IsSpace(r) {
continue
}
if r == '{' {
return false
}
break
}
return true
}