This repository has been archived by the owner on Oct 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
main.go
313 lines (286 loc) · 7.61 KB
/
main.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime/debug"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/hclwrite"
flag "github.com/spf13/pflag"
)
func main() {
flag.Usage = func() {
os.Stderr.WriteString("Usage: terraform-clean-syntax <dir>\n")
}
flag.Parse()
args := flag.Args()
if len(args) < 1 {
flag.Usage()
os.Exit(1)
}
for _, arg := range args {
processItem(arg)
}
}
func processItem(fn string) {
fn = filepath.Clean(fn)
info, err := os.Lstat(fn)
if err != nil {
log.Printf("Failed to stat %q: %s\n", fn, err)
return
}
if info.IsDir() {
if info.Name() != "." && info.Name() != ".." && strings.HasPrefix(info.Name(), ".") {
return
}
processDir(fn)
} else {
if !info.Mode().IsRegular() {
log.Printf("Skipping %q: not a regular file or directory", fn)
}
if !strings.HasSuffix(fn, ".tf") {
return
}
processFile(fn, info.Mode())
}
}
func processDir(fn string) {
entries, err := ioutil.ReadDir(fn)
if err != nil {
log.Printf("Failed to read directory %q: %s", fn, err)
return
}
for _, entry := range entries {
processItem(filepath.Join(fn, entry.Name()))
}
}
func processFile(fn string, mode os.FileMode) {
src, err := ioutil.ReadFile(fn)
if err != nil {
log.Printf("Failed to read file %q: %s", fn, err)
return
}
defer func() {
if r := recover(); r != nil {
fmt.Printf("Recovered in processFile while processing %s: %#v\n%s", fn, r, debug.Stack())
}
}()
f, diags := hclwrite.ParseConfig(src, fn, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
for _, diag := range diags {
if diag.Subject != nil {
log.Printf("[%s:%d] %s: %s", diag.Subject.Filename, diag.Subject.Start.Line, diag.Summary, diag.Detail)
} else {
log.Printf("%s: %s", diag.Summary, diag.Detail)
}
}
return
}
cleanFile(f)
newSrc := f.Bytes()
if bytes.Equal(newSrc, src) {
// No changes
return
}
// TODO: Write the new file to disk in place of the old one
err = ioutil.WriteFile(fn, newSrc, mode)
if err != nil {
log.Printf("Failed to write to %q: %s", fn, err)
log.Printf("WARNING: File %q may be left with only partial content", fn)
return
}
log.Printf("Made changes: %s", fn)
}
func cleanFile(f *hclwrite.File) {
cleanBody(f.Body(), nil)
}
func cleanBody(body *hclwrite.Body, inBlocks []string) {
attrs := body.Attributes()
for name, attr := range attrs {
var cleanedExprTokens hclwrite.Tokens
tokens := attr.Expr().BuildTokens(nil)
if len(inBlocks) == 1 {
inBlock := inBlocks[0]
if inBlock == "variable" && name == "type" {
cleanedExprTokens = cleanTypeExpr(tokens)
body.SetAttributeRaw(name, cleanedExprTokens)
continue
} else if (inBlock == "resource" || inBlock == "data") && name == "provider" {
cleanedExprTokens = cleanProviderExpr(tokens)
body.SetAttributeRaw(name, cleanedExprTokens)
continue
}
}
cleanedExprTokens = cleanValueExpr(tokens)
body.SetAttributeRaw(name, cleanedExprTokens)
}
blocks := body.Blocks()
for _, block := range blocks {
inBlocks := append(inBlocks, block.Type())
cleanBody(block.Body(), inBlocks)
}
}
func cleanValueExpr(tokens hclwrite.Tokens) hclwrite.Tokens {
if len(tokens) < 5 {
// Can't possibly be a "${ ... }" sequence without at least enough
// tokens for the delimiters and one token inside them.
return tokens
}
oQuote := tokens[0]
oBrace := tokens[1]
cBrace := tokens[len(tokens)-2]
cQuote := tokens[len(tokens)-1]
if oQuote.Type != hclsyntax.TokenOQuote || oBrace.Type != hclsyntax.TokenTemplateInterp || cBrace.Type != hclsyntax.TokenTemplateSeqEnd || cQuote.Type != hclsyntax.TokenCQuote {
// Not an interpolation sequence at all, then.
return tokens
}
inside := tokens[2 : len(tokens)-2]
// We're only interested in sequences that are provable to be single
// interpolation sequences, which we'll determine by hunting inside
// the interior tokens for any other interpolation sequences. This is
// likely to produce false negatives sometimes, but that's better than
// false positives and we're mainly interested in catching the easy cases
// here.
quotes := 0
for _, token := range inside {
if token.Type == hclsyntax.TokenOQuote {
quotes++
continue
}
if token.Type == hclsyntax.TokenCQuote {
quotes--
continue
}
if quotes > 0 {
// Interpolation sequences inside nested quotes are okay, because
// they are part of a nested expression.
// "${foo("${bar}")}"
continue
}
if token.Type == hclsyntax.TokenTemplateInterp || token.Type == hclsyntax.TokenTemplateSeqEnd {
// We've found another template delimiter within our interior
// tokens, which suggests that we've found something like this:
// "${foo}${bar}"
// That isn't unwrappable, so we'll leave the whole expression alone.
return tokens
}
}
// If we got down here without an early return then this looks like
// an unwrappable sequence, but we'll trim any leading and trailing
// newlines that might result in an invalid result if we were to
// naively trim something like this:
// "${
// foo
// }"
return trimNewlines(inside)
}
func cleanProviderExpr(tokens hclwrite.Tokens) hclwrite.Tokens {
if len(tokens) != 3 {
// We're only interested in plain quoted strings, which consist
// of the open and close quotes and a literal string token.
return tokens
}
oQuote := tokens[0]
strTok := tokens[1]
cQuote := tokens[2]
if oQuote.Type != hclsyntax.TokenOQuote || strTok.Type != hclsyntax.TokenQuotedLit || cQuote.Type != hclsyntax.TokenCQuote {
// Not a quoted string sequence, then.
return tokens
}
// HACK: Technically a provider.alias sequence ought to be three
// separate tokens, because the dot is an operator, but only the
// `Bytes` part of this is relevant to our output anyway so
// we'll cheat and thus avoid the need to parse `strTok.Bytes.
return hclwrite.Tokens{
{
Type: hclsyntax.TokenIdent,
Bytes: []byte(strTok.Bytes),
},
}
}
func cleanTypeExpr(tokens hclwrite.Tokens) hclwrite.Tokens {
if len(tokens) != 3 {
// We're only interested in plain quoted strings, which consist
// of the open and close quotes and a literal string token.
return tokens
}
oQuote := tokens[0]
strTok := tokens[1]
cQuote := tokens[2]
if oQuote.Type != hclsyntax.TokenOQuote || strTok.Type != hclsyntax.TokenQuotedLit || cQuote.Type != hclsyntax.TokenCQuote {
// Not a quoted string sequence, then.
return tokens
}
switch string(strTok.Bytes) {
case "string":
return hclwrite.Tokens{
{
Type: hclsyntax.TokenIdent,
Bytes: []byte("string"),
},
}
case "list":
return hclwrite.Tokens{
{
Type: hclsyntax.TokenIdent,
Bytes: []byte("list"),
},
{
Type: hclsyntax.TokenOParen,
Bytes: []byte("("),
},
{
Type: hclsyntax.TokenIdent,
Bytes: []byte("string"),
},
{
Type: hclsyntax.TokenCParen,
Bytes: []byte(")"),
},
}
case "map":
return hclwrite.Tokens{
{
Type: hclsyntax.TokenIdent,
Bytes: []byte("map"),
},
{
Type: hclsyntax.TokenOParen,
Bytes: []byte("("),
},
{
Type: hclsyntax.TokenIdent,
Bytes: []byte("string"),
},
{
Type: hclsyntax.TokenCParen,
Bytes: []byte(")"),
},
}
default:
// Something else we're not expecting, then.
return tokens
}
}
func trimNewlines(tokens hclwrite.Tokens) hclwrite.Tokens {
if len(tokens) == 0 {
return nil
}
var start, end int
for start = 0; start < len(tokens); start++ {
if tokens[start].Type != hclsyntax.TokenNewline {
break
}
}
for end = len(tokens); end > 0; end-- {
if tokens[end-1].Type != hclsyntax.TokenNewline {
break
}
}
return tokens[start:end]
}