aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go
blob: 86ffdf11dd32203db57ff5b7560feafb905041a6 (plain) (blame)
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
package tfconfig

import (
	"io/ioutil"
	"strings"

	legacyhcl "github.com/hashicorp/hcl"
	legacyast "github.com/hashicorp/hcl/hcl/ast"
)

func loadModuleLegacyHCL(dir string) (*Module, Diagnostics) {
	// This implementation is intentionally more quick-and-dirty than the
	// main loader. In particular, it doesn't bother to keep careful track
	// of multiple error messages because we always fall back on returning
	// the main parser's error message if our fallback parsing produces
	// an error, and thus the errors here are not seen by the end-caller.
	mod := newModule(dir)

	primaryPaths, diags := dirFiles(dir)
	if diags.HasErrors() {
		return mod, diagnosticsHCL(diags)
	}

	for _, filename := range primaryPaths {
		src, err := ioutil.ReadFile(filename)
		if err != nil {
			return mod, diagnosticsErrorf("Error reading %s: %s", filename, err)
		}

		hclRoot, err := legacyhcl.Parse(string(src))
		if err != nil {
			return mod, diagnosticsErrorf("Error parsing %s: %s", filename, err)
		}

		list, ok := hclRoot.Node.(*legacyast.ObjectList)
		if !ok {
			return mod, diagnosticsErrorf("Error parsing %s: no root object", filename)
		}

		for _, item := range list.Filter("terraform").Items {
			if len(item.Keys) > 0 {
				item = &legacyast.ObjectItem{
					Val: &legacyast.ObjectType{
						List: &legacyast.ObjectList{
							Items: []*legacyast.ObjectItem{item},
						},
					},
				}
			}

			type TerraformBlock struct {
				RequiredVersion string `hcl:"required_version"`
			}
			var block TerraformBlock
			err = legacyhcl.DecodeObject(&block, item.Val)
			if err != nil {
				return nil, diagnosticsErrorf("terraform block: %s", err)
			}

			if block.RequiredVersion != "" {
				mod.RequiredCore = append(mod.RequiredCore, block.RequiredVersion)
			}
		}

		if vars := list.Filter("variable"); len(vars.Items) > 0 {
			vars = vars.Children()
			type VariableBlock struct {
				Type        string `hcl:"type"`
				Default     interface{}
				Description string
				Fields      []string `hcl:",decodedFields"`
			}

			for _, item := range vars.Items {
				unwrapLegacyHCLObjectKeysFromJSON(item, 1)

				if len(item.Keys) != 1 {
					return nil, diagnosticsErrorf("variable block at %s has no label", item.Pos())
				}

				name := item.Keys[0].Token.Value().(string)

				var block VariableBlock
				err := legacyhcl.DecodeObject(&block, item.Val)
				if err != nil {
					return nil, diagnosticsErrorf("invalid variable block at %s: %s", item.Pos(), err)
				}

				// Clean up legacy HCL decoding ambiguity by unwrapping list of maps
				if ms, ok := block.Default.([]map[string]interface{}); ok {
					def := make(map[string]interface{})
					for _, m := range ms {
						for k, v := range m {
							def[k] = v
						}
					}
					block.Default = def
				}

				v := &Variable{
					Name:        name,
					Type:        block.Type,
					Description: block.Description,
					Default:     block.Default,
					Pos:         sourcePosLegacyHCL(item.Pos(), filename),
				}
				if _, exists := mod.Variables[name]; exists {
					return nil, diagnosticsErrorf("duplicate variable block for %q", name)
				}
				mod.Variables[name] = v

			}
		}

		if outputs := list.Filter("output"); len(outputs.Items) > 0 {
			outputs = outputs.Children()
			type OutputBlock struct {
				Description string
			}

			for _, item := range outputs.Items {
				unwrapLegacyHCLObjectKeysFromJSON(item, 1)

				if len(item.Keys) != 1 {
					return nil, diagnosticsErrorf("output block at %s has no label", item.Pos())
				}

				name := item.Keys[0].Token.Value().(string)

				var block OutputBlock
				err := legacyhcl.DecodeObject(&block, item.Val)
				if err != nil {
					return nil, diagnosticsErrorf("invalid output block at %s: %s", item.Pos(), err)
				}

				o := &Output{
					Name:        name,
					Description: block.Description,
					Pos:         sourcePosLegacyHCL(item.Pos(), filename),
				}
				if _, exists := mod.Outputs[name]; exists {
					return nil, diagnosticsErrorf("duplicate output block for %q", name)
				}
				mod.Outputs[name] = o
			}
		}

		for _, blockType := range []string{"resource", "data"} {
			if resources := list.Filter(blockType); len(resources.Items) > 0 {
				resources = resources.Children()
				type ResourceBlock struct {
					Provider string
				}

				for _, item := range resources.Items {
					unwrapLegacyHCLObjectKeysFromJSON(item, 2)

					if len(item.Keys) != 2 {
						return nil, diagnosticsErrorf("resource block at %s has wrong label count", item.Pos())
					}

					typeName := item.Keys[0].Token.Value().(string)
					name := item.Keys[1].Token.Value().(string)
					var mode ResourceMode
					var rMap map[string]*Resource
					switch blockType {
					case "resource":
						mode = ManagedResourceMode
						rMap = mod.ManagedResources
					case "data":
						mode = DataResourceMode
						rMap = mod.DataResources
					}

					var block ResourceBlock
					err := legacyhcl.DecodeObject(&block, item.Val)
					if err != nil {
						return nil, diagnosticsErrorf("invalid resource block at %s: %s", item.Pos(), err)
					}

					var providerName, providerAlias string
					if dotPos := strings.IndexByte(block.Provider, '.'); dotPos != -1 {
						providerName = block.Provider[:dotPos]
						providerAlias = block.Provider[dotPos+1:]
					} else {
						providerName = block.Provider
					}
					if providerName == "" {
						providerName = resourceTypeDefaultProviderName(typeName)
					}

					r := &Resource{
						Mode: mode,
						Type: typeName,
						Name: name,
						Provider: ProviderRef{
							Name:  providerName,
							Alias: providerAlias,
						},
						Pos: sourcePosLegacyHCL(item.Pos(), filename),
					}
					key := r.MapKey()
					if _, exists := rMap[key]; exists {
						return nil, diagnosticsErrorf("duplicate resource block for %q", key)
					}
					rMap[key] = r
				}
			}

		}

		if moduleCalls := list.Filter("module"); len(moduleCalls.Items) > 0 {
			moduleCalls = moduleCalls.Children()
			type ModuleBlock struct {
				Source  string
				Version string
			}

			for _, item := range moduleCalls.Items {
				unwrapLegacyHCLObjectKeysFromJSON(item, 1)

				if len(item.Keys) != 1 {
					return nil, diagnosticsErrorf("module block at %s has no label", item.Pos())
				}

				name := item.Keys[0].Token.Value().(string)

				var block ModuleBlock
				err := legacyhcl.DecodeObject(&block, item.Val)
				if err != nil {
					return nil, diagnosticsErrorf("module block at %s: %s", item.Pos(), err)
				}

				mc := &ModuleCall{
					Name:    name,
					Source:  block.Source,
					Version: block.Version,
					Pos:     sourcePosLegacyHCL(item.Pos(), filename),
				}
				// it's possible this module call is from an override file
				if origMod, exists := mod.ModuleCalls[name]; exists {
					if mc.Source == "" {
						mc.Source = origMod.Source
					}
				}
				mod.ModuleCalls[name] = mc
			}
		}

		if providerConfigs := list.Filter("provider"); len(providerConfigs.Items) > 0 {
			providerConfigs = providerConfigs.Children()
			type ProviderBlock struct {
				Version string
			}

			for _, item := range providerConfigs.Items {
				unwrapLegacyHCLObjectKeysFromJSON(item, 1)

				if len(item.Keys) != 1 {
					return nil, diagnosticsErrorf("provider block at %s has no label", item.Pos())
				}

				name := item.Keys[0].Token.Value().(string)

				var block ProviderBlock
				err := legacyhcl.DecodeObject(&block, item.Val)
				if err != nil {
					return nil, diagnosticsErrorf("invalid provider block at %s: %s", item.Pos(), err)
				}

				if block.Version != "" {
					mod.RequiredProviders[name] = append(mod.RequiredProviders[name], block.Version)
				}

				// Even if there wasn't an explicit version required, we still
				// need an entry in our map to signal the unversioned dependency.
				if _, exists := mod.RequiredProviders[name]; !exists {
					mod.RequiredProviders[name] = []string{}
				}

			}
		}
	}

	return mod, nil
}

// unwrapLegacyHCLObjectKeysFromJSON cleans up an edge case that can occur when
// parsing JSON as input: if we're parsing JSON then directly nested
// items will show up as additional "keys".
//
// For objects that expect a fixed number of keys, this breaks the
// decoding process. This function unwraps the object into what it would've
// looked like if it came directly from HCL by specifying the number of keys
// you expect.
//
// Example:
//
// { "foo": { "baz": {} } }
//
// Will show up with Keys being: []string{"foo", "baz"}
// when we really just want the first two. This function will fix this.
func unwrapLegacyHCLObjectKeysFromJSON(item *legacyast.ObjectItem, depth int) {
	if len(item.Keys) > depth && item.Keys[0].Token.JSON {
		for len(item.Keys) > depth {
			// Pop off the last key
			n := len(item.Keys)
			key := item.Keys[n-1]
			item.Keys[n-1] = nil
			item.Keys = item.Keys[:n-1]

			// Wrap our value in a list
			item.Val = &legacyast.ObjectType{
				List: &legacyast.ObjectList{
					Items: []*legacyast.ObjectItem{
						&legacyast.ObjectItem{
							Keys: []*legacyast.ObjectKey{key},
							Val:  item.Val,
						},
					},
				},
			}
		}
	}
}