forked from terramate-io/terramate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhcl.go
2716 lines (2333 loc) · 68.9 KB
/
hcl.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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 Terramate GmbH
// SPDX-License-Identifier: MPL-2.0
package hcl
import (
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"github.com/gobwas/glob"
"github.com/rs/zerolog/log"
"github.com/terramate-io/hcl/v2"
"github.com/terramate-io/hcl/v2/hclparse"
"github.com/terramate-io/hcl/v2/hclsyntax"
"github.com/terramate-io/terramate/errors"
"github.com/terramate-io/terramate/fs"
"github.com/terramate-io/terramate/hcl/ast"
"github.com/terramate-io/terramate/hcl/eval"
"github.com/terramate-io/terramate/hcl/info"
"github.com/terramate-io/terramate/project"
"github.com/terramate-io/terramate/safeguard"
"github.com/terramate-io/terramate/stdlib"
"github.com/zclconf/go-cty/cty"
"golang.org/x/exp/slices"
)
// Errors returned during the HCL parsing.
const (
ErrHCLSyntax errors.Kind = "HCL syntax error"
ErrTerramateSchema errors.Kind = "terramate schema error"
ErrUnrecognizedBlock errors.Kind = "terramate schema error: unrecognized block"
ErrImport errors.Kind = "import error"
)
const (
// StackBlockType name of the stack block type
StackBlockType = "stack"
)
// OptionalCheck is a bool that can also have no configured value.
type OptionalCheck int
const (
// CheckIsUnset means no value was specified.
CheckIsUnset OptionalCheck = iota
// CheckIsFalse means the check is disabled.
CheckIsFalse
// CheckIsTrue means the check is enabled.
CheckIsTrue
)
// ValueOr returns if an OptionalCheck is enabled, or the given default if its unset.
func (v OptionalCheck) ValueOr(def bool) bool {
if v == CheckIsUnset {
return def
}
return v == CheckIsTrue
}
// ToOptionalCheck creates an OptionalCheck value from a bool.
func ToOptionalCheck(v bool) OptionalCheck {
if v {
return CheckIsTrue
}
return CheckIsFalse
}
// Config represents a Terramate configuration.
type Config struct {
Terramate *Terramate
Stack *Stack
Globals ast.MergedLabelBlocks
Vendor *VendorConfig
Asserts []AssertConfig
Generate GenerateConfig
Scripts []*Script
SharingBackends SharingBackends
Inputs Inputs
Outputs Outputs
Imported RawConfig
// absdir is the absolute path to the configuration directory.
absdir string
}
// GenerateConfig includes code generation related configurations, like
// generate_file and generate_hcl.
type GenerateConfig struct {
Files []GenFileBlock
HCLs []GenHCLBlock
}
// AssertConfig represents Terramate assert configuration block.
type AssertConfig struct {
Range info.Range
Warning hcl.Expression
Assertion hcl.Expression
Message hcl.Expression
}
// StackFilterConfig represents Terramate stack_filter configuration block.
type StackFilterConfig struct {
ProjectPaths []glob.Glob
RepositoryPaths []glob.Glob
}
// SharingBackendType is the type of the sharing backend.
type SharingBackendType int
// SharingBackends is a list of SharingBackend blocks.
type SharingBackends []SharingBackend
// Inputs is a list of Input blocks.
type Inputs []Input
// Outputs is a list of Output blocks.
type Outputs []Output
// SharingBackend holds the parsed values for the `sharing_backend` block.
type SharingBackend struct {
Name string
Type SharingBackendType
Command []string
Filename string
}
// Input holds the parsed values for the `input` block.
type Input struct {
info.Range
Name string
Backend hcl.Expression
FromStackID hcl.Expression
Value hcl.Expression
Sensitive hcl.Expression
Mock hcl.Expression
}
// Output holds the parsed value for the `output` block.
type Output struct {
info.Range
Name string
Backend hcl.Expression
Description hcl.Expression
Value hcl.Expression
Sensitive hcl.Expression
}
// These are the valid sharing_backend types.
const (
TerraformSharingBackend SharingBackendType = iota + 1
)
func (st SharingBackendType) String() string {
switch st {
case TerraformSharingBackend:
return "terraform"
}
return "<unknown>"
}
// MatchAnyGlob is a helper function to test if s matches any of the given patterns.
func MatchAnyGlob(globs []glob.Glob, s string) bool {
for _, g := range globs {
if g.Match(s) {
return true
}
}
return false
}
// RunConfig represents Terramate run configuration.
type RunConfig struct {
// CheckGenCode enables generated code is up-to-date check on run.
CheckGenCode bool
// Env contains environment definitions for run.
Env *RunEnv
}
// RunEnv represents Terramate run environment.
type RunEnv struct {
// Attributes is the collection of attribute definitions within the env block.
Attributes ast.Attributes
}
// GitConfig represents Terramate Git configuration.
type GitConfig struct {
// DefaultBranch is the default branch.
DefaultBranch string
// DefaultRemote is the default remote.
DefaultRemote string
// CheckUntracked enables untracked files checking.
CheckUntracked bool
// CheckUncommitted enables uncommitted files checking.
CheckUncommitted bool
// CheckRemote enables checking if local default branch is updated with remote.
CheckRemote OptionalCheck
}
// ChangeDetectionConfig is the `terramate.config.change_detection` config.
type ChangeDetectionConfig struct {
Terragrunt *TerragruntChangeDetectionConfig
Git *GitChangeDetectionConfig
}
// GitChangeDetectionConfig is the `terramate.config.change_detection.git` config.
type GitChangeDetectionConfig struct {
Untracked *bool
Uncommitted *bool
}
// TerragruntChangeDetectionConfig is the `terramate.config.change_detection.terragrunt` config.
type TerragruntChangeDetectionConfig struct {
Enabled TerragruntChangeDetectionEnabledOption
}
// TerragruntChangeDetectionEnabledOption is the change detection options for enabling Terragrunt.
type TerragruntChangeDetectionEnabledOption int
// Terragrunt Enabling options.
const (
TerragruntAutoOption TerragruntChangeDetectionEnabledOption = iota
TerragruntOffOption
TerragruntForceOption
)
// GenerateRootConfig represents the AST node for the `terramate.config.generate` block.
type GenerateRootConfig struct {
HCLMagicHeaderCommentStyle *string
}
// CloudConfig represents Terramate cloud configuration.
type CloudConfig struct {
// Organization is the name of the cloud organization
Organization string
Targets *TargetsConfig
}
// TargetsConfig represents Terramate targets configuration.
type TargetsConfig struct {
Enabled bool
}
// TelemetryConfig represents Terramate telemetry configuration.
type TelemetryConfig struct {
Enabled *bool
}
// RootConfig represents the root config block of a Terramate configuration.
type RootConfig struct {
Git *GitConfig
Generate *GenerateRootConfig
ChangeDetection *ChangeDetectionConfig
Run *RunConfig
Cloud *CloudConfig
Experiments []string
DisableSafeguards safeguard.Keywords
Telemetry *TelemetryConfig
}
// ManifestDesc represents a parsed manifest description.
type ManifestDesc struct {
// Files is a list of patterns that specify which files the manifest wants to include.
Files []string
// Excludes is a list of patterns that specify which files the manifest wants to exclude.
Excludes []string
}
// ManifestConfig represents the manifest config block of a Terramate configuration.
type ManifestConfig struct {
Default *ManifestDesc
}
// VendorConfig is the parsed "vendor" HCL block.
type VendorConfig struct {
// Manifest is the parsed manifest block, if any.
Manifest *ManifestConfig
// Dir is the path where vendored projects will be stored.
Dir string
}
// Terramate is the parsed "terramate" HCL block.
type Terramate struct {
// RequiredVersion contains the terramate version required by the stack.
RequiredVersion string
// RequiredVersionAllowPreReleases allows pre-release to be matched if true.
RequiredVersionAllowPreReleases bool
// Config is the parsed config blocks.
Config *RootConfig
}
// Stack is the parsed "stack" HCL block.
type Stack struct {
// ID of the stack. If the ID is empty it indicates this stack has no ID.
ID string
// Name of the stack
Name string
// Description of the stack
Description string
// Tags is a list of non-duplicated list of tags
Tags []string
// After is a list of non-duplicated stack entries that must run before the
// current stack runs.
After []string
// Before is a list of non-duplicated stack entries that must run after the
// current stack runs.
Before []string
// Wants is a list of non-duplicated stack entries that must be selected
// whenever the current stack is selected.
Wants []string
// WantedBy is a list of non-duplicated stack entries that must select
// this stack whenever they are selected.
WantedBy []string
// Watch is a list of files to be watched for changes.
Watch []string
}
// GenHCLBlock represents a parsed generate_hcl block.
type GenHCLBlock struct {
// Dir where the block is declared.
Dir project.Path
// Range is the range of the entire block definition.
Range info.Range
// Label of the block.
Label string
// Lets is a block of local variables.
Lets *ast.MergedBlock
// Condition attribute of the block, if any.
Condition *hclsyntax.Attribute
// Represents all stack_filter blocks
StackFilters []StackFilterConfig
// Content block.
Content *hcl.Block
// Asserts represents all assert blocks
Asserts []AssertConfig
// Inherit tells if the block is inherited in child directories.
Inherit *hclsyntax.Attribute
// IsImplicitBlock tells if the block is implicit (does not have a real generate_hcl block).
// This is the case for the "tmgen" feature.
IsImplicitBlock bool
}
// GenFileBlock represents a parsed generate_file block
type GenFileBlock struct {
// Dir where the block is declared.
Dir project.Path
// Range is the range of the entire block definition.
Range info.Range
// Label of the block
Label string
// Lets is a block of local variables.
Lets *ast.MergedBlock
// Condition attribute of the block, if any.
Condition *hclsyntax.Attribute
// Represents all stack_filter blocks
StackFilters []StackFilterConfig
// Content attribute of the block
Content *hclsyntax.Attribute
// Context of the generation (stack by default).
Context string
// Asserts represents all assert blocks
Asserts []AssertConfig
// Inherit tells if the block is inherited in child directories.
Inherit *hclsyntax.Attribute
}
// Evaluator represents a Terramate evaluator
type Evaluator interface {
// Eval evaluates the given expression returning a value.
Eval(hcl.Expression) (cty.Value, error)
// PartialEval partially evaluates the given expression returning the
// tokens that form the result of the partial evaluation. Any unknown
// namespace access are ignored and left as is, while known namespaces
// are substituted by its value.
// If any unknowns are found, the method returns hasUnknowns as true.
PartialEval(hcl.Expression) (expr hcl.Expression, hasUnknowns bool, err error)
// SetNamespace adds a new namespace, replacing any with the same name.
SetNamespace(name string, values map[string]cty.Value)
// DeleteNamespace deletes a namespace.
DeleteNamespace(name string)
}
// TerramateParser is an HCL parser tailored for Terramate configuration schema.
// As the Terramate configuration can span multiple files in the same directory,
// this API allows you to define the exact set of files (and contents) that are
// going to be included in the final configuration.
type TerramateParser struct {
Config RawConfig
Experiments []string
Imported RawConfig
rootdir string
dir string
files map[string][]byte // path=content
hclparser *hclparse.Parser
evalctx *eval.Context
// parsedFiles stores a map of all parsed files
parsedFiles map[string]parsedFile
strict bool
// if true, calling Parse() or MinimalParse() will fail.
parsed bool
}
// NewGitConfig creates a git configuration with proper default values.
func NewGitConfig() *GitConfig {
return &GitConfig{
CheckUntracked: true,
CheckUncommitted: true,
}
}
// NewRunConfig creates a new run configuration.
func NewRunConfig() *RunConfig {
return &RunConfig{
CheckGenCode: true,
}
}
// parsedFile tells the origin and kind of the parsedFile.
// The kind can be either internal or external, meaning the file was parsed
// by this parser or by another parser instance, respectively.
type parsedFile struct {
kind parsedKind
origin string
}
type parsedKind int
const (
_ parsedKind = iota
internal
external
)
// NewTerramateParser creates a Terramate parser for the directory dir inside
// the root directory.
// The parser creates sub-parsers for parsing imports but keeps a list of all
// parsed files of all sub-parsers for detecting cycles and import duplications.
// Calling Parse() or MinimalParse() multiple times is an error.
func NewTerramateParser(rootdir string, dir string, experiments ...string) (*TerramateParser, error) {
st, err := os.Stat(dir)
if err != nil {
return nil, errors.E(err, "failed to stat directory %q", dir)
}
if !strings.HasPrefix(dir, rootdir) {
return nil, errors.E("directory %q is not inside root %q", dir, rootdir)
}
if !st.IsDir() {
return nil, errors.E("%s is not a directory", dir)
}
return &TerramateParser{
Config: NewTopLevelRawConfig(),
Imported: NewTopLevelRawConfig(),
Experiments: experiments,
rootdir: rootdir,
dir: dir,
files: map[string][]byte{},
hclparser: hclparse.NewParser(),
parsedFiles: make(map[string]parsedFile),
evalctx: eval.NewContext(stdlib.Functions(dir, experiments)),
}, nil
}
// NewStrictTerramateParser is like NewTerramateParser but will fail instead of
// warn for harmless configuration mistakes.
func NewStrictTerramateParser(rootdir string, dir string, experiments ...string) (*TerramateParser, error) {
parser, err := NewTerramateParser(rootdir, dir, experiments...)
if err != nil {
return nil, err
}
parser.strict = true
return parser, nil
}
func (p *TerramateParser) addParsedFile(origin string, kind parsedKind, files ...string) {
for _, file := range files {
p.parsedFiles[file] = parsedFile{
kind: kind,
origin: origin,
}
}
}
// AddDir walks over all the files in the directory dir and add all .tm and
// .tm.hcl files to the parser.
func (p *TerramateParser) AddDir(dir string) error {
res, err := fs.ListTerramateFiles(dir)
if err != nil {
return errors.E(err, "adding directory to terramate parser")
}
for _, filename := range res.TmFiles {
path := filepath.Join(dir, filename)
data, err := os.ReadFile(path)
if err != nil {
return errors.E(err, "reading config file %q", path)
}
if err := p.AddFileContent(path, data); err != nil {
return err
}
}
return nil
}
// AddFile adds a file path to be parsed.
func (p *TerramateParser) AddFile(path string) error {
if !strings.HasPrefix(path, p.dir) {
return errors.E("parser only allow files from directory %q", p.dir)
}
data, err := os.ReadFile(path)
if err != nil {
return errors.E("adding file %q to parser", path, err)
}
return p.AddFileContent(path, data)
}
// AddFileContent adds a file to the set of files to be parsed.
func (p *TerramateParser) AddFileContent(name string, data []byte) error {
if !strings.HasPrefix(name, p.dir) {
return errors.E("parser only allow files from directory %q", p.dir)
}
if _, ok := p.files[name]; ok {
return errors.E(os.ErrExist, "adding file %q to the parser", name)
}
p.files[name] = data
return nil
}
// ParseConfig parses and checks the schema of previously added files and
// return either a Config or an error.
func (p *TerramateParser) ParseConfig() (Config, error) {
errs := errors.L()
errs.Append(p.Parse())
// TODO(i4k): don't validate schema here.
// Changing this requires changes to the editor extensions / linters / etc.
cfg, err := p.parseTerramateSchema()
errs.Append(err)
if err == nil {
errs.Append(p.checkConfigSanity(cfg))
}
if err := errs.AsError(); err != nil {
return Config{}, err
}
return cfg, nil
}
// Parse does the syntax parsing and merging of configurations but do not
// validate if the HCL schema is a valid Terramate configuration.
func (p *TerramateParser) Parse() error {
if p.parsed {
return errors.E("files already parsed")
}
defer func() { p.parsed = true }()
errs := errors.L()
errs.Append(p.parseSyntax())
errs.Append(p.applyImports())
errs.Append(p.mergeConfig())
return errs.AsError()
}
// ParsedBodies returns a map of filename to the parsed hclsyntax.Body.
func (p *TerramateParser) ParsedBodies() map[string]*hclsyntax.Body {
parsed := make(map[string]*hclsyntax.Body)
bodyMap := p.hclparser.Files()
for _, filename := range p.internalParsedFiles() {
hclfile := bodyMap[filename]
// A cast error here would be a severe programming error on Terramate
// side, so we are by design allowing the cast to panic
parsed[filename] = hclfile.Body.(*hclsyntax.Body)
}
return parsed
}
// Imports returns all import blocks.
func (p *TerramateParser) Imports() (ast.Blocks, error) {
errs := errors.L()
var imports ast.Blocks
bodies := p.ParsedBodies()
for _, origin := range p.sortedParsedFilenames() {
body := bodies[origin]
for _, rawBlock := range body.Blocks {
if rawBlock.Type != "import" {
continue
}
importBlock := ast.NewBlock(p.rootdir, rawBlock)
err := validateImportBlock(importBlock)
errs.Append(err)
if err == nil {
imports = append(imports, importBlock)
}
}
}
if err := errs.AsError(); err != nil {
return nil, err
}
return imports, nil
}
func (p *TerramateParser) mergeConfig() error {
errs := errors.L()
bodies := p.ParsedBodies()
for _, origin := range p.sortedParsedFilenames() {
body := bodies[origin]
errs.Append(p.Config.mergeAttrs(ast.NewAttributes(p.rootdir, ast.AsHCLAttributes(body.Attributes))))
errs.Append(p.Config.mergeBlocks(ast.NewBlocks(p.rootdir, body.Blocks)))
}
return errs.AsError()
}
func (p *TerramateParser) parseSyntax() error {
errs := errors.L()
for _, name := range p.sortedFilenames() {
data := p.files[name]
_, diags := p.hclparser.ParseHCL(data, name)
if diags.HasErrors() {
errs.Append(errors.E(ErrHCLSyntax, diags))
continue
}
p.addParsedFile(p.dir, internal, name)
}
return errs.AsError()
}
func (p *TerramateParser) applyImports() error {
importBlocks, err := p.Imports()
if err != nil {
return err
}
errs := errors.L()
for _, importBlock := range importBlocks {
errs.Append(p.handleImport(importBlock))
}
return errs.AsError()
}
func (p *TerramateParser) handleImport(importBlock *ast.Block) error {
srcAttr := importBlock.Attributes["source"]
srcVal, diags := srcAttr.Expr.Value(nil)
if diags.HasErrors() {
return errors.E(ErrTerramateSchema, srcAttr.Expr.Range(),
"failed to evaluate import.source")
}
if srcVal.Type() != cty.String {
return attrErr(srcAttr, "import.source must be a string")
}
src := srcVal.AsString()
srcBase := path.Base(src)
srcDir := path.Dir(src)
if path.IsAbs(srcDir) { // project-path
srcDir = filepath.Join(p.rootdir, srcDir)
} else {
srcDir = filepath.Join(p.dir, srcDir)
}
if srcDir == p.dir {
return errors.E(ErrImport, srcAttr.Expr.Range(),
"importing files in the same directory is not permitted")
}
if strings.HasPrefix(p.dir, srcDir) {
return errors.E(ErrImport, srcAttr.Expr.Range(),
"importing files in the same tree is not permitted")
}
src = filepath.Join(srcDir, srcBase)
matches, err := filepath.Glob(src)
if err != nil {
return errors.E(ErrTerramateSchema, srcAttr.Expr.Range(),
"failed to evaluate import.source")
}
if matches == nil {
return errors.E(ErrImport, srcAttr.Expr.Range(),
"import path %q returned no matches", srcVal.AsString())
}
for _, file := range matches {
if _, ok := p.parsedFiles[file]; ok {
return errors.E(ErrImport, srcAttr.Expr.Range(),
"file %q already parsed", file)
}
st, err := os.Lstat(file)
if err != nil {
return errors.E(
ErrImport,
srcAttr.Expr.Range(),
"failed to stat file %q",
file,
)
}
if st.IsDir() {
return errors.E(
ErrImport,
srcAttr.Expr.Range(),
"import directory is not allowed: %s",
file,
)
}
fileDir := filepath.Dir(file)
importParser, err := NewTerramateParser(p.rootdir, fileDir)
if err != nil {
return errors.E(ErrImport, srcAttr.Expr.Range(),
err, "failed to create sub parser: %s", fileDir)
}
err = importParser.AddFile(file)
if err != nil {
return errors.E(ErrImport, srcAttr.Expr.Range(),
err)
}
importParser.addParsedFile(p.dir, external, p.internalParsedFiles()...)
err = importParser.Parse()
if err != nil {
return err
}
errs := errors.L()
for _, block := range importParser.Config.UnmergedBlocks {
if block.Type == "stack" {
errs.Append(
errors.E(ErrImport, srcAttr.Expr.Range(),
"import of stack block is not permitted"))
}
}
errs.Append(p.Imported.Merge(importParser.Imported))
errs.Append(p.Imported.Merge(importParser.Config))
if err := errs.AsError(); err != nil {
return errors.E(ErrImport, err, "failed to merge imported configuration")
}
p.addParsedFile(p.dir, external, file)
}
return nil
}
func (p *TerramateParser) sortedFilenames() []string {
filenames := []string{}
for fname := range p.files {
filenames = append(filenames, fname)
}
sort.Strings(filenames)
return filenames
}
func (p *TerramateParser) sortedParsedFilenames() []string {
filenames := append([]string{}, p.internalParsedFiles()...)
sort.Strings(filenames)
return filenames
}
func (p *TerramateParser) internalParsedFiles() []string {
filenames := []string{}
for fname, parsed := range p.parsedFiles {
if parsed.kind == internal {
filenames = append(filenames, fname)
}
}
sort.Strings(filenames)
return filenames
}
func (p *TerramateParser) parseStack(stackblock *ast.Block) (*Stack, error) {
errs := errors.L()
for _, block := range stackblock.Body.Blocks {
errs.Append(
errors.E(block.TypeRange, "unrecognized block %q", block.Type),
)
}
stack := &Stack{}
attrs := ast.AsHCLAttributes(stackblock.Body.Attributes)
for _, attr := range ast.SortRawAttributes(attrs) {
attrVal, err := p.evalctx.Eval(attr.Expr)
if err != nil {
errs.Append(
errors.E(err, "failed to evaluate %q attribute", attr.Name),
)
continue
}
switch attr.Name {
case "id":
if attrVal.Type() != cty.String {
errs.Append(hclAttrErr(attr,
"field stack.id must be a string but is %q",
attrVal.Type().FriendlyName()),
)
continue
}
stack.ID = attrVal.AsString()
case "name":
if attrVal.Type() != cty.String {
errs.Append(hclAttrErr(attr,
"field stack.name must be a string but given %q",
attrVal.Type().FriendlyName()),
)
continue
}
stack.Name = attrVal.AsString()
case "description":
if attrVal.Type() != cty.String {
errs.Append(hclAttrErr(attr,
"field stack.\"description\" must be a \"string\" but given %q",
attrVal.Type().FriendlyName(),
))
continue
}
stack.Description = attrVal.AsString()
// The `tags`, `after`, `before`, `wants`, `wanted_by` and `watch`
// have all the same parsing rules.
// By the spec, they must be a `set(string)`.
// In order to speed up the tests, only the `after` attribute is
// extensively tested for all error cases.
// **So have this in mind if the specification of any of the attributes
// below change in the future**.
case "tags":
errs.Append(assignSet(attr, &stack.Tags, attrVal))
case "after":
errs.Append(assignSet(attr, &stack.After, attrVal))
case "before":
errs.Append(assignSet(attr, &stack.Before, attrVal))
case "wants":
errs.Append(assignSet(attr, &stack.Wants, attrVal))
case "wanted_by":
errs.Append(assignSet(attr, &stack.WantedBy, attrVal))
case "watch":
errs.Append(assignSet(attr, &stack.Watch, attrVal))
default:
errs.Append(errors.E(
attr.NameRange, "unrecognized attribute stack.%q", attr.Name,
))
}
}
if err := errs.AsError(); err != nil {
return nil, err
}
return stack, nil
}
// NewConfig creates a new HCL config with dir as config directory path.
func NewConfig(dir string) (Config, error) {
st, err := os.Stat(dir)
if err != nil {
return Config{}, errors.E(err, "initializing config")
}
if !st.IsDir() {
return Config{}, errors.E("config constructor requires a directory path")
}
return Config{
absdir: dir,
Imported: NewTopLevelRawConfig(),
}, nil
}
// IsRootConfig tells if the Config is a root configuration.
func (c Config) IsRootConfig() bool {
return c.Terramate != nil && c.Terramate.RequiredVersion != ""
}
// HasRunEnv returns true if the config has a terramate.config.run.env block defined
func (c Config) HasRunEnv() bool {
return c.Terramate != nil &&
c.Terramate.Config != nil &&
c.Terramate.Config.Run != nil &&
c.Terramate.Config.Run.Env != nil
}
// Experiments returns the config enabled experiments, if any.
func (c Config) Experiments() []string {
if c.Terramate != nil &&
c.Terramate.Config != nil {
return c.Terramate.Config.Experiments
}
return []string{}
}
// AbsDir returns the absolute path of the configuration directory.
func (c Config) AbsDir() string { return c.absdir }
// IsEmpty returns true if the config is empty, false otherwise.
func (c Config) IsEmpty() bool {
return c.Stack == nil && c.Terramate == nil &&
c.Vendor == nil && len(c.Asserts) == 0 &&
len(c.Globals) == 0 &&
len(c.Generate.Files) == 0 && len(c.Generate.HCLs) == 0
}
// HasGlobals tells if the configuration has any globals defined.
func (c Config) HasGlobals() bool {
return len(c.Globals) > 0
}
// Save the configuration file using filename inside config directory.
func (c Config) Save(filename string) (err error) {
cfgpath := filepath.Join(c.absdir, filename)
f, err := os.Create(cfgpath)
if err != nil {
return errors.E(err, "saving configuration file %q", cfgpath)
}
defer func() {
err2 := f.Close()
if err != nil {
return
}
err = err2
}()
return PrintConfig(f, c)
}
// ParseDir will parse Terramate configuration from a given directory,
// using root as project workspace, parsing all files with the suffixes .tm and
// .tm.hcl. It parses in non-strict mode for compatibility with older versions.
// Note: it does not recurse into child directories.
func ParseDir(root string, dir string, experiments ...string) (Config, error) {
p, err := NewTerramateParser(root, dir, experiments...)
if err != nil {
return Config{}, err
}
err = p.AddDir(dir)
if err != nil {
return Config{}, errors.E("adding files to parser", err)
}
return p.ParseConfig()
}
// IsRootConfig parses rootdir and tells if it contains a root config or not.
func IsRootConfig(rootdir string) (bool, error) {
p, err := NewTerramateParser(rootdir, rootdir)
if err != nil {
return false, err
}