-
Notifications
You must be signed in to change notification settings - Fork 367
/
Copy pathparser.go
340 lines (296 loc) · 9.61 KB
/
parser.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
package terraform
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/spf13/afero"
"github.com/zclconf/go-cty/cty"
)
// Parser is a fork of configs.Parser. This is the main interface to read
// configuration files and other related files from disk.
//
// It retains a cache of all files that are loaded so that they can be used
// to create source code snippets in diagnostics, etc.
type Parser struct {
fs afero.Afero
p *hclparse.Parser
}
// NewParser creates and returns a new Parser that reads files from the given
// filesystem. If a nil filesystem is passed then the system's "real" filesystem
// will be used, via afero.OsFs.
func NewParser(fs afero.Fs) *Parser {
if fs == nil {
fs = afero.OsFs{}
}
return &Parser{
fs: afero.Afero{Fs: fs},
p: hclparse.NewParser(),
}
}
// LoadConfigDir reads the .tf and .tf.json files in the given directory and
// then combines these files into a single Module.
//
// If this method returns nil, that indicates that the given directory does not
// exist at all or could not be opened for some reason. Callers may wish to
// detect this case and ignore the returned diagnostics so that they can
// produce a more context-aware error message in that case.
//
// If this method returns a non-nil module while error diagnostics are returned
// then the module may be incomplete but can be used carefully for static
// analysis.
//
// This file does not consider a directory with no files to be an error, and
// will simply return an empty module in that case.
//
// .tf files are parsed using the HCL native syntax while .tf.json files are
// parsed using the HCL JSON syntax.
//
// If a baseDir is passed, the loaded files are assumed to be loaded from that
// directory. However, SourceDir does not contain baseDir because it affects
// `path.module` and `path.root` values.
func (p *Parser) LoadConfigDir(baseDir, dir string) (*Module, hcl.Diagnostics) {
primaries, overrides, diags := p.configDirFiles(baseDir, dir)
if diags.HasErrors() {
return nil, diags
}
mod := NewEmptyModule()
for _, path := range primaries {
f, loadDiags := p.loadHCLFile(baseDir, path)
diags = diags.Extend(loadDiags)
if loadDiags.HasErrors() {
continue
}
realPath := filepath.Join(baseDir, path)
mod.primaries[realPath] = f
mod.Sources[realPath] = f.Bytes
mod.Files[realPath] = f
}
for _, path := range overrides {
f, loadDiags := p.loadHCLFile(baseDir, path)
diags = diags.Extend(loadDiags)
if loadDiags.HasErrors() {
continue
}
realPath := filepath.Join(baseDir, path)
mod.overrides[realPath] = f
mod.Sources[realPath] = f.Bytes
mod.Files[realPath] = f
}
if diags.HasErrors() {
return mod, diags
}
// Do not contain baseDir because it affects `path.module` and `path.root` values.
mod.SourceDir = dir
buildDiags := mod.build()
diags = diags.Extend(buildDiags)
return mod, diags
}
// LoadConfigDirFiles reads the .tf and .tf.json files in the given directory and
// then returns these files as a map of file path.
//
// The difference with LoadConfigDir is that it returns hcl.File instead of
// a single module. This is useful when parsing HCL files in a context outside of
// Terraform.
//
// If a baseDir is passed, the loaded files are assumed to be loaded from that
// directory.
func (p *Parser) LoadConfigDirFiles(baseDir, dir string) (map[string]*hcl.File, hcl.Diagnostics) {
primaries, overrides, diags := p.configDirFiles(baseDir, dir)
if diags.HasErrors() {
return map[string]*hcl.File{}, diags
}
files := map[string]*hcl.File{}
for _, path := range primaries {
f, loadDiags := p.loadHCLFile(baseDir, path)
diags = diags.Extend(loadDiags)
if loadDiags.HasErrors() {
continue
}
files[filepath.Join(baseDir, path)] = f
}
for _, path := range overrides {
f, loadDiags := p.loadHCLFile(baseDir, path)
diags = diags.Extend(loadDiags)
if loadDiags.HasErrors() {
continue
}
files[filepath.Join(baseDir, path)] = f
}
return files, diags
}
// LoadValuesFile reads the file at the given path and parses it as a "values
// file", which is an HCL config file whose top-level attributes are treated
// as arbitrary key.value pairs.
//
// If the file cannot be read -- for example, if it does not exist -- then
// a nil map will be returned along with error diagnostics. Callers may wish
// to disregard the returned diagnostics in this case and instead generate
// their own error message(s) with additional context.
//
// If the returned diagnostics has errors when a non-nil map is returned
// then the map may be incomplete but should be valid enough for careful
// static analysis.
//
// If a baseDir is passed, the loaded file is assumed to be loaded from that
// directory.
func (p *Parser) LoadValuesFile(baseDir, path string) (map[string]cty.Value, hcl.Diagnostics) {
f, diags := p.loadHCLFile(baseDir, path)
if diags.HasErrors() {
return nil, diags
}
vals := make(map[string]cty.Value)
if f == nil || f.Body == nil {
return vals, diags
}
attrs, attrDiags := f.Body.JustAttributes()
diags = diags.Extend(attrDiags)
if attrs == nil {
return vals, diags
}
for name, attr := range attrs {
val, valDiags := attr.Expr.Value(nil)
diags = diags.Extend(valDiags)
vals[name] = val
}
return vals, diags
}
func (p *Parser) loadHCLFile(baseDir, path string) (*hcl.File, hcl.Diagnostics) {
src, err := p.fs.ReadFile(path)
realPath := filepath.Join(baseDir, path)
if err != nil {
if os.IsNotExist(err) {
return nil, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Failed to read file",
Subject: &hcl.Range{},
Detail: fmt.Sprintf("The file %q does not exist.", realPath),
},
}
}
return nil, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Failed to read file",
Subject: &hcl.Range{},
Detail: fmt.Sprintf("The file %q could not be read.", realPath),
},
}
}
switch {
case strings.HasSuffix(path, ".json"):
return p.p.ParseJSON(src, realPath)
default:
return p.p.ParseHCL(src, realPath)
}
}
// Sources returns a map of the cached source buffers for all files that
// have been loaded through this parser, with source filenames (as requested
// when each file was opened) as the keys.
func (p *Parser) Sources() map[string][]byte {
return p.p.Sources()
}
// Files returns a map of the cached HCL file objects for all files that
// have been loaded through this parser, with source filenames (as requested
// when each file was opened) as the keys.
func (p *Parser) Files() map[string]*hcl.File {
return p.p.Files()
}
// IsConfigDir determines whether the given path refers to a directory that
// exists and contains at least one Terraform config file (with a .tf or
// .tf.json extension.)
func (p *Parser) IsConfigDir(baseDir, path string) bool {
primaryPaths, overridePaths, _ := p.configDirFiles(baseDir, path)
return (len(primaryPaths) + len(overridePaths)) > 0
}
// Exists returns true if the given path exists in fs.
func (p *Parser) Exists(path string) bool {
_, err := p.fs.Stat(path)
return err == nil
}
func (p *Parser) configDirFiles(baseDir, dir string) (primary, override []string, diags hcl.Diagnostics) {
infos, err := p.fs.ReadDir(dir)
if err != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Failed to read module directory",
Subject: &hcl.Range{},
Detail: fmt.Sprintf("Module directory %s does not exist or cannot be read.", filepath.Join(baseDir, dir)),
})
return
}
for _, info := range infos {
if info.IsDir() {
// We only care about files
continue
}
name := info.Name()
ext := configFileExt(name)
if ext == "" || isIgnoredFile(name) {
continue
}
baseName := name[:len(name)-len(ext)] // strip extension
isOverride := baseName == "override" || strings.HasSuffix(baseName, "_override")
fullPath := filepath.Join(dir, name)
if isOverride {
override = append(override, fullPath)
} else {
primary = append(primary, fullPath)
}
}
return
}
func (p *Parser) autoLoadValuesDirFiles(baseDir, dir string) (files []string, diags hcl.Diagnostics) {
infos, err := p.fs.ReadDir(dir)
if err != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Failed to read module directory",
Subject: &hcl.Range{},
Detail: fmt.Sprintf("Module directory %s does not exist or cannot be read.", filepath.Join(baseDir, dir)),
})
return nil, diags
}
for _, info := range infos {
if info.IsDir() {
// We only care about files
continue
}
name := info.Name()
if !isAutoVarFile(name) {
continue
}
fullPath := filepath.Join(dir, name)
files = append(files, fullPath)
}
// The files should be sorted alphabetically. This is equivalent to priority.
sort.Strings(files)
return
}
// configFileExt returns the Terraform configuration extension of the given
// path, or a blank string if it is not a recognized extension.
func configFileExt(path string) string {
if strings.HasSuffix(path, ".tf") {
return ".tf"
} else if strings.HasSuffix(path, ".tf.json") {
return ".tf.json"
} else {
return ""
}
}
// isAutoVarFile determines if the file ends with .auto.tfvars or .auto.tfvars.json
func isAutoVarFile(path string) bool {
return strings.HasSuffix(path, ".auto.tfvars") ||
strings.HasSuffix(path, ".auto.tfvars.json")
}
// isIgnoredFile returns true if the given filename (which must not have a
// directory path ahead of it) should be ignored as e.g. an editor swap file.
func isIgnoredFile(name string) bool {
return strings.HasPrefix(name, ".") || // Unix-like hidden files
strings.HasSuffix(name, "~") || // vim
strings.HasPrefix(name, "#") && strings.HasSuffix(name, "#") // emacs
}