netherframe.generation 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- netherframe/generation/__init__.py +31 -0
- netherframe/generation/api.py +306 -0
- netherframe/generation/batch.py +65 -0
- netherframe/generation/convert/__init__.py +6 -0
- netherframe/generation/convert/bindings.py +180 -0
- netherframe/generation/convert/converter.py +365 -0
- netherframe/generation/convert/emitter.py +972 -0
- netherframe/generation/convert/expressions.py +701 -0
- netherframe/generation/convert/hcl_ast.py +721 -0
- netherframe/generation/convert/module_fetch.py +135 -0
- netherframe/generation/convert/module_source.py +200 -0
- netherframe/generation/convert/python_code.py +152 -0
- netherframe/generation/discovered_code.py +777 -0
- netherframe/generation/functions/__init__.py +8 -0
- netherframe/generation/functions/generator.py +369 -0
- netherframe/generation/import_specs.py +179 -0
- netherframe/generation/imports.py +169 -0
- netherframe/generation/nf_alias_shims.py +104 -0
- netherframe/generation/providers/__init__.py +1 -0
- netherframe/generation/providers/build_backend.py +90 -0
- netherframe/generation/providers/cli.py +274 -0
- netherframe/generation/providers/code_generator.py +2128 -0
- netherframe/generation/providers/codegen_support.py +542 -0
- netherframe/generation/providers/logging.py +22 -0
- netherframe/generation/providers/output_transaction.py +85 -0
- netherframe/generation/providers/package_output.py +440 -0
- netherframe/generation/providers/release.py +155 -0
- netherframe/generation/providers/schema_generation.py +220 -0
- netherframe/generation/providers/schema_loading.py +10 -0
- netherframe/generation/providers/schema_native.py +97 -0
- netherframe/generation/providers/schema_parser.py +563 -0
- netherframe/generation/py.typed +0 -0
- netherframe_generation-0.3.0.dist-info/METADATA +66 -0
- netherframe_generation-0.3.0.dist-info/RECORD +68 -0
- netherframe_generation-0.3.0.dist-info/WHEEL +4 -0
- netherframe_generation-0.3.0.dist-info/licenses/LICENSE +21 -0
- nf/generation/__init__.py +4 -0
- nf/generation/api.py +4 -0
- nf/generation/batch.py +4 -0
- nf/generation/convert/__init__.py +4 -0
- nf/generation/convert/bindings.py +4 -0
- nf/generation/convert/converter.py +4 -0
- nf/generation/convert/emitter.py +4 -0
- nf/generation/convert/expressions.py +4 -0
- nf/generation/convert/hcl_ast.py +4 -0
- nf/generation/convert/module_fetch.py +4 -0
- nf/generation/convert/module_source.py +4 -0
- nf/generation/convert/python_code.py +4 -0
- nf/generation/discovered_code.py +4 -0
- nf/generation/functions/__init__.py +4 -0
- nf/generation/functions/generator.py +4 -0
- nf/generation/import_specs.py +4 -0
- nf/generation/imports.py +4 -0
- nf/generation/nf_alias_shims.py +4 -0
- nf/generation/providers/__init__.py +4 -0
- nf/generation/providers/build_backend.py +4 -0
- nf/generation/providers/cli.py +4 -0
- nf/generation/providers/code_generator.py +4 -0
- nf/generation/providers/codegen_support.py +4 -0
- nf/generation/providers/logging.py +4 -0
- nf/generation/providers/output_transaction.py +4 -0
- nf/generation/providers/package_output.py +4 -0
- nf/generation/providers/release.py +4 -0
- nf/generation/providers/schema_generation.py +4 -0
- nf/generation/providers/schema_loading.py +4 -0
- nf/generation/providers/schema_native.py +4 -0
- nf/generation/providers/schema_parser.py +4 -0
- nf/generation/py.typed +0 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
"""Convert a Terraform module directory (and the local modules it calls) to a Python package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from netherframe.core.execution.adoption import adoption_manifest, format_adoption_manifest
|
|
12
|
+
from netherframe.generation.providers.package_output import ruff_command
|
|
13
|
+
|
|
14
|
+
from .bindings import BindingResolver
|
|
15
|
+
from .emitter import EmittedModule, ModuleEmitter, ModuleInfo
|
|
16
|
+
from .expressions import Todo
|
|
17
|
+
from .module_source import ModuleSource, is_local_source, load_module, module_source_text
|
|
18
|
+
from .python_code import Names, identifier, pascal
|
|
19
|
+
|
|
20
|
+
_SUPPORT_CODE = {
|
|
21
|
+
"module_provider": '''def module_provider[T: Provider](providers: dict[str, Provider | None], name: str, provider_type: type[T]) -> T | None:
|
|
22
|
+
"""Select a typed provider from a module's heterogeneous provider mapping."""
|
|
23
|
+
provider = providers.get(name)
|
|
24
|
+
if provider is not None and not isinstance(provider, provider_type):
|
|
25
|
+
raise TypeError(f"Module provider {name} must be a {provider_type.__name__}")
|
|
26
|
+
return provider
|
|
27
|
+
''',
|
|
28
|
+
"module_resources": '''def module_resources(module: Any, *, include_dependencies: bool = False) -> list[Resource]:
|
|
29
|
+
"""The resources of one converted module or its instances, including nested modules."""
|
|
30
|
+
instances = module.values() if isinstance(module, dict) else module if isinstance(module, (list, tuple)) else (module,)
|
|
31
|
+
result: list[Resource] = []
|
|
32
|
+
seen: set[int] = set()
|
|
33
|
+
for instance in instances:
|
|
34
|
+
members = [*instance._nf_resources, *(instance._nf_depends_on if include_dependencies else ())]
|
|
35
|
+
for resource in members:
|
|
36
|
+
if id(resource) not in seen:
|
|
37
|
+
seen.add(id(resource))
|
|
38
|
+
result.append(resource)
|
|
39
|
+
return result
|
|
40
|
+
''',
|
|
41
|
+
"add_module_dependencies": '''def add_module_dependencies(module: Any, dependencies: list[Resource]) -> None:
|
|
42
|
+
"""Apply module-level dependencies to its resources, retaining barriers for empty modules."""
|
|
43
|
+
module._nf_depends_on.extend(dependencies)
|
|
44
|
+
for resource in module_resources(module):
|
|
45
|
+
resource.depends_on = [*(resource.depends_on or ()), *dependencies]
|
|
46
|
+
''',
|
|
47
|
+
"tf_tostring": '''@overload
|
|
48
|
+
def tf_tostring(value: None) -> None: ...
|
|
49
|
+
|
|
50
|
+
@overload
|
|
51
|
+
def tf_tostring(value: str | int | float) -> str: ...
|
|
52
|
+
|
|
53
|
+
def tf_tostring(value: Any) -> str | None:
|
|
54
|
+
"""Terraform's scalar string conversion: lowercase booleans, null kept as null."""
|
|
55
|
+
if value is None or isinstance(value, str):
|
|
56
|
+
return value
|
|
57
|
+
if isinstance(value, bool):
|
|
58
|
+
return "true" if value else "false"
|
|
59
|
+
if isinstance(value, int):
|
|
60
|
+
return str(value)
|
|
61
|
+
if isinstance(value, float):
|
|
62
|
+
from decimal import Decimal
|
|
63
|
+
|
|
64
|
+
number = Decimal(str(value))
|
|
65
|
+
if number.is_finite():
|
|
66
|
+
text = format(number, "f")
|
|
67
|
+
return text.rstrip("0").rstrip(".") if "." in text else text
|
|
68
|
+
raise ValueError("tostring accepts only a string, finite number, bool or null")
|
|
69
|
+
''',
|
|
70
|
+
"each": '''def each(collection: Any) -> Any:
|
|
71
|
+
"""``for_each``'s pairs of a collection: a map's keys and values, a set's members twice."""
|
|
72
|
+
if isinstance(collection, dict):
|
|
73
|
+
return collection.items()
|
|
74
|
+
return ((member, member) for member in collection)
|
|
75
|
+
''',
|
|
76
|
+
"items": '''def items(collection: Any) -> Any:
|
|
77
|
+
"""A ``for`` expression's pairs of a collection: a map's keys and values, a list's indexes and elements."""
|
|
78
|
+
if isinstance(collection, dict):
|
|
79
|
+
return collection.items()
|
|
80
|
+
return enumerate(collection)
|
|
81
|
+
''',
|
|
82
|
+
"UnconvertedModule": '''class UnconvertedModule:
|
|
83
|
+
"""A module call `nf convert` did not convert: its source, version and arguments, to port it from.
|
|
84
|
+
|
|
85
|
+
Expressions that read its outputs were left as Terraform strings with TODO markers.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(self, name: str, *, source: str, version: str | None = None, inputs: dict[str, Any] | None = None) -> None:
|
|
89
|
+
self.name = name
|
|
90
|
+
self.source = source
|
|
91
|
+
self.version = version
|
|
92
|
+
self.inputs = inputs or {}
|
|
93
|
+
''',
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_COUNT_ORDER = ("variables", "locals", "providers", "resources", "data sources", "ephemeral resources", "module calls", "module calls (not converted)", "outputs")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ConversionError(Exception):
|
|
101
|
+
"""A module the converter cannot read."""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass
|
|
105
|
+
class ModuleReport:
|
|
106
|
+
rel: str
|
|
107
|
+
python_module: str
|
|
108
|
+
class_name: str
|
|
109
|
+
counts: dict[str, int]
|
|
110
|
+
typed: dict[str, int]
|
|
111
|
+
generic_types: set[str]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass
|
|
115
|
+
class ConversionResult:
|
|
116
|
+
"""What a conversion wrote and what it left as TODO markers."""
|
|
117
|
+
|
|
118
|
+
source: Path
|
|
119
|
+
output: Path
|
|
120
|
+
package: str
|
|
121
|
+
files: list[Path] = field(default_factory=list)
|
|
122
|
+
modules: list[ModuleReport] = field(default_factory=list)
|
|
123
|
+
todos: list[tuple[str, Todo]] = field(default_factory=list) # (module rel, todo)
|
|
124
|
+
formatted: bool = False
|
|
125
|
+
adoption_manifest: Path | None = None
|
|
126
|
+
|
|
127
|
+
def report(self) -> str:
|
|
128
|
+
"""A readable summary of what was converted and what was not."""
|
|
129
|
+
lines = [f"nf convert: Terraform module {self.source.name} -> Python package {self.package}", ""]
|
|
130
|
+
lines.append("Converted:")
|
|
131
|
+
for module in self.modules:
|
|
132
|
+
where = "root module" if module.rel == "." else f"module {module.rel}"
|
|
133
|
+
lines.append(f" {where} -> {self.package}.{module.python_module}.{module.class_name}")
|
|
134
|
+
ordered = sorted(module.counts.items(), key=lambda item: (_COUNT_ORDER.index(item[0]) if item[0] in _COUNT_ORDER else len(_COUNT_ORDER), item[0]))
|
|
135
|
+
lines.append(" " + (", ".join(f"{what}: {count}" for what, count in ordered) or "nothing to convert"))
|
|
136
|
+
typed, generic = module.typed["typed"], module.typed["generic"]
|
|
137
|
+
if typed or generic:
|
|
138
|
+
detail = f" constructs: {typed} typed (generated bindings), {generic} generic"
|
|
139
|
+
if module.generic_types:
|
|
140
|
+
detail += f" ({', '.join(sorted(module.generic_types))}: no generated binding installed)"
|
|
141
|
+
lines.append(detail)
|
|
142
|
+
if self.adoption_manifest is not None:
|
|
143
|
+
lines.extend(
|
|
144
|
+
[
|
|
145
|
+
"",
|
|
146
|
+
f"Adoption manifest: {self.adoption_manifest.name} (each resource's Terraform state address)",
|
|
147
|
+
f" adopt the module's objects: nf plan --adopt-from {self.adoption_manifest.name} --terraform-state terraform.tfstate",
|
|
148
|
+
],
|
|
149
|
+
)
|
|
150
|
+
lines.append("")
|
|
151
|
+
if not self.todos:
|
|
152
|
+
lines.append("TODO markers: none")
|
|
153
|
+
else:
|
|
154
|
+
lines.append(f"TODO markers ({len(self.todos)}):")
|
|
155
|
+
for rel, todo in self.todos:
|
|
156
|
+
where = f"{todo.file}:{todo.line}" if todo.file and todo.line else todo.file or "-"
|
|
157
|
+
if rel != ".":
|
|
158
|
+
where = f"{rel}/{where}"
|
|
159
|
+
lines.append(f" {where}: {todo.reason}")
|
|
160
|
+
return "\n".join(lines) + "\n"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _module_tree(root: Path, *, fetch_modules: bool = False, module_cache: Path | None = None) -> list[tuple[Path, ModuleSource]]:
|
|
164
|
+
"""The root module and every local module it calls, callers before the modules they call."""
|
|
165
|
+
sources: dict[Path, ModuleSource] = {}
|
|
166
|
+
calls: dict[Path, list[Path]] = {}
|
|
167
|
+
boundaries: dict[Path, Path] = {}
|
|
168
|
+
|
|
169
|
+
def visit(directory: Path) -> None:
|
|
170
|
+
if directory in sources:
|
|
171
|
+
return
|
|
172
|
+
module = load_module(directory)
|
|
173
|
+
sources[directory] = module
|
|
174
|
+
calls[directory] = []
|
|
175
|
+
for block in module.modules:
|
|
176
|
+
source = module_source_text(block) or ""
|
|
177
|
+
if is_local_source(source):
|
|
178
|
+
child = (directory / source).resolve()
|
|
179
|
+
if boundary := boundaries.get(directory):
|
|
180
|
+
if not child.is_relative_to(boundary):
|
|
181
|
+
raise ConversionError(f"Downloaded module {directory.name}: source {source} leaves its package")
|
|
182
|
+
boundaries[child] = boundary
|
|
183
|
+
elif fetch_modules:
|
|
184
|
+
from .module_fetch import ModuleFetchError, fetch_module
|
|
185
|
+
|
|
186
|
+
version = block.body.get("version")
|
|
187
|
+
from .hcl_ast import Literal
|
|
188
|
+
|
|
189
|
+
if version is not None and not isinstance(version, Literal):
|
|
190
|
+
raise ConversionError(f"Module {block.labels[0]} needs a literal version constraint")
|
|
191
|
+
try:
|
|
192
|
+
child = fetch_module(source, str(version.value) if version is not None else None, module_cache or Path.home() / ".cache" / "netherframe" / "modules")
|
|
193
|
+
except ModuleFetchError as error:
|
|
194
|
+
raise ConversionError(str(error)) from error
|
|
195
|
+
module.resolved_modules[block.labels[0]] = child
|
|
196
|
+
boundaries[child] = next(parent for parent in (child, *child.parents) if (parent / ".nf-complete").is_file())
|
|
197
|
+
else:
|
|
198
|
+
continue
|
|
199
|
+
if child.is_dir() and any(path.name.endswith((".tf", ".tf.json")) for path in child.iterdir()):
|
|
200
|
+
calls[directory].append(child)
|
|
201
|
+
visit(child)
|
|
202
|
+
|
|
203
|
+
visit(root)
|
|
204
|
+
# Callers first: a module's argument kinds come from every call to it
|
|
205
|
+
order: list[Path] = []
|
|
206
|
+
seen: set[Path] = set()
|
|
207
|
+
|
|
208
|
+
def post(directory: Path) -> None:
|
|
209
|
+
if directory in seen:
|
|
210
|
+
return
|
|
211
|
+
seen.add(directory)
|
|
212
|
+
for child in calls[directory]:
|
|
213
|
+
post(child)
|
|
214
|
+
order.append(directory)
|
|
215
|
+
|
|
216
|
+
post(root)
|
|
217
|
+
return [(directory, sources[directory]) for directory in reversed(order)]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def convert_module(
|
|
221
|
+
source: Path | str,
|
|
222
|
+
output: Path | str,
|
|
223
|
+
*,
|
|
224
|
+
package: str | None = None,
|
|
225
|
+
use_generated_bindings: bool = True,
|
|
226
|
+
format_code: bool = True,
|
|
227
|
+
clean: bool = False,
|
|
228
|
+
fetch_modules: bool = False,
|
|
229
|
+
module_cache: Path | None = None,
|
|
230
|
+
) -> ConversionResult:
|
|
231
|
+
"""Convert the Terraform module at ``source`` into the Python package ``output/<package>``.
|
|
232
|
+
|
|
233
|
+
Types of installed generated provider packages convert to their classes, others to generic
|
|
234
|
+
``Resource(nf_type=...)``. Returns what was written and the TODO markers left.
|
|
235
|
+
"""
|
|
236
|
+
root = Path(source).resolve()
|
|
237
|
+
if not root.is_dir():
|
|
238
|
+
raise ConversionError(f"{source} is not a directory")
|
|
239
|
+
if not any(path.name.endswith((".tf", ".tf.json")) for path in root.iterdir()):
|
|
240
|
+
raise ConversionError(f"{source} has no .tf or .tf.json files")
|
|
241
|
+
package_name = identifier(package or root.name).lower()
|
|
242
|
+
package_dir = Path(output).resolve() / package_name
|
|
243
|
+
if package_dir.exists() and any(package_dir.iterdir()):
|
|
244
|
+
if not clean:
|
|
245
|
+
raise ConversionError(f"{package_dir} exists; replace it with --force (clean=True)")
|
|
246
|
+
shutil.rmtree(package_dir)
|
|
247
|
+
|
|
248
|
+
tree = _module_tree(root, fetch_modules=fetch_modules, module_cache=module_cache)
|
|
249
|
+
class_names = Names({"Stack", "App", "UnconvertedModule"})
|
|
250
|
+
module_names = Names({"main", "_support", "__init__"})
|
|
251
|
+
infos: dict[Path, ModuleInfo] = {}
|
|
252
|
+
for directory, module in tree:
|
|
253
|
+
is_root = directory == root
|
|
254
|
+
rel = "." if is_root else Path(os.path.relpath(directory, root)).as_posix() if directory.is_relative_to(root) else f"downloaded/{directory.parent.name}/{directory.name}"
|
|
255
|
+
if is_root:
|
|
256
|
+
info = ModuleInfo(module, rel, "main", class_names.allocate(f"{pascal(package_name)}Stack"), True, default_id=package_name)
|
|
257
|
+
else:
|
|
258
|
+
stem = module_names.allocate(identifier(directory.name).lower())
|
|
259
|
+
info = ModuleInfo(module, rel, f"modules.{stem}", class_names.allocate(f"{pascal(directory.name)}Module"), False)
|
|
260
|
+
infos[directory] = info
|
|
261
|
+
|
|
262
|
+
resolver = BindingResolver(use_generated=use_generated_bindings)
|
|
263
|
+
result = ConversionResult(root, package_dir, package_name)
|
|
264
|
+
emitted: dict[Path, EmittedModule] = {}
|
|
265
|
+
helpers: set[str] = set()
|
|
266
|
+
# Callers first: a module's arguments decide its parameters' kinds. A module's outputs are
|
|
267
|
+
# attributes named when it is emitted, so outputs referenced before are named the same way.
|
|
268
|
+
for directory, module in tree:
|
|
269
|
+
info = infos[directory]
|
|
270
|
+
output_names = Names()
|
|
271
|
+
for block in module.outputs:
|
|
272
|
+
info.outputs.setdefault(block.labels[0], output_names.allocate(block.labels[0]))
|
|
273
|
+
for directory, _module in tree:
|
|
274
|
+
info = infos[directory]
|
|
275
|
+
emitted[directory] = ModuleEmitter(info, infos, resolver, inherited_sources=tree[0][1].required_providers()).emit()
|
|
276
|
+
helpers |= emitted[directory].helpers
|
|
277
|
+
|
|
278
|
+
package_dir.mkdir(parents=True, exist_ok=True)
|
|
279
|
+
written: list[Path] = []
|
|
280
|
+
root_info = infos[root]
|
|
281
|
+
for directory, _module in tree:
|
|
282
|
+
info = infos[directory]
|
|
283
|
+
module_emitted = emitted[directory]
|
|
284
|
+
path = package_dir / f"{info.python_module.replace('.', '/')}.py"
|
|
285
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
286
|
+
path.write_text(module_emitted.code)
|
|
287
|
+
written.append(path)
|
|
288
|
+
result.modules.append(ModuleReport(info.rel, info.python_module, info.class_name, module_emitted.counts, module_emitted.typed, module_emitted.generic_types))
|
|
289
|
+
result.todos.extend((info.rel, todo) for todo in module_emitted.todos)
|
|
290
|
+
if any(not info.is_root for info in infos.values()):
|
|
291
|
+
modules_init = package_dir / "modules" / "__init__.py"
|
|
292
|
+
modules_init.write_text('"""Local Terraform modules of the converted module."""\n')
|
|
293
|
+
written.append(modules_init)
|
|
294
|
+
if helpers:
|
|
295
|
+
support = package_dir / "_support.py"
|
|
296
|
+
typing_names = "Any, overload" if "tf_tostring" in helpers else "Any"
|
|
297
|
+
parts = ['"""Helpers of the converted modules (`nf convert`)."""', "", "from __future__ import annotations", "", f"from typing import {typing_names}", ""]
|
|
298
|
+
core_imports = set()
|
|
299
|
+
if helpers & {"module_resources", "add_module_dependencies"}:
|
|
300
|
+
core_imports.add("Resource")
|
|
301
|
+
if "module_provider" in helpers:
|
|
302
|
+
core_imports.add("Provider")
|
|
303
|
+
if core_imports:
|
|
304
|
+
parts.extend([f"from netherframe.core import {', '.join(sorted(core_imports))}", ""])
|
|
305
|
+
for name in sorted(helpers):
|
|
306
|
+
parts.extend(["", _SUPPORT_CODE[name]])
|
|
307
|
+
support.write_text("\n".join(parts).rstrip() + "\n")
|
|
308
|
+
written.append(support)
|
|
309
|
+
init = package_dir / "__init__.py"
|
|
310
|
+
init.write_text(
|
|
311
|
+
f'"""Netherframe conversion of the Terraform module {root.name} (`nf convert`)."""\n\nfrom .main import {root_info.class_name}\n\n__all__ = ["{root_info.class_name}"]\n',
|
|
312
|
+
)
|
|
313
|
+
written.append(init)
|
|
314
|
+
result.files = sorted(written)
|
|
315
|
+
if format_code:
|
|
316
|
+
result.formatted = format_files(result.files)
|
|
317
|
+
manifest = adoption_manifest_for(tree, infos, emitted, stack=root_info.default_id)
|
|
318
|
+
manifest_path = package_dir.parent / f"{package_name}.adopt.json"
|
|
319
|
+
manifest_path.write_text(format_adoption_manifest(manifest))
|
|
320
|
+
result.adoption_manifest = manifest_path
|
|
321
|
+
return result
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def adoption_manifest_for(tree: list[tuple[Path, ModuleSource]], infos: dict[Path, ModuleInfo], emitted: dict[Path, EmittedModule], *, stack: str) -> dict[str, object]:
|
|
325
|
+
"""The adoption manifest mapping each converted resource's Terraform state address to its netherframe address.
|
|
326
|
+
|
|
327
|
+
A resource converted from ``aws_instance.web`` keeps its name; one in a loop gets its instance
|
|
328
|
+
key (``web_{key}``), and one in a local module the call's name before it (``edge_web``): the
|
|
329
|
+
renames the conversion makes, as ``terraform_address`` entries (a pattern with ``[*]`` per
|
|
330
|
+
loop). ``nf plan --adopt-from <manifest> --terraform-state terraform.tfstate`` then shows every
|
|
331
|
+
object of the Terraform state as an import.
|
|
332
|
+
"""
|
|
333
|
+
directories = {id(info): directory for directory, info in infos.items()}
|
|
334
|
+
entries: dict[str, dict[str, str]] = {}
|
|
335
|
+
patterns: list[dict[str, str]] = []
|
|
336
|
+
|
|
337
|
+
def visit(directory: Path, terraform_prefix: str, name_prefix: str) -> None:
|
|
338
|
+
module = emitted[directory]
|
|
339
|
+
for terraform_relative, tf_type, nf_relative in module.adoptions:
|
|
340
|
+
terraform_address = terraform_prefix + terraform_relative
|
|
341
|
+
nf_id = name_prefix + nf_relative
|
|
342
|
+
# Each loop's key, in order: {0}, {1}...
|
|
343
|
+
parts = nf_id.split("{*}")
|
|
344
|
+
address = f"{stack}.{tf_type}." + "".join(part + (f"{{{index}}}" if index < len(parts) - 1 else "") for index, part in enumerate(parts))
|
|
345
|
+
if "[*]" in terraform_address:
|
|
346
|
+
patterns.append({"address": address, "terraform_address": terraform_address})
|
|
347
|
+
else:
|
|
348
|
+
entries[address] = {"terraform_address": terraform_address}
|
|
349
|
+
for call, looped, child in module.module_calls:
|
|
350
|
+
child_directory = directories.get(id(child))
|
|
351
|
+
if child_directory is not None:
|
|
352
|
+
visit(child_directory, f"{terraform_prefix}module.{call}{'[*]' if looped else ''}.", f"{name_prefix}{call}{'_{*}' if looped else ''}_")
|
|
353
|
+
|
|
354
|
+
visit(tree[0][0], "", "")
|
|
355
|
+
return adoption_manifest(entries, patterns=patterns)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def format_files(paths: list[Path]) -> bool:
|
|
359
|
+
"""Format files with Ruff, as provider generation does; False without Ruff or on failure."""
|
|
360
|
+
command = ruff_command()
|
|
361
|
+
try:
|
|
362
|
+
completed = subprocess.run([*command, "format", "--quiet", *map(str, paths)], capture_output=True, text=True, check=False)
|
|
363
|
+
except FileNotFoundError:
|
|
364
|
+
return False
|
|
365
|
+
return completed.returncode == 0
|