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.
Files changed (68) hide show
  1. netherframe/generation/__init__.py +31 -0
  2. netherframe/generation/api.py +306 -0
  3. netherframe/generation/batch.py +65 -0
  4. netherframe/generation/convert/__init__.py +6 -0
  5. netherframe/generation/convert/bindings.py +180 -0
  6. netherframe/generation/convert/converter.py +365 -0
  7. netherframe/generation/convert/emitter.py +972 -0
  8. netherframe/generation/convert/expressions.py +701 -0
  9. netherframe/generation/convert/hcl_ast.py +721 -0
  10. netherframe/generation/convert/module_fetch.py +135 -0
  11. netherframe/generation/convert/module_source.py +200 -0
  12. netherframe/generation/convert/python_code.py +152 -0
  13. netherframe/generation/discovered_code.py +777 -0
  14. netherframe/generation/functions/__init__.py +8 -0
  15. netherframe/generation/functions/generator.py +369 -0
  16. netherframe/generation/import_specs.py +179 -0
  17. netherframe/generation/imports.py +169 -0
  18. netherframe/generation/nf_alias_shims.py +104 -0
  19. netherframe/generation/providers/__init__.py +1 -0
  20. netherframe/generation/providers/build_backend.py +90 -0
  21. netherframe/generation/providers/cli.py +274 -0
  22. netherframe/generation/providers/code_generator.py +2128 -0
  23. netherframe/generation/providers/codegen_support.py +542 -0
  24. netherframe/generation/providers/logging.py +22 -0
  25. netherframe/generation/providers/output_transaction.py +85 -0
  26. netherframe/generation/providers/package_output.py +440 -0
  27. netherframe/generation/providers/release.py +155 -0
  28. netherframe/generation/providers/schema_generation.py +220 -0
  29. netherframe/generation/providers/schema_loading.py +10 -0
  30. netherframe/generation/providers/schema_native.py +97 -0
  31. netherframe/generation/providers/schema_parser.py +563 -0
  32. netherframe/generation/py.typed +0 -0
  33. netherframe_generation-0.3.0.dist-info/METADATA +66 -0
  34. netherframe_generation-0.3.0.dist-info/RECORD +68 -0
  35. netherframe_generation-0.3.0.dist-info/WHEEL +4 -0
  36. netherframe_generation-0.3.0.dist-info/licenses/LICENSE +21 -0
  37. nf/generation/__init__.py +4 -0
  38. nf/generation/api.py +4 -0
  39. nf/generation/batch.py +4 -0
  40. nf/generation/convert/__init__.py +4 -0
  41. nf/generation/convert/bindings.py +4 -0
  42. nf/generation/convert/converter.py +4 -0
  43. nf/generation/convert/emitter.py +4 -0
  44. nf/generation/convert/expressions.py +4 -0
  45. nf/generation/convert/hcl_ast.py +4 -0
  46. nf/generation/convert/module_fetch.py +4 -0
  47. nf/generation/convert/module_source.py +4 -0
  48. nf/generation/convert/python_code.py +4 -0
  49. nf/generation/discovered_code.py +4 -0
  50. nf/generation/functions/__init__.py +4 -0
  51. nf/generation/functions/generator.py +4 -0
  52. nf/generation/import_specs.py +4 -0
  53. nf/generation/imports.py +4 -0
  54. nf/generation/nf_alias_shims.py +4 -0
  55. nf/generation/providers/__init__.py +4 -0
  56. nf/generation/providers/build_backend.py +4 -0
  57. nf/generation/providers/cli.py +4 -0
  58. nf/generation/providers/code_generator.py +4 -0
  59. nf/generation/providers/codegen_support.py +4 -0
  60. nf/generation/providers/logging.py +4 -0
  61. nf/generation/providers/output_transaction.py +4 -0
  62. nf/generation/providers/package_output.py +4 -0
  63. nf/generation/providers/release.py +4 -0
  64. nf/generation/providers/schema_generation.py +4 -0
  65. nf/generation/providers/schema_loading.py +4 -0
  66. nf/generation/providers/schema_native.py +4 -0
  67. nf/generation/providers/schema_parser.py +4 -0
  68. nf/generation/py.typed +0 -0
