-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathpostprocessing.go
295 lines (258 loc) · 7.65 KB
/
postprocessing.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package generate
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/zclconf/go-cty/cty"
)
func stripDefaults(fpath string, extraFieldsToRemove map[string]any) error {
file, err := readHCLFile(fpath)
if err != nil {
return err
}
hasChanges := false
for _, block := range file.Body().Blocks() {
if s := stripDefaultsFromBlock(block, extraFieldsToRemove); s {
hasChanges = true
}
}
if hasChanges {
log.Printf("Updating file: %s\n", fpath)
return os.WriteFile(fpath, file.Bytes(), 0600)
}
return nil
}
func wrapJSONFieldsInFunction(fpath string) error {
file, err := readHCLFile(fpath)
if err != nil {
return err
}
hasChanges := false
// Find json attributes and use jsonencode
for _, block := range file.Body().Blocks() {
for key, attr := range block.Body().Attributes() {
asMap, err := attributeToMap(attr)
if err != nil || asMap == nil {
continue
}
tokens := hclwrite.TokensForValue(HCL2ValueFromConfigValue(asMap))
block.Body().SetAttributeRaw(key, hclwrite.TokensForFunctionCall("jsonencode", tokens))
hasChanges = true
}
}
if hasChanges {
log.Printf("Updating file: %s\n", fpath)
return os.WriteFile(fpath, file.Bytes(), 0600)
}
return nil
}
func abstractDashboards(fpath string) error {
fDir := filepath.Dir(fpath)
outPath := filepath.Join(fDir, "files")
file, err := readHCLFile(fpath)
if err != nil {
return err
}
hasChanges := false
dashboardJsons := map[string][]byte{}
for _, block := range file.Body().Blocks() {
labels := block.Labels()
if len(labels) == 0 || labels[0] != "grafana_dashboard" {
continue
}
dashboard, err := attributeToJSON(block.Body().GetAttribute("config_json"))
if err != nil {
return err
}
if dashboard == nil {
continue
}
writeTo := filepath.Join(outPath, fmt.Sprintf("%s.json", block.Labels()[1]))
// Replace $${ with ${ in the json. No need to escape in the json file
dashboard = []byte(strings.ReplaceAll(string(dashboard), "$${", "${"))
dashboardJsons[writeTo] = dashboard
// Hacky relative path with interpolation
relativePath := strings.ReplaceAll(writeTo, fDir, "")
pathWithInterpolation := hclwrite.Tokens{
{Type: hclsyntax.TokenOQuote, Bytes: []byte(`"`)},
{Type: hclsyntax.TokenTemplateInterp, Bytes: []byte(`${`)},
{Type: hclsyntax.TokenIdent, Bytes: []byte(`path.module`)},
{Type: hclsyntax.TokenTemplateSeqEnd, Bytes: []byte(`}`)},
{Type: hclsyntax.TokenQuotedLit, Bytes: []byte(relativePath)},
{Type: hclsyntax.TokenCQuote, Bytes: []byte(`"`)},
}
block.Body().SetAttributeRaw(
"config_json",
hclwrite.TokensForFunctionCall("file", pathWithInterpolation),
)
hasChanges = true
}
if hasChanges {
log.Printf("Updating file: %s\n", fpath)
os.Mkdir(outPath, 0755)
for writeTo, dashboard := range dashboardJsons {
err := os.WriteFile(writeTo, dashboard, 0600)
if err != nil {
panic(err)
}
}
return os.WriteFile(fpath, file.Bytes(), 0600)
}
return nil
}
func attributeToMap(attr *hclwrite.Attribute) (map[string]interface{}, error) {
var err error
// Convert jsonencode to raw json
s := strings.TrimPrefix(string(attr.Expr().BuildTokens(nil).Bytes()), " ")
if strings.HasPrefix(s, "jsonencode(") {
return nil, nil // Figure out how to handle those
}
if !strings.HasPrefix(s, "\"") {
// if expr is not a string, assume it's already converted, return (idempotency
return nil, nil
}
s, err = strconv.Unquote(s)
if err != nil {
return nil, err
}
s = strings.ReplaceAll(s, "$${", "${") // These are escaped interpolations
var dashboardMap map[string]interface{}
err = json.Unmarshal([]byte(s), &dashboardMap)
if err != nil {
return nil, err
}
return dashboardMap, nil
}
func attributeToJSON(attr *hclwrite.Attribute) ([]byte, error) {
jsonMap, err := attributeToMap(attr)
if err != nil || jsonMap == nil {
return nil, err
}
jsonMarshalled, err := json.MarshalIndent(jsonMap, "", "\t")
if err != nil {
return nil, err
}
return jsonMarshalled, nil
}
func readHCLFile(fpath string) (*hclwrite.File, error) {
src, err := os.ReadFile(fpath)
if err != nil {
return nil, err
}
file, diags := hclwrite.ParseConfig(src, fpath, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
return nil, errors.New(diags.Error())
}
return file, nil
}
func stripDefaultsFromBlock(block *hclwrite.Block, extraFieldsToRemove map[string]any) bool {
hasChanges := false
for _, innblock := range block.Body().Blocks() {
if s := stripDefaultsFromBlock(innblock, extraFieldsToRemove); s {
hasChanges = true
}
if len(innblock.Body().Attributes()) == 0 && len(innblock.Body().Blocks()) == 0 {
if rm := block.Body().RemoveBlock(innblock); rm {
hasChanges = true
}
}
}
for name, attribute := range block.Body().Attributes() {
if string(attribute.Expr().BuildTokens(nil).Bytes()) == " null" {
if rm := block.Body().RemoveAttribute(name); rm != nil {
hasChanges = true
}
}
if string(attribute.Expr().BuildTokens(nil).Bytes()) == " {}" {
if rm := block.Body().RemoveAttribute(name); rm != nil {
hasChanges = true
}
}
if string(attribute.Expr().BuildTokens(nil).Bytes()) == " []" {
if rm := block.Body().RemoveAttribute(name); rm != nil {
hasChanges = true
}
}
for key, valueToRemove := range extraFieldsToRemove {
if name == key {
toRemove := false
fieldValue := strings.TrimSpace(string(attribute.Expr().BuildTokens(nil).Bytes()))
fieldValue, err := extractJSONEncode(fieldValue)
if err != nil {
continue
}
if v, ok := valueToRemove.(bool); ok && v {
toRemove = true
} else if v, ok := valueToRemove.(string); ok && v == fieldValue {
toRemove = true
}
if toRemove {
if rm := block.Body().RemoveAttribute(name); rm != nil {
hasChanges = true
}
}
}
}
}
return hasChanges
}
// BELOW IS FROM https://github.com/hashicorp/terraform/blob/main/internal/configs/hcl2shim/values.go
// UnknownVariableValue is a sentinel value that can be used
// to denote that the value of a variable is unknown at this time.
// RawConfig uses this information to build up data about
// unknown keys.
const UnknownVariableValue = "74D93920-ED26-11E3-AC10-0800200C9A66"
// HCL2ValueFromConfigValue is the opposite of configValueFromHCL2: it takes
// a value as would be returned from the old interpolator and turns it into
// a cty.Value so it can be used within, for example, an HCL2 EvalContext.
func HCL2ValueFromConfigValue(v interface{}) cty.Value {
if v == nil {
return cty.NullVal(cty.DynamicPseudoType)
}
if v == UnknownVariableValue {
return cty.DynamicVal
}
switch tv := v.(type) {
case bool:
return cty.BoolVal(tv)
case string:
return cty.StringVal(tv)
case int:
return cty.NumberIntVal(int64(tv))
case float64:
return cty.NumberFloatVal(tv)
case []interface{}:
vals := make([]cty.Value, len(tv))
for i, ev := range tv {
vals[i] = HCL2ValueFromConfigValue(ev)
}
return cty.TupleVal(vals)
case map[string]interface{}:
vals := map[string]cty.Value{}
for k, ev := range tv {
vals[k] = HCL2ValueFromConfigValue(ev)
}
return cty.ObjectVal(vals)
default:
// HCL/HIL should never generate anything that isn't caught by
// the above, so if we get here something has gone very wrong.
panic(fmt.Errorf("can't convert %#v to cty.Value", v))
}
}
func extractJSONEncode(value string) (string, error) {
if !strings.HasPrefix(value, "jsonencode(") {
return "", nil
}
value = strings.TrimPrefix(value, "jsonencode(")
value = strings.TrimSuffix(value, ")")
b, err := json.MarshalIndent(value, "", " ")
return string(b), err
}