Debian Codegraph @

tfconfig/load_legacy.go

raw
1 // Copyright (c) HashiCorp, Inc.
2 // SPDX-License-Identifier: MPL-2.0
3
4 package tfconfig
5
6 import (
7 "strings"
8
9 legacyhcl "github.com/hashicorp/hcl"
10 legacyast "github.com/hashicorp/hcl/hcl/ast"
11 )
12
13 func loadModuleLegacyHCL(fs FS, dir string) (*Module, Diagnostics) {
14 // This implementation is intentionally more quick-and-dirty than the
15 // main loader. In particular, it doesn't bother to keep careful track
16 // of multiple error messages because we always fall back on returning
17 // the main parser's error message if our fallback parsing produces
18 // an error, and thus the errors here are not seen by the end-caller.
19 mod := NewModule(dir)
20
21 primaryPaths, diags := dirFiles(fs, dir)
22 if diags.HasErrors() {
23 return mod, diagnosticsHCL(diags)
24 }
25
26 for _, filename := range primaryPaths {
27 src, err := fs.ReadFile(filename)
28 if err != nil {
29 return mod, diagnosticsErrorf("Error reading %s: %s", filename, err)
30 }
31
32 hclRoot, err := legacyhcl.Parse(string(src))
33 if err != nil {
34 return mod, diagnosticsErrorf("Error parsing %s: %s", filename, err)
35 }
36
37 list, ok := hclRoot.Node.(*legacyast.ObjectList)
38 if !ok {
39 return mod, diagnosticsErrorf("Error parsing %s: no root object", filename)
40 }
41
42 for _, item := range list.Filter("terraform").Items {
43 if len(item.Keys) > 0 {
44 item = &legacyast.ObjectItem{
45 Val: &legacyast.ObjectType{
46 List: &legacyast.ObjectList{
47 Items: []*legacyast.ObjectItem{item},
48 },
49 },
50 }
51 }
52
53 type TerraformBlock struct {
54 RequiredVersion string `hcl:"required_version"`
55 RequiredProviders interface{} `hcl:"required_providers"`
56 Fields []string `hcl:",decodedFields"`
57 }
58 var block TerraformBlock
59 err = legacyhcl.DecodeObject(&block, item.Val)
60 if err != nil {
61 return nil, diagnosticsErrorf("terraform block: %s", err)
62 }
63
64 for _, field := range block.Fields {
65 if field == "RequiredProviders" {
66 return nil, diagnosticsErrorf("terraform.required_providers must not exist")
67 }
68 }
69
70 if block.RequiredVersion != "" {
71 mod.RequiredCore = append(mod.RequiredCore, block.RequiredVersion)
72 }
73 }
74
75 if vars := list.Filter("variable"); len(vars.Items) > 0 {
76 vars = vars.Children()
77 type VariableBlock struct {
78 Type string `hcl:"type"`
79 Default interface{}
80 Description string
81 Fields []string `hcl:",decodedFields"`
82 }
83
84 for _, item := range vars.Items {
85 unwrapLegacyHCLObjectKeysFromJSON(item, 1)
86
87 if len(item.Keys) != 1 {
88 return nil, diagnosticsErrorf("variable block at %s has no label", item.Pos())
89 }
90
91 name := item.Keys[0].Token.Value().(string)
92
93 var block VariableBlock
94 err := legacyhcl.DecodeObject(&block, item.Val)
95 if err != nil {
96 return nil, diagnosticsErrorf("invalid variable block at %s: %s", item.Pos(), err)
97 }
98
99 // Clean up legacy HCL decoding ambiguity by unwrapping list of maps
100 if ms, ok := block.Default.([]map[string]interface{}); ok {
101 def := make(map[string]interface{})
102 for _, m := range ms {
103 for k, v := range m {
104 def[k] = v
105 }
106 }
107 block.Default = def
108 }
109
110 v := &Variable{
111 Name: name,
112 Type: block.Type,
113 Description: block.Description,
114 Default: block.Default,
115 Required: block.Default == nil,
116 Pos: sourcePosLegacyHCL(item.Pos(), filename),
117 }
118 if _, exists := mod.Variables[name]; exists {
119 return nil, diagnosticsErrorf("duplicate variable block for %q", name)
120 }
121 mod.Variables[name] = v
122
123 }
124 }
125
126 if outputs := list.Filter("output"); len(outputs.Items) > 0 {
127 outputs = outputs.Children()
128 type OutputBlock struct {
129 Description string
130 Sensitive bool
131 }
132
133 for _, item := range outputs.Items {
134 unwrapLegacyHCLObjectKeysFromJSON(item, 1)
135
136 if len(item.Keys) != 1 {
137 return nil, diagnosticsErrorf("output block at %s has no label", item.Pos())
138 }
139
140 name := item.Keys[0].Token.Value().(string)
141
142 var block OutputBlock
143 err := legacyhcl.DecodeObject(&block, item.Val)
144 if err != nil {
145 return nil, diagnosticsErrorf("invalid output block at %s: %s", item.Pos(), err)
146 }
147
148 o := &Output{
149 Name: name,
150 Description: block.Description,
151 Sensitive: block.Sensitive,
152 Pos: sourcePosLegacyHCL(item.Pos(), filename),
153 }
154 if _, exists := mod.Outputs[name]; exists {
155 return nil, diagnosticsErrorf("duplicate output block for %q", name)
156 }
157 mod.Outputs[name] = o
158 }
159 }
160
161 for _, blockType := range []string{"resource", "data"} {
162 if resources := list.Filter(blockType); len(resources.Items) > 0 {
163 resources = resources.Children()
164 type ResourceBlock struct {
165 Provider string
166 }
167
168 for _, item := range resources.Items {
169 unwrapLegacyHCLObjectKeysFromJSON(item, 2)
170
171 if len(item.Keys) != 2 {
172 return nil, diagnosticsErrorf("resource block at %s has wrong label count", item.Pos())
173 }
174
175 typeName := item.Keys[0].Token.Value().(string)
176 name := item.Keys[1].Token.Value().(string)
177 var mode ResourceMode
178 var rMap map[string]*Resource
179 switch blockType {
180 case "resource":
181 mode = ManagedResourceMode
182 rMap = mod.ManagedResources
183 case "data":
184 mode = DataResourceMode
185 rMap = mod.DataResources
186 }
187
188 var block ResourceBlock
189 err := legacyhcl.DecodeObject(&block, item.Val)
190 if err != nil {
191 return nil, diagnosticsErrorf("invalid resource block at %s: %s", item.Pos(), err)
192 }
193
194 var providerName, providerAlias string
195 if dotPos := strings.IndexByte(block.Provider, '.'); dotPos != -1 {
196 providerName = block.Provider[:dotPos]
197 providerAlias = block.Provider[dotPos+1:]
198 } else {
199 providerName = block.Provider
200 }
201 if providerName == "" {
202 providerName = resourceTypeDefaultProviderName(typeName)
203 }
204
205 r := &Resource{
206 Mode: mode,
207 Type: typeName,
208 Name: name,
209 Provider: ProviderRef{
210 Name: providerName,
211 Alias: providerAlias,
212 },
213 Pos: sourcePosLegacyHCL(item.Pos(), filename),
214 }
215 key := r.MapKey()
216 if _, exists := rMap[key]; exists {
217 return nil, diagnosticsErrorf("duplicate resource block for %q", key)
218 }
219 rMap[key] = r
220 }
221 }
222
223 }
224
225 if moduleCalls := list.Filter("module"); len(moduleCalls.Items) > 0 {
226 moduleCalls = moduleCalls.Children()
227 type ModuleBlock struct {
228 Source string
229 Version string
230 }
231
232 for _, item := range moduleCalls.Items {
233 unwrapLegacyHCLObjectKeysFromJSON(item, 1)
234
235 if len(item.Keys) != 1 {
236 return nil, diagnosticsErrorf("module block at %s has no label", item.Pos())
237 }
238
239 name := item.Keys[0].Token.Value().(string)
240
241 var block ModuleBlock
242 err := legacyhcl.DecodeObject(&block, item.Val)
243 if err != nil {
244 return nil, diagnosticsErrorf("module block at %s: %s", item.Pos(), err)
245 }
246
247 mc := &ModuleCall{
248 Name: name,
249 Source: block.Source,
250 Version: block.Version,
251 Pos: sourcePosLegacyHCL(item.Pos(), filename),
252 }
253 // it's possible this module call is from an override file
254 if origMod, exists := mod.ModuleCalls[name]; exists {
255 if mc.Source == "" {
256 mc.Source = origMod.Source
257 }
258 }
259 mod.ModuleCalls[name] = mc
260 }
261 }
262
263 if providerConfigs := list.Filter("provider"); len(providerConfigs.Items) > 0 {
264 providerConfigs = providerConfigs.Children()
265 type ProviderBlock struct {
266 Version string
267 }
268
269 for _, item := range providerConfigs.Items {
270 unwrapLegacyHCLObjectKeysFromJSON(item, 1)
271
272 if len(item.Keys) != 1 {
273 return nil, diagnosticsErrorf("provider block at %s has no label", item.Pos())
274 }
275
276 name := item.Keys[0].Token.Value().(string)
277
278 var block ProviderBlock
279 err := legacyhcl.DecodeObject(&block, item.Val)
280 if err != nil {
281 return nil, diagnosticsErrorf("invalid provider block at %s: %s", item.Pos(), err)
282 }
283 // Even if there wasn't an explicit version required, we still
284 // need an entry in our map to signal the unversioned dependency.
285 if _, exists := mod.RequiredProviders[name]; !exists {
286 mod.RequiredProviders[name] = &ProviderRequirement{}
287 }
288
289 if block.Version != "" {
290 mod.RequiredProviders[name].VersionConstraints = append(mod.RequiredProviders[name].VersionConstraints, block.Version)
291 }
292 }
293 }
294 }
295
296 return mod, nil
297 }
298
299 // unwrapLegacyHCLObjectKeysFromJSON cleans up an edge case that can occur when
300 // parsing JSON as input: if we're parsing JSON then directly nested
301 // items will show up as additional "keys".
302 //
303 // For objects that expect a fixed number of keys, this breaks the
304 // decoding process. This function unwraps the object into what it would've
305 // looked like if it came directly from HCL by specifying the number of keys
306 // you expect.
307 //
308 // Example:
309 //
310 // { "foo": { "baz": {} } }
311 //
312 // Will show up with Keys being: []string{"foo", "baz"}
313 // when we really just want the first two. This function will fix this.
314 func unwrapLegacyHCLObjectKeysFromJSON(item *legacyast.ObjectItem, depth int) {
315 if len(item.Keys) > depth && item.Keys[0].Token.JSON {
316 for len(item.Keys) > depth {
317 // Pop off the last key
318 n := len(item.Keys)
319 key := item.Keys[n-1]
320 item.Keys[n-1] = nil
321 item.Keys = item.Keys[:n-1]
322
323 // Wrap our value in a list
324 item.Val = &legacyast.ObjectType{
325 List: &legacyast.ObjectList{
326 Items: []*legacyast.ObjectItem{
327 {
328 Keys: []*legacyast.ObjectKey{key},
329 Val: item.Val,
330 },
331 },
332 },
333 }
334 }
335 }
336 }