@@ -0,0 +1,777 @@
1
+ """Python source from discovered infrastructure.
2
+
3
+ A discoverer finds existing objects and the provider imports them, so their state is exactly what
4
+ the provider would hold after ``terraform import``. This module turns that state into readable
5
+ Netherframe code: each object becomes one construct call with an explicit ``nf_id``, arguments
6
+ are the configurable attributes that differ from what the provider or server would choose anyway,
7
+ references to other emitted objects replace raw IDs, and secrets become inputs instead of literals.
8
+
9
+ It is provider-agnostic. A provider-specific layer (such as the Keycloak codifier) decides which
10
+ objects to emit, names them, and rewrites values into :class:`Reference` and :class:`SecretInput`;
11
+ this module reduces state with the provider schema (:func:`configurable_arguments`), renders the
12
+ module (:func:`render_module`) and formats it with Ruff (:func:`format_source`).
13
+
14
+ Constructs use the generated typed bindings when they are installed (:class:`BindingCatalog`) and
15
+ the generic ``Resource``/``DataSource`` classes otherwise; the rendered code is the same otherwise.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ import binascii
22
+ import importlib
23
+ import importlib.util
24
+ import json
25
+ import keyword
26
+ import re
27
+ import subprocess
28
+ import sys
29
+ from dataclasses import dataclass, field
30
+ from typing import TYPE_CHECKING, Any, Literal
31
+
32
+ from netherframe.core.execution.adoption import adoption_manifest as core_adoption_manifest
33
+ from netherframe.core.execution.adoption import format_adoption_manifest # noqa: F401 - written beside generated code, as callers import it from here
34
+ from netherframe.generation.providers.codegen_support import CONSTRUCT_KINDS, provider_class_name, python_segment, resource_type_prefixes, safe_name
35
+
36
+ if TYPE_CHECKING:
37
+ from collections.abc import Iterable, Mapping
38
+
39
+ MISSING: Any = object()
40
+ """No known default for an attribute (distinct from a default of ``None``)."""
41
+
42
+ DEFAULT_LINE_LENGTH = 100
43
+
44
+
45
+ # --------------------------------------------------------------------------------------------
46
+ # Values a provider-specific layer puts into arguments
47
+ # --------------------------------------------------------------------------------------------
48
+
49
+
50
+ @dataclass(frozen=True, order=True)
51
+ class Reference:
52
+ """An attribute of another emitted construct, rendered as ``<variable>.output.<attribute>``."""
53
+
54
+ target: str
55
+ """The :attr:`CodeObject.key` of the construct referred to."""
56
+ attribute: str
57
+
58
+
59
+ @dataclass(frozen=True, order=True)
60
+ class SecretInput:
61
+ """A secret the code takes as input instead of holding it: rendered ``secrets.<field>``."""
62
+
63
+ field: str
64
+ """Field of the generated secrets class (a Python identifier)."""
65
+ env_var: str
66
+ """Environment variable the secrets class reads it from."""
67
+ description: str
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class Expression:
72
+ """Python source rendered verbatim (a parameter name, say)."""
73
+
74
+ code: str
75
+
76
+
77
+ @dataclass
78
+ class CodeObject:
79
+ """One construct to emit."""
80
+
81
+ key: str
82
+ """Unique key other objects refer to it by (its type and import ID, say)."""
83
+ resource_type: str
84
+ nf_id: str
85
+ arguments: dict[str, Any]
86
+ kind: Literal["resource", "data_source"] = "resource"
87
+ import_id: str | None = None
88
+ """The provider's import ID of the existing object, for the adoption manifest (:func:`adoption_manifest`)."""
89
+ section: str = ""
90
+ """Heading the object is grouped under."""
91
+ comment: str | None = None
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class StackParameter:
96
+ """A keyword parameter of the generated stack."""
97
+
98
+ name: str
99
+ annotation: str
100
+ default: Any = MISSING
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class ProviderSpec:
105
+ """The provider configuration the generated stack declares."""
106
+
107
+ source: str
108
+ """``keycloak/keycloak``."""
109
+ nf_id: str
110
+ arguments: dict[str, Any]
111
+ version: str | None = None
112
+
113
+ @property
114
+ def local_name(self) -> str:
115
+ return self.source.rsplit("/", 1)[-1]
116
+
117
+
118
+ @dataclass
119
+ class ModuleSpec:
120
+ """Everything :func:`render_module` writes into one module."""
121
+
122
+ docstring: str
123
+ stack_class: str
124
+ stack_nf_id: str
125
+ app_nf_id: str
126
+ provider: ProviderSpec
127
+ objects: list[CodeObject]
128
+ secrets_class: str
129
+ secrets: list[SecretInput] = field(default_factory=list)
130
+ parameters: list[StackParameter] = field(default_factory=list)
131
+ stack_docstring: str = ""
132
+
133
+
134
+ # --------------------------------------------------------------------------------------------
135
+ # Provider schema views
136
+ # --------------------------------------------------------------------------------------------
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class AttributeSchema:
141
+ name: str
142
+ type: Any
143
+ required: bool = False
144
+ optional: bool = False
145
+ computed: bool = False
146
+ sensitive: bool = False
147
+ write_only: bool = False
148
+
149
+ @property
150
+ def configurable(self) -> bool:
151
+ return self.required or self.optional
152
+
153
+ @property
154
+ def is_set(self) -> bool:
155
+ return isinstance(self.type, list) and len(self.type) == 2 and self.type[0] == "set"
156
+
157
+
158
+ @dataclass(frozen=True)
159
+ class NestedBlockSchema:
160
+ name: str
161
+ nesting: str
162
+ """``single``, ``list``, ``set``, ``map`` or ``group``."""
163
+ block: BlockSchema
164
+ max_items: int = 0
165
+
166
+
167
+ @dataclass(frozen=True)
168
+ class BlockSchema:
169
+ attributes: dict[str, AttributeSchema]
170
+ blocks: dict[str, NestedBlockSchema]
171
+
172
+ def names(self) -> list[str]:
173
+ """Attribute and block names, required ones first, then in schema (alphabetical) order."""
174
+ required = [name for name, attribute in self.attributes.items() if attribute.required]
175
+ rest = sorted(name for name in [*self.attributes, *self.blocks] if name not in required)
176
+ return [*required, *rest]
177
+
178
+
179
+ _NESTING_NAMES = {0: "invalid", 1: "single", 2: "list", 3: "set", 4: "map", 5: "group"}
180
+
181
+
182
+ def _decode_type(raw: Any) -> Any:
183
+ """An attribute type from a schema: native schemas hold base64 JSON, CLI schemas JSON values."""
184
+ if isinstance(raw, str):
185
+ try:
186
+ return json.loads(base64.b64decode(raw, validate=True))
187
+ except binascii.Error, ValueError:
188
+ return raw
189
+ return raw
190
+
191
+
192
+ def parse_block(raw: Mapping[str, Any]) -> BlockSchema:
193
+ """A block schema from either the native form (``get_schema()``) or the CLI JSON form."""
194
+ raw_attributes = raw.get("attributes") or []
195
+ items = raw_attributes.items() if isinstance(raw_attributes, dict) else ((attribute.get("name"), attribute) for attribute in raw_attributes)
196
+ attributes = {
197
+ str(name): AttributeSchema(
198
+ name=str(name),
199
+ type=_decode_type(attribute.get("type")),
200
+ required=bool(attribute.get("required")),
201
+ optional=bool(attribute.get("optional")),
202
+ computed=bool(attribute.get("computed")),
203
+ sensitive=bool(attribute.get("sensitive")),
204
+ write_only=bool(attribute.get("write_only")),
205
+ )
206
+ for name, attribute in items
207
+ if name
208
+ }
209
+ raw_blocks = raw.get("block_types") or []
210
+ block_items = raw_blocks.items() if isinstance(raw_blocks, dict) else ((block.get("type_name"), block) for block in raw_blocks)
211
+ blocks = {}
212
+ for name, nested in block_items:
213
+ if not name:
214
+ continue
215
+ nesting = nested.get("nesting") or nested.get("nesting_mode") or "list"
216
+ nesting = _NESTING_NAMES.get(nesting, str(nesting)) if isinstance(nesting, int) else str(nesting).lower()
217
+ blocks[str(name)] = NestedBlockSchema(name=str(name), nesting=nesting, block=parse_block(nested.get("block") or {}), max_items=int(nested.get("max_items") or 0))
218
+ return BlockSchema(attributes=attributes, blocks=blocks)
219
+
220
+
221
+ class ProviderSchema:
222
+ """A provider's resource and data source schemas, parsed on first use."""
223
+
224
+ def __init__(self, raw: Mapping[str, Any]) -> None:
225
+ self._raw = raw
226
+ self._cache: dict[tuple[str, str], BlockSchema] = {}
227
+
228
+ def _block(self, section: str, type_name: str) -> BlockSchema:
229
+ key = (section, type_name)
230
+ if key not in self._cache:
231
+ entry = (self._raw.get(section) or self._raw.get(f"{section.removesuffix('s')}_schemas") or {}).get(type_name)
232
+ if entry is None:
233
+ raise KeyError(f"the provider schema has no {section.removesuffix('s').replace('_', ' ')} {type_name}")
234
+ self._cache[key] = parse_block(entry.get("block") or {})
235
+ return self._cache[key]
236
+
237
+ def resource(self, type_name: str) -> BlockSchema:
238
+ return self._block("resources", type_name)
239
+
240
+ def data_source(self, type_name: str) -> BlockSchema:
241
+ return self._block("data_sources", type_name)
242
+
243
+ def has_resource(self, type_name: str) -> bool:
244
+ return type_name in (self._raw.get("resources") or {})
245
+
246
+
247
+ # --------------------------------------------------------------------------------------------
248
+ # State reduction
249
+ # --------------------------------------------------------------------------------------------
250
+
251
+
252
+ def is_zero(value: Any) -> bool:
253
+ """Whether a value is its type's zero value, which providers built on the legacy SDK store for unset arguments."""
254
+ return value is None or value is False or value == "" or (isinstance(value, (int, float)) and not isinstance(value, bool) and value == 0) or (isinstance(value, (list, dict, tuple)) and not value)
255
+
256
+
257
+ def _normalized(value: Any, attribute: AttributeSchema | None = None) -> Any:
258
+ """A value in a canonical order, so sets compare (and render) the same whatever order state held."""
259
+ if isinstance(value, list) and attribute is not None and attribute.is_set:
260
+ return sorted(value, key=lambda item: json.dumps(item, sort_keys=True, default=str))
261
+ return value
262
+
263
+
264
+ def same_value(left: Any, right: Any, attribute: AttributeSchema | None = None) -> bool:
265
+ if isinstance(left, list) and isinstance(right, list) and attribute is not None and attribute.is_set:
266
+ return _normalized(left, attribute) == _normalized(right, attribute)
267
+ return left == right
268
+
269
+
270
+ @dataclass
271
+ class ReducedState:
272
+ """The arguments that reproduce an object's state, and the sensitive values left out of them."""
273
+
274
+ arguments: dict[str, Any]
275
+ sensitive: dict[str, Any]
276
+
277
+
278
+ def configurable_arguments(
279
+ state: Mapping[str, Any],
280
+ block: BlockSchema,
281
+ *,
282
+ defaults: Mapping[str, Any] | None = None,
283
+ created_defaults: Mapping[str, Any] | None = None,
284
+ skip: Iterable[str] = (),
285
+ ) -> ReducedState:
286
+ """The arguments to write for an imported object, in :meth:`BlockSchema.names` order.
287
+
288
+ - Computed-only and write-only attributes, and those in ``skip``, are left out.
289
+ - Required attributes are always written.
290
+ - An optional attribute is left out when its value is the one an object gets when the argument
291
+ is unset: its ``created_defaults`` entry (what an object created with only its required
292
+ arguments reads back with: the server's choice for optional and computed attributes), else
293
+ its ``defaults`` entry (what the provider plans for it, from a create plan), else when it
294
+ is its type's zero value, which legacy-SDK providers store for unset arguments.
295
+ - A null value is left out, except an optional and computed collection, written empty: unset,
296
+ the provider would plan it unknown, and every plan would update the object.
297
+ - A block is left out when empty or equal to its ``created_defaults`` entry; inside, null
298
+ values, and zero values of optional arguments, are left out.
299
+ - Sensitive values with something in them go to :attr:`ReducedState.sensitive`, never into
300
+ the arguments: the caller decides what the code takes instead.
301
+ """
302
+ defaults = defaults or {}
303
+ created = created_defaults or {}
304
+ skipped = set(skip)
305
+ arguments: dict[str, Any] = {}
306
+ sensitive: dict[str, Any] = {}
307
+ for name in block.names():
308
+ if name in skipped or name not in state:
309
+ continue
310
+ value = state[name]
311
+ attribute = block.attributes.get(name)
312
+ if attribute is None:
313
+ nested = block.blocks[name]
314
+ if is_zero(value) or (name in created and value == created[name]):
315
+ continue
316
+ arguments[name] = _block_value(value, nested)
317
+ continue
318
+ if not attribute.configurable or attribute.write_only:
319
+ continue
320
+ if attribute.sensitive:
321
+ if not is_zero(value):
322
+ sensitive[name] = value
323
+ continue
324
+ if value is None:
325
+ # An optional and computed collection the provider stores as null plans as unknown
326
+ # when unset (so every plan would update it); empty, it plans as null again.
327
+ if attribute.optional and attribute.computed and (empty := _empty_collection(attribute.type)) is not None:
328
+ arguments[name] = empty
329
+ continue
330
+ if not attribute.required and _is_default(value, attribute, defaults, created):
331
+ continue
332
+ arguments[name] = _normalized(value, attribute)
333
+ return ReducedState(arguments=arguments, sensitive=sensitive)
334
+
335
+
336
+ def _is_default(value: Any, attribute: AttributeSchema, defaults: Mapping[str, Any], created_defaults: Mapping[str, Any]) -> bool:
337
+ known = created_defaults.get(attribute.name, MISSING)
338
+ if known is MISSING:
339
+ known = defaults.get(attribute.name, MISSING)
340
+ if known is not MISSING:
341
+ return same_value(value, known, attribute)
342
+ return is_zero(value)
343
+
344
+
345
+ def _empty_collection(type_: Any) -> list[Any] | dict[str, Any] | None:
346
+ if isinstance(type_, list) and type_:
347
+ if type_[0] in {"list", "set"}:
348
+ return []
349
+ if type_[0] == "map":
350
+ return {}
351
+ return None
352
+
353
+
354
+ def _block_value(value: Any, nested: NestedBlockSchema) -> Any:
355
+ def kept(name: str, item: Any) -> bool:
356
+ attribute = nested.block.attributes.get(name)
357
+ if item is None:
358
+ return False
359
+ return not (attribute is not None and not attribute.required and not attribute.computed and is_zero(item))
360
+
361
+ def element(item: Any) -> Any:
362
+ if not isinstance(item, dict):
363
+ return item
364
+ return {name: _normalized(item[name], nested.block.attributes.get(name)) for name in nested.block.names() if name in item and kept(name, item[name])}
365
+
366
+ if isinstance(value, list):
367
+ return [element(item) for item in value]
368
+ if isinstance(value, dict) and nested.nesting == "map":
369
+ return {key: element(item) for key, item in value.items()}
370
+ return element(value)
371
+
372
+
373
+ # --------------------------------------------------------------------------------------------
374
+ # Bindings
375
+ # --------------------------------------------------------------------------------------------
376
+
377
+
378
+ @dataclass(frozen=True)
379
+ class Binding:
380
+ """The generated class for one resource or data source type."""
381
+
382
+ module: str
383
+ class_name: str
384
+
385
+
386
+ class BindingCatalog:
387
+ """Which generated class to use for each type, if any.
388
+
389
+ Class names follow the provider generator: the type without its provider prefix, in
390
+ CamelCase, with a kind suffix for every kind but resources (``keycloak_openid_client`` ->
391
+ ``OpenidClient``, its data source ``OpenidClientDataSource``); keyword names are the
392
+ attribute names made safe (``id`` -> ``id_``).
393
+ """
394
+
395
+ def __init__(self, provider_source: str, module: str | None, available: Iterable[str] | None = None) -> None:
396
+ self.provider_source = provider_source
397
+ self.module = module
398
+ self._available = set(available) if available is not None else None
399
+
400
+ @classmethod
401
+ def generic(cls, provider_source: str) -> BindingCatalog:
402
+ """No generated classes: every construct is a generic ``Resource``/``DataSource``."""
403
+ return cls(provider_source, None)
404
+
405
+ @classmethod
406
+ def typed(cls, provider_source: str, module: str | None = None) -> BindingCatalog:
407
+ """The generated classes, whether installed or not (the code imports them)."""
408
+ return cls(provider_source, module or default_binding_module(provider_source))
409
+
410
+ @classmethod
411
+ def detect(cls, provider_source: str) -> BindingCatalog:
412
+ """The generated classes when their package is installed, else generic constructs."""
413
+ package = default_binding_module(provider_source).replace("nf.", "netherframe.", 1)
414
+ try:
415
+ spec = importlib.util.find_spec(package)
416
+ except ImportError, ValueError:
417
+ spec = None
418
+ if spec is None:
419
+ return cls.generic(provider_source)
420
+ try:
421
+ available = getattr(importlib.import_module(package), "__all__", None)
422
+ except Exception: # noqa: BLE001 - a broken package is as good as none
423
+ return cls.generic(provider_source)
424
+ return cls(provider_source, default_binding_module(provider_source), available)
425
+
426
+ @property
427
+ def is_typed(self) -> bool:
428
+ return self.module is not None
429
+
430
+ @property
431
+ def provider_class(self) -> str:
432
+ org, _, name = self.provider_source.rpartition("/")
433
+ return provider_class_name(name) if org or name else "Provider"
434
+
435
+ def lookup(self, type_name: str, kind: Literal["resource", "data_source"] = "resource") -> Binding | None:
436
+ if self.module is None:
437
+ return None
438
+ name = self.provider_source.rsplit("/", 1)[-1]
439
+ stem = type_name
440
+ for prefix in resource_type_prefixes(name):
441
+ if type_name.startswith(prefix):
442
+ stem = type_name.removeprefix(prefix)
443
+ break
444
+ if kind == "data_source":
445
+ stem = f"{stem}_data_source"
446
+ class_name = CONSTRUCT_KINDS[kind].class_name(stem)
447
+ if self._available is not None and class_name not in self._available:
448
+ return None
449
+ return Binding(self.module, class_name)
450
+
451
+
452
+ def default_binding_module(provider_source: str) -> str:
453
+ """``keycloak/keycloak`` -> ``nf.providers.keycloak.keycloak``."""
454
+ org, _, name = provider_source.rpartition("/")
455
+ return f"nf.providers.{python_segment(org or 'hashicorp')}.{python_segment(name)}"
456
+
457
+
458
+ # --------------------------------------------------------------------------------------------
459
+ # Rendering
460
+ # --------------------------------------------------------------------------------------------
461
+
462
+
463
+ _IDENTIFIER = re.compile(r"[^0-9a-zA-Z]+")
464
+
465
+
466
+ def identifier(text: str, *, fallback: str = "item") -> str:
467
+ """A readable snake_case Python identifier for ``text`` (``"Custom Browser"`` -> ``custom_browser``)."""
468
+ words = _IDENTIFIER.sub(" ", re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", text)).split()
469
+ name = "_".join(word.lower() for word in words) or fallback
470
+ if name[0].isdigit():
471
+ name = f"{fallback}_{name}"
472
+ if keyword.iskeyword(name) or keyword.issoftkeyword(name) or name in {"self", "secrets", "nf_scope", "nf_id"}:
473
+ name = f"{name}_"
474
+ return name
475
+
476
+
477
+ class _Renderer:
478
+ def __init__(self, spec: ModuleSpec, catalog: BindingCatalog) -> None:
479
+ self.spec = spec
480
+ self.catalog = catalog
481
+ self.objects = {obj.key: obj for obj in spec.objects}
482
+ self.referenced = self._referenced_keys()
483
+ self.uses_resource = False
484
+ self.uses_data_source = False
485
+ self.typed_names: set[str] = set()
486
+
487
+ def _referenced_keys(self) -> set[str]:
488
+ keys: set[str] = set()
489
+
490
+ def visit(value: Any) -> None:
491
+ if isinstance(value, Reference):
492
+ keys.add(value.target)
493
+ elif isinstance(value, dict):
494
+ for item in value.values():
495
+ visit(item)
496
+ elif isinstance(value, (list, tuple)):
497
+ for item in value:
498
+ visit(item)
499
+
500
+ for obj in self.spec.objects:
501
+ visit(obj.arguments)
502
+ return keys
503
+
504
+ def value(self, value: Any) -> str:
505
+ if isinstance(value, Reference):
506
+ target = self.objects.get(value.target)
507
+ if target is None:
508
+ raise ValueError(f"reference to {value.target}, which is not emitted")
509
+ return f"{target.nf_id}.output.{value.attribute}"
510
+ if isinstance(value, SecretInput):
511
+ return f"secrets.{value.field}"
512
+ if isinstance(value, Expression):
513
+ return value.code
514
+ if isinstance(value, dict):
515
+ return "{" + ", ".join(f"{self.value(key)}: {self.value(item)}" for key, item in value.items()) + "}"
516
+ if isinstance(value, (list, tuple)):
517
+ return "[" + ", ".join(self.value(item) for item in value) + "]"
518
+ if isinstance(value, float) and value.is_integer():
519
+ return repr(int(value))
520
+ return repr(value)
521
+
522
+ def keyword_arguments(self, arguments: Mapping[str, Any], *, typed: bool) -> list[str]:
523
+ rendered = []
524
+ unsafe: dict[str, Any] = {}
525
+ for name, value in arguments.items():
526
+ keyword_name = safe_name(name) if typed else name
527
+ if not keyword_name.isidentifier() or keyword.iskeyword(keyword_name):
528
+ unsafe[name] = value
529
+ continue
530
+ rendered.append(f"{keyword_name}={self.value(value)}")
531
+ if unsafe:
532
+ rendered.append("**" + self.value(unsafe))
533
+ return rendered
534
+
535
+ def construct(self, obj: CodeObject) -> list[str]:
536
+ binding = self.catalog.lookup(obj.resource_type, obj.kind)
537
+ head = ["nf_scope=self", f"nf_id={obj.nf_id!r}"]
538
+ if binding is None:
539
+ if obj.kind == "data_source":
540
+ self.uses_data_source = True
541
+ class_name = "DataSource"
542
+ else:
543
+ self.uses_resource = True
544
+ class_name = "Resource"
545
+ head.append(f"nf_type={obj.resource_type!r}")
546
+ else:
547
+ self.typed_names.add(binding.class_name)
548
+ class_name = binding.class_name
549
+ call = f"{class_name}({', '.join([*head, *self.keyword_arguments(obj.arguments, typed=binding is not None)])})"
550
+ lines = [f"# {line}" for line in (obj.comment or "").splitlines()]
551
+ lines.append(f"{obj.nf_id} = {call}" if obj.key in self.referenced else call)
552
+ return lines
553
+
554
+ def render(self) -> str:
555
+ spec = self.spec
556
+ body: list[str] = []
557
+ section = None
558
+ for obj in spec.objects:
559
+ if obj.section and obj.section != section:
560
+ section = obj.section
561
+ body.extend(["", f"# {section}"])
562
+ body.extend(self.construct(obj))
563
+
564
+ provider_class = self.catalog.provider_class
565
+ if self.catalog.is_typed:
566
+ self.typed_names.add(provider_class)
567
+ if spec.provider.version:
568
+ provider_class = "Codified" + provider_class
569
+ provider_call = f"{provider_class}({', '.join(['nf_scope=self', f'nf_id={spec.provider.nf_id!r}', *self.keyword_arguments(spec.provider.arguments, typed=self.catalog.is_typed)])})"
570
+
571
+ core_names = {"App", "Stack"}
572
+ if self.uses_resource:
573
+ core_names.add("Resource")
574
+ if self.uses_data_source:
575
+ core_names.add("DataSource")
576
+ if not self.catalog.is_typed:
577
+ core_names.add("Provider")
578
+
579
+ out: list[str] = [f'"""{spec.docstring.strip()}\n"""', "", "from __future__ import annotations", ""]
580
+ if spec.secrets:
581
+ out.extend(["import os", "from dataclasses import dataclass", ""])
582
+ out.append(f"from nf.core import {', '.join(sorted(core_names))}")
583
+ if self.catalog.is_typed and self.typed_names:
584
+ out.append(f"from {self.catalog.module} import {', '.join(sorted(self.typed_names))}")
585
+ out.extend(["", ""])
586
+
587
+ if not self.catalog.is_typed:
588
+ source = spec.provider.source
589
+ out.extend(
590
+ [
591
+ f"class {provider_class}(Provider):",
592
+ f' """The {source} provider (its generated bindings are not installed: constructs are generic)."""',
593
+ "",
594
+ f" _PROVIDER_TYPE = {spec.provider.local_name!r}",
595
+ f" _PROVIDER_SOURCE = {source!r}",
596
+ *([f" _PROVIDER_VERSION = {spec.provider.version!r}"] if spec.provider.version else []),
597
+ "",
598
+ "",
599
+ ],
600
+ )
601
+
602
+ elif spec.provider.version:
603
+ out.extend([f"class {provider_class}({self.catalog.provider_class}):", f" _PROVIDER_VERSION = {spec.provider.version!r}", "", ""])
604
+
605
+ out.extend(self._secrets_class())
606
+
607
+ parameters = ["*", "nf_scope: App"]
608
+ if spec.secrets:
609
+ parameters.append(f"secrets: {spec.secrets_class}")
610
+ parameters.append(f"nf_id: str = {spec.stack_nf_id!r}")
611
+ for parameter in spec.parameters:
612
+ default = "" if parameter.default is MISSING else f" = {self.value(parameter.default)}"
613
+ parameters.append(f"{parameter.name}: {parameter.annotation}{default}")
614
+ out.extend(
615
+ [
616
+ f"class {spec.stack_class}(Stack):",
617
+ f' """{(spec.stack_docstring or spec.stack_class).strip()}"""',
618
+ "",
619
+ f" def __init__(self, {', '.join(parameters)}) -> None:",
620
+ " super().__init__(nf_scope=nf_scope, nf_id=nf_id)",
621
+ f" {provider_call}",
622
+ ],
623
+ )
624
+ out.extend(f" {line}" if line else "" for line in body)
625
+ secrets_argument = f", secrets={spec.secrets_class}.from_env()" if spec.secrets else ""
626
+ out.extend(
627
+ [
628
+ "",
629
+ "",
630
+ "def build_app() -> App:",
631
+ f' """The app holding the stack{"; secrets are read from the environment" if spec.secrets else ""}."""',
632
+ f" app = App(nf_id={spec.app_nf_id!r})",
633
+ f" {spec.stack_class}(nf_scope=app{secrets_argument})",
634
+ " return app",
635
+ "",
636
+ ],
637
+ )
638
+ return "\n".join(out)
639
+
640
+ def _secrets_class(self) -> list[str]:
641
+ spec = self.spec
642
+ if not spec.secrets:
643
+ return []
644
+ lines = [
645
+ "@dataclass(frozen=True)",
646
+ f"class {spec.secrets_class}:",
647
+ ' """Secret values the code takes as input: discovery never writes them into code."""',
648
+ "",
649
+ ]
650
+ for secret in spec.secrets:
651
+ lines.append(f" {secret.field}: str")
652
+ lines.append(f' """{secret.description} (${secret.env_var})."""')
653
+ lines.extend(
654
+ [
655
+ "",
656
+ " @classmethod",
657
+ f" def from_env(cls) -> {spec.secrets_class}:",
658
+ ' """Read every secret from its environment variable."""',
659
+ " return cls(",
660
+ ],
661
+ )
662
+ lines.extend(f" {secret.field}=os.environ[{secret.env_var!r}]," for secret in spec.secrets)
663
+ lines.extend([" )", "", ""])
664
+ return lines
665
+
666
+
667
+ def render_module(spec: ModuleSpec, catalog: BindingCatalog, *, line_length: int = DEFAULT_LINE_LENGTH, format_code: bool = True) -> str:
668
+ """The module for ``spec``: a secrets class, a stack holding every object, and ``build_app()``.
669
+
670
+ Objects are emitted in ``spec.objects`` order, which must put every object after those it
671
+ refers to.
672
+ """
673
+ keys = set()
674
+ for obj in spec.objects:
675
+ _check_references(obj, keys)
676
+ keys.add(obj.key)
677
+ source = _Renderer(spec, catalog).render()
678
+ return format_source(source, line_length=line_length) if format_code else source
679
+
680
+
681
+ def adoption_manifest(spec: ModuleSpec) -> dict[str, Any]:
682
+ """The adoption manifest for ``spec``: the existing object each managed construct stands for, by import ID.
683
+
684
+ The code holds no import blocks; a hybrid plan given the manifest (``nf plan --adopt-from``,
685
+ see ``netherframe.core.execution.adoption``) shows each object as an ``import``. Addresses
686
+ are ``<stack>.<type>.<nf_id>`` in the stack ``spec.stack_nf_id``; the provider configuration
687
+ recorded leaves out expressions (except parameters with defaults) and holds no credentials.
688
+ """
689
+ defaults = {parameter.name: parameter.default for parameter in spec.parameters if parameter.default is not MISSING}
690
+ provider_config: dict[str, Any] = {}
691
+ for name, value in spec.provider.arguments.items():
692
+ if isinstance(value, Expression):
693
+ if value.code in defaults:
694
+ provider_config[name] = defaults[value.code]
695
+ elif not isinstance(value, (Reference, SecretInput)):
696
+ provider_config[name] = value
697
+ entries = {f"{spec.stack_nf_id}.{obj.resource_type}.{obj.nf_id}": {"import_id": obj.import_id} for obj in spec.objects if obj.kind == "resource" and obj.import_id is not None}
698
+ provider_metadata: dict[str, Any] = {"source": spec.provider.source, "config": dict(sorted(provider_config.items()))}
699
+ if spec.provider.version:
700
+ provider_metadata["version"] = spec.provider.version
701
+ return core_adoption_manifest(entries, provider=provider_metadata)
702
+
703
+
704
+ def _check_references(obj: CodeObject, emitted: set[str]) -> None:
705
+ def visit(value: Any) -> None:
706
+ if isinstance(value, Reference) and value.target not in emitted:
707
+ raise ValueError(f"{obj.key} refers to {value.target}, which is not emitted before it")
708
+ if isinstance(value, dict):
709
+ for item in value.values():
710
+ visit(item)
711
+ elif isinstance(value, (list, tuple)):
712
+ for item in value:
713
+ visit(item)
714
+
715
+ visit(obj.arguments)
716
+
717
+
718
+ def format_source(source: str, *, line_length: int = DEFAULT_LINE_LENGTH) -> str:
719
+ """``source`` formatted by Ruff with its default style (whatever configuration is around); unformatted without Ruff."""
720
+ command = [sys.executable, "-m", "ruff"] if importlib.util.find_spec("ruff") is not None else ["ruff"]
721
+ try:
722
+ result = subprocess.run([*command, "format", "--isolated", f"--line-length={line_length}", "-"], input=source, capture_output=True, text=True, check=False) # noqa: S603
723
+ except OSError:
724
+ return source
725
+ if result.returncode != 0:
726
+ raise ValueError(f"the generated code does not parse: {result.stderr.strip()}")
727
+ return result.stdout
728
+
729
+
730
+ def order_objects(objects: Iterable[CodeObject], *, section_order: Mapping[str, int] | None = None) -> list[CodeObject]:
731
+ """``objects`` with each after those it refers to; otherwise by section, then as given.
732
+
733
+ Raises ValueError on a reference cycle (the provider layer must break it, as Terraform
734
+ providers do with separate binding resources).
735
+ """
736
+ items = list(objects)
737
+ by_key = {obj.key: obj for obj in items}
738
+ rank = section_order or {}
739
+ position = {obj.key: (rank.get(obj.section, len(rank)), index) for index, obj in enumerate(items)}
740
+
741
+ def targets(value: Any) -> set[str]:
742
+ if isinstance(value, Reference):
743
+ return {value.target} if value.target in by_key else set()
744
+ if isinstance(value, dict):
745
+ return set().union(*(targets(item) for item in value.values())) if value else set()
746
+ if isinstance(value, (list, tuple)):
747
+ return set().union(*(targets(item) for item in value)) if value else set()
748
+ return set()
749
+
750
+ dependencies = {obj.key: targets(obj.arguments) - {obj.key} for obj in items}
751
+
752
+ # An object goes no earlier than the sections of what it refers to, so a section is not
753
+ # split by an object waiting for a later one.
754
+ effective: dict[str, tuple[int, int]] = {}
755
+
756
+ def rank_of(key: str, seen: frozenset[str] = frozenset()) -> tuple[int, int]:
757
+ if key not in effective:
758
+ if key in seen:
759
+ raise ValueError(f"reference cycle through {key}")
760
+ section_rank = max([position[key][0], *(rank_of(dependency, seen | {key})[0] for dependency in dependencies[key])])
761
+ effective[key] = (section_rank, position[key][1])
762
+ return effective[key]
763
+
764
+ ordered: list[CodeObject] = []
765
+ done: set[str] = set()
766
+ remaining = sorted(by_key, key=rank_of)
767
+ while remaining:
768
+ ready = [key for key in remaining if dependencies[key] <= done]
769
+ if not ready:
770
+ cycle = ", ".join(remaining[:5])
771
+ raise ValueError(f"reference cycle among {cycle}")
772
+ # The first ready object in the preferred order, so sections stay together where they can
773
+ key = ready[0]
774
+ ordered.append(by_key[key])
775
+ done.add(key)
776
+ remaining.remove(key)
777
+ return ordered