-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
642 lines (570 loc) · 17.2 KB
/
parse.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
package config
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/hcl2/gohcl"
"github.com/hashicorp/hcl2/hcl"
"github.com/hashicorp/hcl2/hclparse"
"github.com/zclconf/go-cty/cty"
)
type Parser struct {
HCLParser *hclparse.Parser
}
func NewParser() *Parser {
return &Parser{
HCLParser: hclparse.NewParser(),
}
}
func (p *Parser) Files() map[string]*hcl.File {
return p.HCLParser.Files()
}
func (p *Parser) ParseFileSource(src []byte, filename string) (*File, hcl.Diagnostics) {
astFile, diags := p.HCLParser.ParseHCL(src, filename)
file := &File{
Source: src,
SourcePath: filepath.Clean(filename),
SourceAST: astFile,
}
if astFile == nil {
return file, diags
}
content, contentDiags := astFile.Body.Content(fileRootSchema)
diags = append(diags, contentDiags...)
file.Description = content.Attributes["Description"]
for _, block := range content.Blocks {
switch block.Type {
case "Conditions":
attrs, attrsDiags := block.Body.JustAttributes()
diags = append(diags, attrsDiags...)
for _, attr := range attrs {
file.Conditions = append(file.Conditions, attr)
}
case "Constant":
constant, decDiags := decodeConstant(block)
diags = append(diags, decDiags...)
file.Constants = append(file.Constants, constant)
case "Locals":
attrs, attrsDiags := block.Body.JustAttributes()
diags = append(diags, attrsDiags...)
for _, attr := range attrs {
file.Locals = append(file.Locals, attr)
}
case "Mappings":
attrs, attrsDiags := block.Body.JustAttributes()
diags = append(diags, attrsDiags...)
for _, attr := range attrs {
file.Mappings = append(file.Mappings, attr)
}
case "Metadata":
attrs, attrsDiags := block.Body.JustAttributes()
diags = append(diags, attrsDiags...)
for _, attr := range attrs {
file.Metadata = append(file.Metadata, attr)
}
case "Module":
module, decDiags := decodeModuleCall(block)
diags = append(diags, decDiags...)
file.Modules = append(file.Modules, module)
case "Output":
output, decDiags := decodeOutput(block)
diags = append(diags, decDiags...)
file.Outputs = append(file.Outputs, output)
case "Parameter":
param, decDiags := decodeParameter(block)
diags = append(diags, decDiags...)
file.Parameters = append(file.Parameters, param)
case "Resource":
resource, decDiags := decodeResource(block)
diags = append(diags, decDiags...)
file.Resources = append(file.Resources, resource)
case "UserInterface":
// TODO
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagWarning,
Summary: "UserInterface block is not yet supported",
Detail: "This block is ignored by this version of awsup.",
Subject: &block.DefRange,
})
default:
// Should never happen since the above cases should always cover
// all of the block types in our schema.
panic(fmt.Errorf("unhandled block type %q", block.Type))
}
}
return file, diags
}
func (p *Parser) ParseFile(filename string) (*File, hcl.Diagnostics) {
src, err := ioutil.ReadFile(filename)
if err != nil {
if os.IsNotExist(err) {
return nil, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Failed to read configuration file",
Detail: fmt.Sprintf("The requested file %s does not exist.", filename),
},
}
} else {
return nil, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Failed to read configuration file",
Detail: fmt.Sprintf("There was an error reading %s: %s", filename, err),
},
}
}
}
return p.ParseFileSource(src, filename)
}
func NewModule(sourcePath, sourceDir string, files ...*File) (*Module, hcl.Diagnostics) {
var diags hcl.Diagnostics
module := &Module{
SourcePath: filepath.Clean(sourcePath),
SourceDir: filepath.Clean(sourceDir),
Files: make(map[string]*File),
FileASTs: make(map[string]*hcl.File),
Description: nil, // Assigned in loop, or defaulted after loop if needed
Conditions: make(map[string]*hcl.Attribute),
Constants: make(map[string]*Constant),
Locals: make(map[string]*hcl.Attribute),
Mappings: make(map[string]*hcl.Attribute),
Metadata: make(map[string]*hcl.Attribute),
Modules: make(map[string]*ModuleCall),
Outputs: make(map[string]*Output),
Parameters: make(map[string]*Parameter),
Resources: make(map[string]*Resource),
UIParamGroups: make([]*UIParamGroup, 0),
UIParamLabels: make(map[string]*hcl.Attribute),
}
var descriptionRange hcl.Range
for _, file := range files {
if file == nil {
// Should never happen
panic("nil *File passed to NewModule")
}
if _, conflict := module.Files[file.SourcePath]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagWarning,
Summary: "Duplicate file in module",
Detail: fmt.Sprintf("Ignored duplicate definition for file %s while building module.", file.SourcePath),
})
continue
}
module.Files[file.SourcePath] = file
module.FileASTs[file.SourcePath] = file.SourceAST
if file.Description != nil {
if module.Description != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Multiple descriptions",
Detail: fmt.Sprintf(
"Duplicate definition of module description, which was already defined at %s.",
descriptionRange,
),
Subject: &file.Description.NameRange,
})
continue
}
module.Description = file.Description.Expr
descriptionRange = file.Description.NameRange
}
for _, def := range file.Conditions {
if _, conflict := module.Conditions[def.Name]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate condition",
Detail: fmt.Sprintf(
"Duplicate definition of condition %q, which was already defined at %s.",
def.Name, module.Conditions[def.Name].NameRange,
),
Subject: &def.NameRange,
})
continue
}
module.Conditions[def.Name] = def
}
for _, def := range file.Constants {
if _, conflict := module.Constants[def.Name]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate constant",
Detail: fmt.Sprintf(
"Duplicate definition of constant %q, which was already defined at %s.",
def.Name, module.Constants[def.Name].DeclRange,
),
Subject: &def.DeclRange,
})
continue
}
module.Constants[def.Name] = def
}
for _, def := range file.Locals {
if _, conflict := module.Locals[def.Name]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate local",
Detail: fmt.Sprintf(
"Duplicate definition of local %q, which was already defined at %s.",
def.Name, module.Locals[def.Name].NameRange,
),
Subject: &def.NameRange,
})
continue
}
module.Locals[def.Name] = def
}
for _, def := range file.Mappings {
if _, conflict := module.Mappings[def.Name]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate mapping",
Detail: fmt.Sprintf(
"Duplicate definition of mapping %q, which was already defined at %s.",
def.Name, module.Mappings[def.Name].NameRange,
),
Subject: &def.NameRange,
})
continue
}
module.Mappings[def.Name] = def
}
for _, def := range file.Metadata {
if _, conflict := module.Mappings[def.Name]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate mapping",
Detail: fmt.Sprintf(
"Duplicate definition of metadata field %q, which was already defined at %s.",
def.Name, module.Metadata[def.Name].NameRange,
),
Subject: &def.NameRange,
})
continue
}
module.Metadata[def.Name] = def
}
for _, def := range file.Modules {
if _, conflict := module.Modules[def.Name]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate module",
Detail: fmt.Sprintf(
"Duplicate definition of module %q, which was already defined at %s.",
def.Name, module.Modules[def.Name].DeclRange,
),
Subject: &def.DeclRange,
})
continue
}
module.Modules[def.Name] = def
}
for _, def := range file.Outputs {
if _, conflict := module.Outputs[def.Name]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate output",
Detail: fmt.Sprintf(
"Duplicate definition of output %q, which was already defined at %s.",
def.Name, module.Outputs[def.Name].DeclRange,
),
Subject: &def.DeclRange,
})
continue
}
module.Outputs[def.Name] = def
}
for _, def := range file.Parameters {
if _, conflict := module.Parameters[def.Name]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate parameter",
Detail: fmt.Sprintf(
"Duplicate definition of parameter %q, which was already defined at %s.",
def.Name, module.Parameters[def.Name].DeclRange,
),
Subject: &def.DeclRange,
})
continue
}
module.Parameters[def.Name] = def
}
for _, def := range file.Resources {
if _, conflict := module.Resources[def.LogicalID]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate resource",
Detail: fmt.Sprintf(
"Duplicate definition of resource %q, which was already defined at %s.",
def.LogicalID, module.Resources[def.LogicalID].DeclRange,
),
Subject: &def.DeclRange,
})
continue
}
module.Resources[def.LogicalID] = def
}
for _, def := range file.UIParamGroups {
module.UIParamGroups = append(module.UIParamGroups, def)
}
for _, def := range file.UIParamLabels {
if _, conflict := module.UIParamLabels[def.Name]; conflict {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Duplicate parameter label",
Detail: fmt.Sprintf(
"Duplicate parameter label for parameter %q, which was already labeled at %s.",
def.Name, module.UIParamLabels[def.Name].NameRange,
),
Subject: &def.NameRange,
})
continue
}
module.UIParamLabels[def.Name] = def
}
}
if module.Description == nil {
// Put a placeholder expression here so that callers don't need to
// deal with this ever being nil.
// We don't have any useful range to include here, but that's okay
// since we never actually show the range of the description as a whole
// anyway.
module.Description = hcl.StaticExpr(cty.NullVal(cty.String), hcl.Range{})
}
return module, diags
}
func (p *Parser) ParseDir(path string) (*Module, hcl.Diagnostics) {
infos, err := ioutil.ReadDir(path)
if err != nil {
// We'll return an empty module just so the caller gets something
// somewhat-valid to chew on in spite of the error.
empty, _ := NewModule(path, path)
if os.IsNotExist(err) {
return empty, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Failed to read configuration",
Detail: fmt.Sprintf("The requested directory %s does not exist.", path),
},
}
} else {
return empty, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Failed to read configuration",
Detail: fmt.Sprintf("There was an error reading %s: %s.", path, err),
},
}
}
}
var files []*File
var diags hcl.Diagnostics
for _, info := range infos {
name := info.Name()
// Look for files with names ending in ".awsup" while also filtering
// out things that look like editor temporary files.
switch {
case info.IsDir():
continue
case !strings.HasSuffix(name, ".awsup"):
continue
case strings.HasPrefix(name, "#") && strings.HasSuffix(name, "#"):
continue
case strings.HasPrefix(name, "."):
continue
}
filePath := filepath.Join(path, name)
file, fileDiags := p.ParseFile(filePath)
diags = append(diags, fileDiags...)
files = append(files, file)
}
module, modDiags := NewModule(path, path, files...)
diags = append(diags, modDiags...)
return module, diags
}
func (p *Parser) ParseDirOrFile(path string) (*Module, hcl.Diagnostics) {
info, err := os.Stat(path)
if err == nil && !info.IsDir() {
file, diags := p.ParseFile(path)
module, modDiags := NewModule(file.SourcePath, filepath.Dir(file.SourcePath), file)
diags = append(diags, modDiags...)
return module, diags
}
return p.ParseDir(path)
}
func decodeConstant(block *hcl.Block) (*Constant, hcl.Diagnostics) {
var b struct {
Description hcl.Expression `hcl:"Description"`
Default hcl.Expression `hcl:"Default"`
}
diags := gohcl.DecodeBody(block.Body, nil, &b)
return &Constant{
Name: block.Labels[0],
DeclRange: block.DefRange,
Description: b.Description,
Default: b.Default,
}, diags
}
func decodeModuleCall(block *hcl.Block) (*ModuleCall, hcl.Diagnostics) {
var b struct {
Source hcl.Expression `hcl:"Source"`
Parameters *rawBody `hcl:"Parameters,block"`
Constants *rawBody `hcl:"Constants,block"`
ForEach hcl.Expression `hcl:"ForEach"`
}
diags := gohcl.DecodeBody(block.Body, nil, &b)
module := &ModuleCall{
Name: block.Labels[0],
DeclRange: block.DefRange,
Source: b.Source,
ForEach: b.ForEach,
}
if b.Parameters != nil {
var jaDiags hcl.Diagnostics
module.Parameters, jaDiags = b.Parameters.JustAttributes()
diags = append(diags, jaDiags...)
}
if b.Constants != nil {
var jaDiags hcl.Diagnostics
module.Constants, jaDiags = b.Constants.JustAttributes()
diags = append(diags, jaDiags...)
}
return module, diags
}
func decodeOutput(block *hcl.Block) (*Output, hcl.Diagnostics) {
var b struct {
Description hcl.Expression `hcl:"Description"`
Value hcl.Expression `hcl:"Value"`
Export *struct {
Name hcl.Expression `hcl:"Name"`
} `hcl:"Export,block"`
}
diags := gohcl.DecodeBody(block.Body, nil, &b)
ret := &Output{
Name: block.Labels[0],
DeclRange: block.DefRange,
Description: b.Description,
Value: b.Value,
}
if b.Export != nil {
ret.Export = &OutputExport{
Name: b.Export.Name,
}
}
return ret, diags
}
func decodeParameter(block *hcl.Block) (*Parameter, hcl.Diagnostics) {
var b struct {
Type string `hcl:"Type"`
Description hcl.Expression `hcl:"Description"`
Default hcl.Expression `hcl:"Default"`
AllowedPattern hcl.Expression `hcl:"AllowedPattern"`
AllowedValues hcl.Expression `hcl:"AllowedValues"`
ConstraintDescription hcl.Expression `hcl:"ConstraintDescription"`
MinLength hcl.Expression `hcl:"MinLength"`
MaxLength hcl.Expression `hcl:"MaxLength"`
MinValue hcl.Expression `hcl:"MinValue"`
MaxValue hcl.Expression `hcl:"MaxValue"`
Obscure hcl.Expression `hcl:"Obscure"`
}
diags := gohcl.DecodeBody(block.Body, nil, &b)
return &Parameter{
Name: block.Labels[0],
DeclRange: block.DefRange,
Type: b.Type,
Description: b.Description,
Default: b.Default,
AllowedPattern: b.AllowedPattern,
AllowedValues: b.AllowedValues,
ConstraintDescription: b.ConstraintDescription,
MinLength: b.MinLength,
MaxLength: b.MaxLength,
MinValue: b.MinValue,
MaxValue: b.MaxValue,
Obscure: b.Obscure,
}, diags
}
func decodeResource(block *hcl.Block) (*Resource, hcl.Diagnostics) {
var b struct {
Type string `hcl:"Type"`
Parameters *hcl.Attributes `hcl:"Parameters,block"`
Metadata *hcl.Attributes `hcl:"Metadata,block"`
DependsOn hcl.Expression `hcl:"DependsOn"`
CreationPolicy *struct {
AutoScaling *struct {
MinSuccessfulInstancesPercent hcl.Expression `hcl:"MinSuccessfulInstancesPercent"`
} `hcl:"AutoScaling"`
Signal *struct {
Count hcl.Expression `hcl:"Count"`
Timeout hcl.Expression `hcl:"Timeout"`
} `hcl:"AutoScaling"`
} `hcl:"CreationPolicy"`
DeletionPolicy hcl.Expression `hcl:"DeletionPolicy"`
UpdatePolicy *struct {
} `hcl:"UpdatePolicy"`
ForEach hcl.Expression `hcl:"ForEach"`
}
diags := gohcl.DecodeBody(block.Body, nil, &b)
resource := &Resource{
LogicalID: block.Labels[0],
DeclRange: block.DefRange,
}
return resource, diags
}
type rawBody struct {
hcl.Body `hcl:",remain"`
}
func (b *rawBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) {
if b == nil {
// for convenience in our decode functions
return make(hcl.Attributes), nil
}
return b.Body.JustAttributes()
}
var fileRootSchema = &hcl.BodySchema{
Attributes: []hcl.AttributeSchema{
{
Name: "Description",
Required: false,
},
},
Blocks: []hcl.BlockHeaderSchema{
{
Type: "Conditions",
},
{
Type: "Constant",
LabelNames: []string{"name"},
},
{
Type: "Locals",
},
{
Type: "Mappings",
},
{
Type: "Metadata",
},
{
Type: "Module",
LabelNames: []string{"name"},
},
{
Type: "Output",
LabelNames: []string{"name"},
},
{
Type: "Parameter",
LabelNames: []string{"name"},
},
{
Type: "Resource",
LabelNames: []string{"logical id"},
},
{
Type: "UserInterface",
},
},
}