netherframe.cli 0.2.1__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 (92) hide show
  1. netherframe/cli/__init__.py +1 -0
  2. netherframe/cli/__main__.py +4 -0
  3. netherframe/cli/commands/__init__.py +93 -0
  4. netherframe/cli/commands/backend.py +305 -0
  5. netherframe/cli/commands/config_command.py +98 -0
  6. netherframe/cli/commands/convert.py +40 -0
  7. netherframe/cli/commands/discover.py +679 -0
  8. netherframe/cli/commands/drift.py +499 -0
  9. netherframe/cli/commands/encode.py +130 -0
  10. netherframe/cli/commands/generation.py +861 -0
  11. netherframe/cli/commands/graph_state.py +439 -0
  12. netherframe/cli/commands/hybrid.py +461 -0
  13. netherframe/cli/commands/idiff.py +493 -0
  14. netherframe/cli/commands/infrastructure.py +1182 -0
  15. netherframe/cli/commands/init_command.py +11 -0
  16. netherframe/cli/commands/lint.py +49 -0
  17. netherframe/cli/commands/providers.py +315 -0
  18. netherframe/cli/commands/shell_command.py +17 -0
  19. netherframe/cli/commands/skill.py +167 -0
  20. netherframe/cli/commands/synthesis.py +732 -0
  21. netherframe/cli/commands/terraform_command.py +17 -0
  22. netherframe/cli/commands/watch_command.py +117 -0
  23. netherframe/cli/entrypoint.py +18 -0
  24. netherframe/cli/logging.py +33 -0
  25. netherframe/cli/main.py +177 -0
  26. netherframe/cli/options.py +32 -0
  27. netherframe/cli/py.typed +0 -0
  28. netherframe/cli/services/__init__.py +1 -0
  29. netherframe/cli/services/app_loader.py +62 -0
  30. netherframe/cli/services/app_resolver.py +205 -0
  31. netherframe/cli/services/graph_onboarding.py +144 -0
  32. netherframe/cli/services/legacy_cli.py +51 -0
  33. netherframe/cli/services/project_config.py +107 -0
  34. netherframe/cli/services/provider_batch.py +620 -0
  35. netherframe/cli/services/stack_inventory.py +342 -0
  36. netherframe/cli/skills/netherframe/SKILL.md +53 -0
  37. netherframe/cli/skills/netherframe/agents/openai.yaml +3 -0
  38. netherframe/cli/skills/netherframe/references/authoring.md +77 -0
  39. netherframe/cli/skills/netherframe/references/execution.md +70 -0
  40. netherframe/cli/skills/netherframe/references/migration.md +69 -0
  41. netherframe/cli/state_migration.py +111 -0
  42. netherframe/cli/tui/__init__.py +1 -0
  43. netherframe/cli/tui/plan_filters.py +200 -0
  44. netherframe/cli/tui/plan_models.py +51 -0
  45. netherframe/cli/tui/plan_viewer.py +745 -0
  46. netherframe/cli/ui.py +25 -0
  47. netherframe_cli-0.2.1.dist-info/METADATA +86 -0
  48. netherframe_cli-0.2.1.dist-info/RECORD +92 -0
  49. netherframe_cli-0.2.1.dist-info/WHEEL +4 -0
  50. netherframe_cli-0.2.1.dist-info/entry_points.txt +3 -0
  51. netherframe_cli-0.2.1.dist-info/licenses/LICENSE +21 -0
  52. nf/cli/__init__.py +4 -0
  53. nf/cli/__main__.py +4 -0
  54. nf/cli/commands/__init__.py +4 -0
  55. nf/cli/commands/backend.py +4 -0
  56. nf/cli/commands/config_command.py +4 -0
  57. nf/cli/commands/convert.py +4 -0
  58. nf/cli/commands/discover.py +4 -0
  59. nf/cli/commands/drift.py +4 -0
  60. nf/cli/commands/encode.py +4 -0
  61. nf/cli/commands/generation.py +4 -0
  62. nf/cli/commands/graph_state.py +4 -0
  63. nf/cli/commands/hybrid.py +4 -0
  64. nf/cli/commands/idiff.py +4 -0
  65. nf/cli/commands/infrastructure.py +4 -0
  66. nf/cli/commands/init_command.py +4 -0
  67. nf/cli/commands/lint.py +4 -0
  68. nf/cli/commands/providers.py +4 -0
  69. nf/cli/commands/shell_command.py +4 -0
  70. nf/cli/commands/skill.py +4 -0
  71. nf/cli/commands/synthesis.py +4 -0
  72. nf/cli/commands/terraform_command.py +4 -0
  73. nf/cli/commands/watch_command.py +4 -0
  74. nf/cli/entrypoint.py +4 -0
  75. nf/cli/logging.py +4 -0
  76. nf/cli/main.py +4 -0
  77. nf/cli/options.py +4 -0
  78. nf/cli/py.typed +0 -0
  79. nf/cli/services/__init__.py +4 -0
  80. nf/cli/services/app_loader.py +4 -0
  81. nf/cli/services/app_resolver.py +4 -0
  82. nf/cli/services/graph_onboarding.py +4 -0
  83. nf/cli/services/legacy_cli.py +4 -0
  84. nf/cli/services/project_config.py +4 -0
  85. nf/cli/services/provider_batch.py +4 -0
  86. nf/cli/services/stack_inventory.py +4 -0
  87. nf/cli/state_migration.py +4 -0
  88. nf/cli/tui/__init__.py +4 -0
  89. nf/cli/tui/plan_filters.py +4 -0
  90. nf/cli/tui/plan_models.py +4 -0
  91. nf/cli/tui/plan_viewer.py +4 -0
  92. nf/cli/ui.py +4 -0
@@ -0,0 +1,1182 @@
1
+ """Infrastructure management commands for the NF CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ import sys
7
+ from collections.abc import Generator
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+ from typing import Any, cast
11
+
12
+ import click
13
+ from netherframe.cli.ui import console
14
+ from netherframe.cli.services.project_config import load_project_config
15
+ from netherframe.core.config import get_legacy_binary
16
+ from netherframe.cli.services.legacy_cli import run_legacy_cli_command
17
+ from netherframe.cli.services.stack_inventory import (
18
+ app_has_export_only_stacks,
19
+ discover_stacks,
20
+ discover_synthesized_apps,
21
+ find_stack_directory,
22
+ get_stack_name,
23
+ has_legacy_phased_artifacts,
24
+ list_available_stacks,
25
+ print_no_stacks_message,
26
+ )
27
+
28
+ from .hybrid import (
29
+ baseline_option,
30
+ deferred_options,
31
+ graph_plan_scope_option,
32
+ prefer_mine_option,
33
+ print_plan_counts,
34
+ print_provenance_report,
35
+ print_result_errors,
36
+ provenance_option,
37
+ parallelism_options,
38
+ planning_options,
39
+ set_execution_overrides,
40
+ )
41
+
42
+ run_terraform_command = run_legacy_cli_command
43
+
44
+
45
+ @contextmanager
46
+ def _direct_execution_errors(action: str) -> Generator[None]:
47
+ """Report direct-execution failures (e.g. unsupported hybrid features) as CLI errors."""
48
+ try:
49
+ yield
50
+ except click.ClickException, click.exceptions.Exit, SystemExit:
51
+ raise
52
+ except Exception as e:
53
+ console.print(f"[bold red]Error {action}: {e}[/bold red]")
54
+ raise click.ClickException(str(e)) from e
55
+
56
+
57
+ def _single_direct_app(targets: list[str], option: str) -> str:
58
+ if len(targets) != 1:
59
+ raise click.ClickException(f"{option} needs exactly one app; select it with --app.")
60
+ return targets[0]
61
+
62
+
63
+ def _reject_phased_stack_dir(stack_dir: Path, *, command_name: str) -> None:
64
+ """Fail closed when a stack directory only contains phased Terraform artifacts."""
65
+ if not has_legacy_phased_artifacts(stack_dir):
66
+ return
67
+
68
+ stack_name = stack_dir.name
69
+ raise click.ClickException(
70
+ f"Stack '{stack_name}' uses legacy phased Terraform artifacts and is no longer runnable via 'nf {command_name} --stack'. Use app-scoped direct execution with '--app <configured-app>' instead.",
71
+ )
72
+
73
+
74
+ def _resolve_direct_app_targets(
75
+ app: str | None,
76
+ *,
77
+ terraform_args: tuple[str, ...] = (),
78
+ legacy_bin: str | None = None,
79
+ ) -> list[str]:
80
+ """Resolve whether a command should route to direct execution."""
81
+ try:
82
+ project_config = load_project_config(allow_empty_apps=True)
83
+ except click.ClickException:
84
+ if app is not None:
85
+ raise
86
+ return []
87
+
88
+ if app is None:
89
+ if not project_config.legacy_apps and project_config.hybrid_apps:
90
+ _reject_direct_passthrough(terraform_args, legacy_bin)
91
+ return list(project_config.hybrid_apps)
92
+ return []
93
+
94
+ if app in project_config.hybrid_apps:
95
+ _reject_direct_passthrough(terraform_args, legacy_bin)
96
+ return [app]
97
+
98
+ if app in project_config.legacy_apps:
99
+ if terraform_args:
100
+ raise click.ClickException(
101
+ "--app direct execution does not accept raw Terraform/OpenTofu arguments; use --stack for legacy passthrough commands.",
102
+ )
103
+ if legacy_bin is not None:
104
+ raise click.ClickException(
105
+ "--legacy-bin is only supported for legacy Terraform/OpenTofu subprocess execution. Use --stack to stay on that path.",
106
+ )
107
+ return [app]
108
+
109
+ raise click.ClickException(f"App '{app}' not found")
110
+
111
+
112
+ def _reject_direct_passthrough(terraform_args, legacy_bin):
113
+ if terraform_args:
114
+ raise click.ClickException("Direct execution does not accept raw Terraform/OpenTofu arguments; use the named nf options, or --stack for legacy passthrough commands.")
115
+ if legacy_bin is not None:
116
+ raise click.ClickException("--legacy-bin is only supported for legacy Terraform/OpenTofu subprocess execution.")
117
+
118
+
119
+ def _print_hybrid_target_header(
120
+ *,
121
+ index: int,
122
+ total: int,
123
+ app_name: str,
124
+ ) -> None:
125
+ """Print a per-app header when operating on multiple hybrid apps."""
126
+ if total > 1:
127
+ console.print(
128
+ f"\n[bold blue]Hybrid app {index}/{total}: {app_name}[/bold blue]",
129
+ )
130
+
131
+
132
+ def _resolve_direct_stack_target(
133
+ stack: str | None,
134
+ *,
135
+ app: str | None,
136
+ outdir: str | None,
137
+ terraform_args: tuple[str, ...] = (),
138
+ legacy_bin: str | None = None,
139
+ ) -> tuple[str, str, object] | None:
140
+ """Resolve a configured direct-execution app/stack target when possible."""
141
+ from .hybrid import get_direct_app_and_exec
142
+
143
+ if not stack or terraform_args or legacy_bin is not None:
144
+ return None
145
+ if Path(stack).exists():
146
+ return None
147
+
148
+ project_config = load_project_config(allow_empty_apps=True)
149
+ configured_apps = {**project_config.legacy_apps, **project_config.hybrid_apps}
150
+ if not configured_apps:
151
+ return None
152
+ if app is None:
153
+ selector_map, _, _ = discover_stacks(outdir)
154
+ if stack in selector_map:
155
+ return None
156
+
157
+ stack_selector = stack
158
+ app_selector = app
159
+ if "/" in stack:
160
+ selector_app, selector_stack = stack.split("/", 1)
161
+ if app is not None and selector_app != app:
162
+ raise click.ClickException(
163
+ f"--app {app!r} does not match stack selector {stack!r}.",
164
+ )
165
+ app_selector = selector_app
166
+ stack_selector = selector_stack
167
+
168
+ if app_selector is not None:
169
+ if app_selector not in configured_apps:
170
+ raise click.ClickException(f"App '{app_selector}' not found")
171
+ direct_exec = get_direct_app_and_exec(app_selector, outdir=outdir)
172
+ if stack_selector not in direct_exec.app._stacks:
173
+ available = ", ".join(sorted(direct_exec.app._stacks))
174
+ raise click.ClickException(
175
+ f"Stack '{stack_selector}' not found in app '{app_selector}'. Available stacks: {available}",
176
+ )
177
+ return app_selector, stack_selector, direct_exec
178
+
179
+ candidates: list[tuple[str, str, object]] = []
180
+ for selector in configured_apps:
181
+ direct_exec = get_direct_app_and_exec(selector, outdir=outdir)
182
+ if stack_selector in direct_exec.app._stacks:
183
+ candidates.append((selector, stack_selector, direct_exec))
184
+
185
+ if not candidates:
186
+ return None
187
+ if len(candidates) > 1:
188
+ options = ", ".join(f"{selector}/{stack_selector}" for selector, _, _ in candidates)
189
+ raise click.ClickException(
190
+ f"Stack name '{stack_selector}' is ambiguous across configured apps. Use one of: {options}",
191
+ )
192
+ return candidates[0]
193
+
194
+
195
+ def _adopting(direct_exec: Any, adoption: dict[str, Any] | None) -> Any:
196
+ """The direct execution with the run's adoption flags over the app's settings (``adoption_overrides``)."""
197
+ if adoption:
198
+ direct_exec.adoption_overrides.update(adoption)
199
+ return direct_exec
200
+
201
+
202
+ def _adoption_flags(
203
+ adopt_from: Path | None = None,
204
+ terraform_state: Path | None = None,
205
+ adopt_missing: str | None = None,
206
+ allow_duplicate_adoption: bool = False,
207
+ approve_imports: bool = False,
208
+ ) -> dict[str, Any]:
209
+ """The adoption settings the command's flags give (those given only)."""
210
+ flags: dict[str, Any] = {}
211
+ if adopt_from is not None:
212
+ flags["adopt_from"] = str(adopt_from)
213
+ if terraform_state is not None:
214
+ flags["adopt_terraform_state"] = str(terraform_state)
215
+ if adopt_missing is not None:
216
+ flags["adopt_missing"] = adopt_missing
217
+ if allow_duplicate_adoption:
218
+ flags["allow_duplicate_adoption"] = True
219
+ if approve_imports:
220
+ flags["approve_imports"] = True
221
+ return flags
222
+
223
+
224
+ def _run_direct_plan_targets(targets: list[str], outdir: str | None, adoption: dict[str, Any] | None = None) -> None:
225
+ """Run direct planning for one or more apps."""
226
+ from .hybrid import get_direct_app_and_exec
227
+
228
+ if len(targets) > 1:
229
+ console.print(
230
+ f"[dim]Planning {len(targets)} apps with direct execution in configuration order[/dim]",
231
+ )
232
+
233
+ for index, app_name in enumerate(targets, start=1):
234
+ _print_hybrid_target_header(index=index, total=len(targets), app_name=app_name)
235
+ direct_exec = _adopting(get_direct_app_and_exec(app_name, outdir=outdir), adoption)
236
+ print_plan_counts(direct_exec.plan())
237
+
238
+
239
+ def _run_direct_plan_artifact(app_name: str, *, outdir: str | None, plan_out: Path, adoption: dict[str, Any] | None = None) -> None:
240
+ """Plan one app with direct execution and save the immutable plan artifact."""
241
+ from .hybrid import get_direct_app_and_exec, print_plan_summary
242
+
243
+ direct_exec = _adopting(get_direct_app_and_exec(app_name, outdir=outdir), adoption)
244
+ artifact = direct_exec.create_plan_artifact()
245
+ saved_path = direct_exec.save_plan_artifact(plan_out, artifact)
246
+ console.print(f"[dim]Saved plan artifact to {saved_path}[/dim]\n")
247
+ print_plan_summary(artifact.to_summary())
248
+ print_provenance_report(direct_exec.provenance_report)
249
+
250
+
251
+ def _run_direct_apply_plan_file(app_name: str, *, outdir: str | None, plan_file: Path, auto_approve: bool, adoption: dict[str, Any] | None = None) -> None:
252
+ """Apply a saved plan artifact for one app."""
253
+ from .hybrid import exit_if_incomplete, get_direct_app_and_exec, incomplete_exit_code
254
+
255
+ direct_exec = _adopting(get_direct_app_and_exec(app_name, outdir=outdir), adoption)
256
+ artifact = direct_exec.load_plan_artifact(plan_file)
257
+ result = direct_exec.apply(auto_approve=auto_approve, plan=artifact)
258
+ if not result.success:
259
+ console.print(f"[bold red]Apply failed or was cancelled for '{app_name}'[/bold red]")
260
+ print_result_errors(result)
261
+ sys.exit(1)
262
+ exit_if_incomplete(incomplete_exit_code(result, direct_exec))
263
+
264
+
265
+ def _run_direct_plan_stack(
266
+ *,
267
+ app_name: str,
268
+ stack_name: str,
269
+ direct_exec: object,
270
+ adoption: dict[str, Any] | None = None,
271
+ ) -> None:
272
+ """Run direct planning for a single stack in a configured app."""
273
+ console.print(f"[dim]Planning stack {app_name}/{stack_name} with direct execution[/dim]")
274
+ direct_exec_any = _adopting(cast("Any", direct_exec), adoption)
275
+ print_plan_counts(direct_exec_any.plan_stack(stack_name))
276
+
277
+
278
+ def _run_direct_apply_targets(
279
+ targets: list[str],
280
+ *,
281
+ outdir: str | None,
282
+ auto_approve: bool,
283
+ adoption: dict[str, Any] | None = None,
284
+ ) -> None:
285
+ """Run direct apply for one or more apps."""
286
+ from .hybrid import exit_if_incomplete, get_direct_app_and_exec, incomplete_exit_code
287
+
288
+ if len(targets) > 1:
289
+ console.print(
290
+ f"[dim]Applying {len(targets)} apps with direct execution in configuration order[/dim]",
291
+ )
292
+ code = 0
293
+
294
+ for index, app_name in enumerate(targets, start=1):
295
+ _print_hybrid_target_header(index=index, total=len(targets), app_name=app_name)
296
+ direct_exec = _adopting(get_direct_app_and_exec(app_name, outdir=outdir), adoption)
297
+ result = direct_exec.apply(auto_approve=auto_approve)
298
+ if not result.success:
299
+ console.print(
300
+ f"[bold red]Apply failed or was cancelled for '{app_name}'[/bold red]",
301
+ )
302
+ print_result_errors(result)
303
+ sys.exit(1)
304
+ code = code or incomplete_exit_code(result, direct_exec)
305
+ exit_if_incomplete(code)
306
+
307
+
308
+ def _run_direct_apply_stack(
309
+ *,
310
+ app_name: str,
311
+ stack_name: str,
312
+ direct_exec: object,
313
+ auto_approve: bool,
314
+ adoption: dict[str, Any] | None = None,
315
+ ) -> None:
316
+ """Run direct apply for a single stack in a configured app."""
317
+ console.print(f"[dim]Applying stack {app_name}/{stack_name} with direct execution[/dim]")
318
+ from .hybrid import exit_if_incomplete, incomplete_exit_code
319
+
320
+ direct_exec_any = _adopting(cast("Any", direct_exec), adoption)
321
+ result = direct_exec_any.apply_stack(stack_name, auto_approve=auto_approve)
322
+ if not result.success:
323
+ console.print(
324
+ f"[bold red]Apply failed or was cancelled for '{app_name}/{stack_name}'[/bold red]",
325
+ )
326
+ print_result_errors(result)
327
+ sys.exit(1)
328
+ exit_if_incomplete(incomplete_exit_code(result, direct_exec))
329
+
330
+
331
+ def _run_direct_destroy_targets(
332
+ targets: list[str],
333
+ *,
334
+ outdir: str | None,
335
+ auto_approve: bool,
336
+ ) -> None:
337
+ """Run direct destroy for one or more apps."""
338
+ from .hybrid import get_direct_app_and_exec
339
+
340
+ if len(targets) > 1:
341
+ console.print(
342
+ f"[dim]Destroying {len(targets)} apps with direct execution in configuration order[/dim]",
343
+ )
344
+
345
+ for index, app_name in enumerate(targets, start=1):
346
+ _print_hybrid_target_header(index=index, total=len(targets), app_name=app_name)
347
+ direct_exec = get_direct_app_and_exec(app_name, outdir=outdir)
348
+ result = direct_exec.destroy(auto_approve=auto_approve)
349
+ if not result.success:
350
+ console.print(f"[bold yellow]Destroy failed or was cancelled for '{app_name}'[/bold yellow]")
351
+ print_result_errors(result)
352
+ sys.exit(1)
353
+
354
+
355
+ def _run_direct_destroy_stack(
356
+ *,
357
+ app_name: str,
358
+ stack_name: str,
359
+ direct_exec: object,
360
+ auto_approve: bool,
361
+ ) -> None:
362
+ """Run direct destroy for a single stack in a configured app."""
363
+ console.print(
364
+ f"[dim]Destroying stack {app_name}/{stack_name} with direct execution[/dim]",
365
+ )
366
+ direct_exec_any = cast("Any", direct_exec)
367
+ result = direct_exec_any.destroy_stack(stack_name, auto_approve=auto_approve)
368
+ if not result.success:
369
+ console.print(
370
+ f"[bold yellow]Destroy failed or was cancelled for '{app_name}/{stack_name}'[/bold yellow]",
371
+ )
372
+ print_result_errors(result)
373
+ sys.exit(1)
374
+
375
+
376
+ # Common options for stack commands
377
+ stack_option = click.option(
378
+ "--stack",
379
+ "-s",
380
+ help="Stack name (or app/stack when names are ambiguous)",
381
+ )
382
+ app_option = click.option(
383
+ "--app",
384
+ help="Specific app to operate on. For hybrid apps this selects the app directly.",
385
+ )
386
+ legacy_bin_option = click.option(
387
+ "--legacy-bin",
388
+ help="Path to legacy CLI binary",
389
+ )
390
+ outdir_option = click.option(
391
+ "--outdir",
392
+ type=click.Path(),
393
+ help="Synthesis output directory (overrides auto-detection)",
394
+ )
395
+
396
+
397
+ def adoption_options(func: Any) -> Any:
398
+ """The flags of adopting existing objects (hybrid apps): see netherframe.core.execution.adoption."""
399
+ func = click.option(
400
+ "--allow-duplicate-adoption",
401
+ is_flag=True,
402
+ help="Adopt an object state already holds under another address (default off; NF_ALLOW_DUPLICATE_ADOPTION)",
403
+ )(func)
404
+ func = click.option(
405
+ "--adopt-missing",
406
+ type=click.Choice(["create", "error"]),
407
+ help="When an object to adopt is not found: create it, or fail the plan (default create; NF_ADOPT_MISSING)",
408
+ )(func)
409
+ func = click.option(
410
+ "--terraform-state",
411
+ "adopt_terraform_state",
412
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
413
+ help="Terraform state the adoption manifest's terraform_address entries come from (NF_ADOPT_TERRAFORM_STATE)",
414
+ )(func)
415
+ return click.option(
416
+ "--adopt-from",
417
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
418
+ help="Adoption manifest: existing objects the plan imports instead of creating (NF_ADOPT_FROM)",
419
+ )(func)
420
+
421
+
422
+ @click.command()
423
+ @stack_option
424
+ @legacy_bin_option
425
+ @outdir_option
426
+ @click.argument("terraform_args", nargs=-1)
427
+ def init(
428
+ stack: str | None,
429
+ legacy_bin: str | None,
430
+ outdir: str | None,
431
+ terraform_args: tuple[str, ...],
432
+ ) -> None:
433
+ """Initialize a stack."""
434
+ stack_name = get_stack_name(stack, outdir)
435
+ stack_dir = find_stack_directory(stack_name, outdir)
436
+ _reject_phased_stack_dir(stack_dir, command_name="init")
437
+ exit_code = run_terraform_command(
438
+ stack_dir,
439
+ ["init"] + list(terraform_args),
440
+ legacy_bin=legacy_bin,
441
+ )
442
+ sys.exit(exit_code)
443
+
444
+
445
+ @click.command()
446
+ @app_option
447
+ @stack_option
448
+ @legacy_bin_option
449
+ @outdir_option
450
+ @click.option(
451
+ "--out",
452
+ "plan_out",
453
+ type=click.Path(dir_okay=False, path_type=Path),
454
+ help="Save an immutable plan artifact to apply later with 'nf apply --plan-file' (direct execution, one app)",
455
+ )
456
+ @adoption_options
457
+ @provenance_option
458
+ @baseline_option
459
+ @prefer_mine_option
460
+ @graph_plan_scope_option
461
+ @parallelism_options
462
+ @planning_options
463
+ @click.argument("terraform_args", nargs=-1)
464
+ def plan(
465
+ app: str | None,
466
+ stack: str | None,
467
+ legacy_bin: str | None,
468
+ outdir: str | None,
469
+ plan_out: Path | None,
470
+ adopt_from: Path | None,
471
+ adopt_terraform_state: Path | None,
472
+ adopt_missing: str | None,
473
+ allow_duplicate_adoption: bool,
474
+ terraform_args: tuple[str, ...],
475
+ provenance_report: bool | None = None,
476
+ graph_plan_scope: str | None = None,
477
+ baseline: str | None = None,
478
+ prefer_mine: tuple[str, ...] = (),
479
+ parallelism: int | None = None,
480
+ read_parallelism: int | None = None,
481
+ quiet: bool | None = None,
482
+ refresh: bool | None = None,
483
+ targets: tuple[str, ...] = (),
484
+ plan_scope: str | None = None,
485
+ ) -> None:
486
+ """Generate and show an execution plan for a stack or app.
487
+
488
+ For hybrid apps, --adopt-from FILE names existing objects (an adoption manifest, as
489
+ `nf convert` and `nf discover codify` write) the plan imports instead of creating;
490
+ --terraform-state names the Terraform state its terraform_address entries come from.
491
+ """
492
+ set_execution_overrides(
493
+ refresh=refresh,
494
+ targets=targets or None,
495
+ plan_scope=plan_scope,
496
+ quiet=quiet,
497
+ parallelism=parallelism,
498
+ read_parallelism=read_parallelism,
499
+ provenance_report=provenance_report,
500
+ graph_plan_scope=graph_plan_scope,
501
+ baseline=baseline,
502
+ prefer_mine=prefer_mine or None,
503
+ )
504
+ adoption = _adoption_flags(adopt_from, adopt_terraform_state, adopt_missing, allow_duplicate_adoption)
505
+ direct_stack_target = _resolve_direct_stack_target(
506
+ stack,
507
+ app=app,
508
+ outdir=outdir,
509
+ terraform_args=terraform_args,
510
+ legacy_bin=legacy_bin,
511
+ )
512
+ if direct_stack_target is not None:
513
+ if plan_out is not None:
514
+ raise click.ClickException("--out saves whole-app plans; select the app with --app instead of --stack.")
515
+ app_name, stack_name, direct_exec = direct_stack_target
516
+ with _direct_execution_errors("creating plan"):
517
+ _run_direct_plan_stack(
518
+ app_name=app_name,
519
+ stack_name=stack_name,
520
+ direct_exec=direct_exec,
521
+ adoption=adoption,
522
+ )
523
+ return
524
+
525
+ direct_targets = _resolve_direct_app_targets(
526
+ app,
527
+ terraform_args=terraform_args,
528
+ legacy_bin=legacy_bin,
529
+ )
530
+ if direct_targets:
531
+ if stack:
532
+ raise click.ClickException(
533
+ "--stack is not currently supported for app-scoped direct plan; select the app as a whole.",
534
+ )
535
+ with _direct_execution_errors("creating plan"):
536
+ if plan_out is not None:
537
+ _run_direct_plan_artifact(_single_direct_app(direct_targets, "--out"), outdir=outdir, plan_out=plan_out, adoption=adoption)
538
+ else:
539
+ _run_direct_plan_targets(direct_targets, outdir, adoption)
540
+ return
541
+
542
+ if plan_out is not None:
543
+ raise click.ClickException("--out is only supported for apps using direct execution.")
544
+ if graph_plan_scope == "affected":
545
+ raise click.ClickException("--graph-plan-scope affected requires a hybrid app with graph state")
546
+ if adoption:
547
+ raise click.ClickException("Adoption flags (--adopt-from, --terraform-state, ...) are for apps using direct execution; Terraform plans import blocks itself.")
548
+ if parallelism is not None:
549
+ terraform_args = (*terraform_args, f"-parallelism={parallelism}")
550
+ if read_parallelism is not None:
551
+ raise click.ClickException("--read-parallelism requires a direct-execution app")
552
+ stack_name = get_stack_name(stack, outdir)
553
+ stack_dir = find_stack_directory(stack_name, outdir)
554
+ _reject_phased_stack_dir(stack_dir, command_name="plan")
555
+ if plan_scope is not None and plan_scope != "full":
556
+ raise click.ClickException("--plan-scope changed requires direct execution")
557
+ terraform_args = (*terraform_args, *([f"-refresh={str(refresh).lower()}"] if refresh is not None else []), *(f"-target={key}" for key in targets))
558
+ exit_code = run_terraform_command(
559
+ stack_dir,
560
+ ["plan"] + list(terraform_args),
561
+ legacy_bin=legacy_bin,
562
+ )
563
+ sys.exit(exit_code)
564
+
565
+
566
+ @click.command()
567
+ @app_option
568
+ @stack_option
569
+ @legacy_bin_option
570
+ @outdir_option
571
+ @click.option("--auto-approve", is_flag=True, help="Skip interactive approval")
572
+ @click.option(
573
+ "--plan-file",
574
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
575
+ help="Apply a plan artifact saved with 'nf plan --out' (direct execution, one app)",
576
+ )
577
+ @deferred_options
578
+ @adoption_options
579
+ @click.option(
580
+ "--approve-imports",
581
+ is_flag=True,
582
+ help="Let --auto-approve approve the plan's imports of existing objects too (default off; NF_APPROVE_IMPORTS)",
583
+ )
584
+ @click.argument("terraform_args", nargs=-1)
585
+ def apply(
586
+ app: str | None,
587
+ stack: str | None,
588
+ legacy_bin: str | None,
589
+ outdir: str | None,
590
+ auto_approve: bool,
591
+ plan_file: Path | None,
592
+ adopt_from: Path | None,
593
+ adopt_terraform_state: Path | None,
594
+ adopt_missing: str | None,
595
+ allow_duplicate_adoption: bool,
596
+ approve_imports: bool,
597
+ terraform_args: tuple[str, ...],
598
+ apply_deferred: bool | None = None,
599
+ concurrent_applies: bool | None = None,
600
+ graph_plan_scope: str | None = None,
601
+ deferred_approval: str | None = None,
602
+ incomplete_exit_code: int | None = None,
603
+ provider_data_sources: str | None = None,
604
+ deleted_objects: str | None = None,
605
+ provenance_report: bool | None = None,
606
+ baseline: str | None = None,
607
+ prefer_mine: tuple[str, ...] = (),
608
+ parallelism: int | None = None,
609
+ read_parallelism: int | None = None,
610
+ quiet: bool | None = None,
611
+ refresh: bool | None = None,
612
+ targets: tuple[str, ...] = (),
613
+ plan_scope: str | None = None,
614
+ ) -> None:
615
+ """Build or change infrastructure for a stack or app.
616
+
617
+ For hybrid apps, a plan importing existing objects (adoption) is applied with --auto-approve
618
+ only with --approve-imports too.
619
+ """
620
+ if plan_file is not None and (baseline is not None or prefer_mine or refresh is not None or targets or plan_scope is not None):
621
+ raise click.ClickException("A saved plan already records its baseline and conflict resolutions; replan to change them.")
622
+ set_execution_overrides(
623
+ refresh=refresh,
624
+ targets=targets or None,
625
+ plan_scope=plan_scope,
626
+ quiet=quiet,
627
+ parallelism=parallelism,
628
+ read_parallelism=read_parallelism,
629
+ apply_deferred=apply_deferred,
630
+ concurrent_applies=concurrent_applies,
631
+ graph_plan_scope=graph_plan_scope,
632
+ deferred_approval=deferred_approval,
633
+ incomplete_exit_code=incomplete_exit_code,
634
+ provider_data_sources=provider_data_sources,
635
+ deleted_objects=deleted_objects,
636
+ provenance_report=provenance_report,
637
+ baseline=baseline,
638
+ prefer_mine=prefer_mine or None,
639
+ )
640
+ adoption = _adoption_flags(adopt_from, adopt_terraform_state, adopt_missing, allow_duplicate_adoption, approve_imports)
641
+ direct_stack_target = _resolve_direct_stack_target(
642
+ stack,
643
+ app=app,
644
+ outdir=outdir,
645
+ terraform_args=terraform_args,
646
+ legacy_bin=legacy_bin,
647
+ )
648
+ if direct_stack_target is not None:
649
+ if plan_file is not None:
650
+ raise click.ClickException("--plan-file applies whole-app plans; select the app with --app instead of --stack.")
651
+ app_name, stack_name, direct_exec = direct_stack_target
652
+ with _direct_execution_errors("applying changes"):
653
+ _run_direct_apply_stack(
654
+ app_name=app_name,
655
+ stack_name=stack_name,
656
+ direct_exec=direct_exec,
657
+ auto_approve=auto_approve,
658
+ adoption=adoption,
659
+ )
660
+ return
661
+
662
+ direct_targets = _resolve_direct_app_targets(
663
+ app,
664
+ terraform_args=terraform_args,
665
+ legacy_bin=legacy_bin,
666
+ )
667
+ if direct_targets:
668
+ if stack:
669
+ raise click.ClickException(
670
+ "--stack is not currently supported for app-scoped direct apply; select the app as a whole.",
671
+ )
672
+ with _direct_execution_errors("applying changes"):
673
+ if plan_file is not None:
674
+ _run_direct_apply_plan_file(
675
+ _single_direct_app(direct_targets, "--plan-file"),
676
+ outdir=outdir,
677
+ plan_file=plan_file,
678
+ auto_approve=auto_approve,
679
+ adoption=adoption,
680
+ )
681
+ else:
682
+ _run_direct_apply_targets(
683
+ direct_targets,
684
+ outdir=outdir,
685
+ auto_approve=auto_approve,
686
+ adoption=adoption,
687
+ )
688
+ return
689
+
690
+ if plan_file is not None:
691
+ raise click.ClickException("--plan-file is only supported for apps using direct execution.")
692
+ if concurrent_applies:
693
+ raise click.ClickException("--concurrent-applies requires a hybrid app with graph state")
694
+ if graph_plan_scope == "affected":
695
+ raise click.ClickException("--graph-plan-scope affected requires a hybrid app with graph state")
696
+ if adoption:
697
+ raise click.ClickException("Adoption flags (--adopt-from, --terraform-state, --approve-imports, ...) are for apps using direct execution; Terraform applies import blocks itself.")
698
+ if parallelism is not None:
699
+ terraform_args = (*terraform_args, f"-parallelism={parallelism}")
700
+ if read_parallelism is not None:
701
+ raise click.ClickException("--read-parallelism requires a direct-execution app")
702
+ stack_name = get_stack_name(stack, outdir)
703
+ stack_dir = find_stack_directory(stack_name, outdir)
704
+ _reject_phased_stack_dir(stack_dir, command_name="apply")
705
+ if plan_scope is not None and plan_scope != "full":
706
+ raise click.ClickException("--plan-scope changed requires direct execution")
707
+ terraform_args = (*terraform_args, *([f"-refresh={str(refresh).lower()}"] if refresh is not None else []), *(f"-target={key}" for key in targets))
708
+ exit_code = run_terraform_command(
709
+ stack_dir,
710
+ ["apply"] + list(terraform_args),
711
+ auto_approve=auto_approve,
712
+ legacy_bin=legacy_bin,
713
+ )
714
+ sys.exit(exit_code)
715
+
716
+
717
+ @click.command()
718
+ @app_option
719
+ @stack_option
720
+ @legacy_bin_option
721
+ @outdir_option
722
+ @click.option("--auto-approve", is_flag=True, help="Skip interactive approval")
723
+ @click.argument("terraform_args", nargs=-1)
724
+ def destroy(
725
+ app: str | None,
726
+ stack: str | None,
727
+ legacy_bin: str | None,
728
+ outdir: str | None,
729
+ auto_approve: bool,
730
+ terraform_args: tuple[str, ...],
731
+ ) -> None:
732
+ """Destroy infrastructure for a stack or app."""
733
+ direct_stack_target = _resolve_direct_stack_target(
734
+ stack,
735
+ app=app,
736
+ outdir=outdir,
737
+ terraform_args=terraform_args,
738
+ legacy_bin=legacy_bin,
739
+ )
740
+ if direct_stack_target is not None:
741
+ app_name, stack_name, direct_exec = direct_stack_target
742
+ with _direct_execution_errors("destroying infrastructure"):
743
+ _run_direct_destroy_stack(
744
+ app_name=app_name,
745
+ stack_name=stack_name,
746
+ direct_exec=direct_exec,
747
+ auto_approve=auto_approve,
748
+ )
749
+ return
750
+
751
+ direct_targets = _resolve_direct_app_targets(
752
+ app,
753
+ terraform_args=terraform_args,
754
+ legacy_bin=legacy_bin,
755
+ )
756
+ if direct_targets:
757
+ if stack:
758
+ raise click.ClickException(
759
+ "--stack is not currently supported for app-scoped direct destroy; select the app as a whole.",
760
+ )
761
+ with _direct_execution_errors("destroying infrastructure"):
762
+ _run_direct_destroy_targets(
763
+ direct_targets,
764
+ outdir=outdir,
765
+ auto_approve=auto_approve,
766
+ )
767
+ return
768
+
769
+ stack_name = get_stack_name(stack, outdir)
770
+ stack_dir = find_stack_directory(stack_name, outdir)
771
+ _reject_phased_stack_dir(stack_dir, command_name="destroy")
772
+ exit_code = run_terraform_command(
773
+ stack_dir,
774
+ ["destroy"] + list(terraform_args),
775
+ auto_approve=auto_approve,
776
+ legacy_bin=legacy_bin,
777
+ )
778
+ sys.exit(exit_code)
779
+
780
+
781
+ @click.command()
782
+ @stack_option
783
+ @legacy_bin_option
784
+ @outdir_option
785
+ @click.argument("terraform_args", nargs=-1)
786
+ def output(
787
+ stack: str | None,
788
+ legacy_bin: str | None,
789
+ outdir: str | None,
790
+ terraform_args: tuple[str, ...],
791
+ ) -> None:
792
+ """Show output values from a stack."""
793
+ stack_name = get_stack_name(stack, outdir)
794
+ stack_dir = find_stack_directory(stack_name, outdir)
795
+ _reject_phased_stack_dir(stack_dir, command_name="output")
796
+ exit_code = run_terraform_command(
797
+ stack_dir,
798
+ ["output"] + list(terraform_args),
799
+ legacy_bin=legacy_bin,
800
+ )
801
+ sys.exit(exit_code)
802
+
803
+
804
+ def _set_tainted_direct_app(app: str | None, *, outdir: str | None, address: str, tainted: bool) -> bool:
805
+ """Taint or untaint the object at ``address`` in a hybrid app's state; False when the project has no hybrid app to route to."""
806
+ from .hybrid import get_direct_app_and_exec
807
+
808
+ command = "taint" if tainted else "untaint"
809
+ targets = _resolve_direct_app_targets(app)
810
+ if not targets:
811
+ return False
812
+ app_name = _single_direct_app(targets, f"nf state {command}")
813
+ direct_exec = get_direct_app_and_exec(app_name, outdir=outdir)
814
+ with _direct_execution_errors(f"{command}ing {address}"):
815
+ changed = direct_exec.taint_resource(address) if tainted else direct_exec.untaint_resource(address)
816
+ if not changed:
817
+ console.print(f"{address} is {'already' if tainted else 'not'} tainted.")
818
+ elif tainted:
819
+ console.print(f"[green]Tainted {address}: the next plan replaces it.[/green]")
820
+ else:
821
+ console.print(f"[green]Untainted {address}: the next plan keeps it.[/green]")
822
+ return True
823
+
824
+
825
+ def _force_unlock_direct_app(app: str | None, *, outdir: str | None, lock_id: str) -> bool:
826
+ """Release a hybrid app's state lock ``lock_id``; False when the project has no hybrid app to route to."""
827
+ from .hybrid import get_direct_app_and_exec
828
+
829
+ targets = _resolve_direct_app_targets(app)
830
+ if not targets:
831
+ return False
832
+ app_name = _single_direct_app(targets, "nf state force-unlock")
833
+ direct_exec = get_direct_app_and_exec(app_name, outdir=outdir)
834
+ with _direct_execution_errors("releasing the state lock"):
835
+ direct_exec.state_engine.force_unlock(lock_id)
836
+ console.print(f"[green]Released state lock {lock_id} of '{app_name}'.[/green]")
837
+ return True
838
+
839
+
840
+ def _graph_state_direct_app(app: str | None, *, outdir: str | None, args: tuple[str, ...]) -> None:
841
+ """Run a graph state subcommand (``recover``, ``history``, ``show --at``...) against a hybrid app's graph state backend."""
842
+ from .graph_state import parse_at, run_graph_state_command, show_at
843
+ from .hybrid import get_direct_app_and_exec
844
+
845
+ targets = _resolve_direct_app_targets(app)
846
+ if not targets:
847
+ raise click.ClickException(f"nf state {args[0]} needs a hybrid app stored in a graph state backend")
848
+ app_name = _single_direct_app(targets, f"nf state {args[0]}")
849
+ direct_exec = get_direct_app_and_exec(app_name, outdir=outdir)
850
+ with _direct_execution_errors(f"running nf state {args[0]}"):
851
+ if args[0] == "show":
852
+ at = _option_value(args, "--at")
853
+ if at is None:
854
+ raise click.UsageError("Usage: nf state show --at SEQUENCE|RUN|TIME [--app APP]")
855
+ parse_at(at)
856
+ show_at(direct_exec, at)
857
+ return
858
+ run_graph_state_command(direct_exec, args)
859
+
860
+
861
+ def _option_value(args: tuple[str, ...], option: str) -> str | None:
862
+ for index, arg in enumerate(args):
863
+ if arg == option and index + 1 < len(args):
864
+ return args[index + 1]
865
+ if arg.startswith(f"{option}="):
866
+ return arg.split("=", 1)[1]
867
+ return None
868
+
869
+
870
+ @click.command(context_settings={"ignore_unknown_options": True})
871
+ @stack_option
872
+ @app_option
873
+ @legacy_bin_option
874
+ @outdir_option
875
+ @click.argument("terraform_args", nargs=-1, type=click.UNPROCESSED)
876
+ def state(
877
+ stack: str | None,
878
+ app: str | None,
879
+ legacy_bin: str | None,
880
+ outdir: str | None,
881
+ terraform_args: tuple[str, ...],
882
+ ) -> None:
883
+ """Advanced state management for a stack.
884
+
885
+ `nf state force-unlock LOCK_ID [--app APP]` releases the state lock of a run that crashed
886
+ and cannot release it itself: the lock of a hybrid app's state, or, for a --stack, Terraform's
887
+ (`terraform force-unlock`). `nf state taint ADDRESS` marks an object tainted, so the next plan
888
+ replaces it, and `nf state untaint ADDRESS` clears the mark: in a hybrid app's state, or,
889
+ for a --stack, with `terraform taint` and `terraform untaint`.
890
+
891
+ A hybrid app stored in a graph state backend also has `nf state recover [OP_ID]
892
+ [--confirm-terminated] [--import-id ID]`, `nf state operations [--all]`, `nf state history
893
+ [ADDRESS]`, `nf state show --at SEQUENCE|RUN|TIME`, `nf state query "SQL"` and `nf state
894
+ checkpoint list|show|restore`, `nf state retention show|prune`, `nf state rm ADDRESS...`, `nf state mv SOURCE TARGET
895
+ [--auto-approve]`, `nf state import ADDRESS
896
+ [IMPORT_ID] [--identity JSON] [--auto-approve]`, and `nf state
897
+ migrate --to graph --source FILE | --to document --path FILE`. Other subcommands are passed
898
+ to `terraform state`.
899
+ """
900
+ from .graph_state import GRAPH_STATE_COMMANDS
901
+
902
+ subcommand = next(iter(terraform_args), None)
903
+ if subcommand in {"rm", "mv"} and stack is None and _resolve_direct_app_targets(app):
904
+ _graph_state_direct_app(app, outdir=outdir, args=terraform_args)
905
+ return
906
+ if subcommand in GRAPH_STATE_COMMANDS or (subcommand == "show" and _option_value(terraform_args, "--at") is not None):
907
+ if stack is not None:
908
+ raise click.UsageError(f"nf state {subcommand} works on a hybrid app's graph state; select it with --app, not --stack")
909
+ _graph_state_direct_app(app, outdir=outdir, args=terraform_args)
910
+ return
911
+ if terraform_args[:1] in {("taint",), ("untaint",)}:
912
+ command = terraform_args[0]
913
+ if len(terraform_args) != 2:
914
+ raise click.UsageError(f"Usage: nf state {command} ADDRESS [--app APP]")
915
+ address = terraform_args[1]
916
+ if stack is None and _set_tainted_direct_app(app, outdir=outdir, address=address, tainted=command == "taint"):
917
+ return
918
+ stack_dir = find_stack_directory(get_stack_name(stack, outdir), outdir)
919
+ sys.exit(run_terraform_command(stack_dir, [command, address], legacy_bin=legacy_bin))
920
+ if terraform_args[:1] == ("force-unlock",):
921
+ if len(terraform_args) != 2:
922
+ raise click.UsageError("Usage: nf state force-unlock LOCK_ID [--app APP]")
923
+ lock_id = terraform_args[1]
924
+ if stack is None and _force_unlock_direct_app(app, outdir=outdir, lock_id=lock_id):
925
+ return
926
+ stack_dir = find_stack_directory(get_stack_name(stack, outdir), outdir)
927
+ sys.exit(run_terraform_command(stack_dir, ["force-unlock", lock_id], legacy_bin=legacy_bin))
928
+
929
+ stack_name = get_stack_name(stack, outdir)
930
+ stack_dir = find_stack_directory(stack_name, outdir)
931
+ _reject_phased_stack_dir(stack_dir, command_name="state")
932
+ exit_code = run_terraform_command(
933
+ stack_dir,
934
+ ["state"] + list(terraform_args),
935
+ legacy_bin=legacy_bin,
936
+ )
937
+ sys.exit(exit_code)
938
+
939
+
940
+ @click.command()
941
+ @stack_option
942
+ @legacy_bin_option
943
+ @outdir_option
944
+ @click.option(
945
+ "--plan-file",
946
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
947
+ help="Show a plan artifact saved with 'nf plan --out'",
948
+ )
949
+ @click.argument("terraform_args", nargs=-1)
950
+ def show(
951
+ stack: str | None,
952
+ legacy_bin: str | None,
953
+ outdir: str | None,
954
+ plan_file: Path | None,
955
+ terraform_args: tuple[str, ...],
956
+ ) -> None:
957
+ """Show the current state or a saved plan for a stack."""
958
+ if plan_file is not None:
959
+ from .hybrid import show_plan_artifact
960
+
961
+ with _direct_execution_errors("showing plan"):
962
+ show_plan_artifact(plan_file)
963
+ return
964
+
965
+ stack_name = get_stack_name(stack, outdir)
966
+ stack_dir = find_stack_directory(stack_name, outdir)
967
+ _reject_phased_stack_dir(stack_dir, command_name="show")
968
+ exit_code = run_terraform_command(
969
+ stack_dir,
970
+ ["show"] + list(terraform_args),
971
+ legacy_bin=legacy_bin,
972
+ )
973
+ sys.exit(exit_code)
974
+
975
+
976
+ @click.command("import")
977
+ @stack_option
978
+ @legacy_bin_option
979
+ @outdir_option
980
+ @click.argument("terraform_args", nargs=-1)
981
+ def import_cmd(
982
+ stack: str | None,
983
+ legacy_bin: str | None,
984
+ outdir: str | None,
985
+ terraform_args: tuple[str, ...],
986
+ ) -> None:
987
+ """Import existing infrastructure into a stack."""
988
+ stack_name = get_stack_name(stack, outdir)
989
+ stack_dir = find_stack_directory(stack_name, outdir)
990
+ _reject_phased_stack_dir(stack_dir, command_name="import")
991
+ exit_code = run_terraform_command(
992
+ stack_dir,
993
+ ["import"] + list(terraform_args),
994
+ legacy_bin=legacy_bin,
995
+ )
996
+ sys.exit(exit_code)
997
+
998
+
999
+ @click.command()
1000
+ @outdir_option
1001
+ def list_apps(outdir: str | None) -> None:
1002
+ """List configured legacy and hybrid apps."""
1003
+ from rich.table import Table
1004
+
1005
+ project_config = load_project_config(allow_empty_apps=True)
1006
+ if not project_config.legacy_apps and not project_config.hybrid_apps:
1007
+ console.print("[bold red]No apps configured.[/bold red]")
1008
+ console.print("Add [tool.nf].legacy_apps and/or [tool.nf].hybrid_apps to pyproject.toml.")
1009
+ return
1010
+
1011
+ synthesized_apps = discover_synthesized_apps(outdir)
1012
+
1013
+ table = Table(title="Configured Apps")
1014
+ table.add_column("Selector", style="cyan")
1015
+ table.add_column("Type", style="magenta")
1016
+ table.add_column("Import Spec", style="blue")
1017
+ table.add_column("Status", style="yellow")
1018
+ table.add_column("Output", style="green")
1019
+
1020
+ for selector, spec in sorted(project_config.legacy_apps.items()):
1021
+ output_dir = synthesized_apps.get(selector)
1022
+ if output_dir and app_has_export_only_stacks(output_dir):
1023
+ status = "distributable (export-only phased stacks)"
1024
+ elif output_dir:
1025
+ status = "synthesized"
1026
+ else:
1027
+ status = "not synthesized"
1028
+ table.add_row(
1029
+ selector,
1030
+ "legacy",
1031
+ spec,
1032
+ status,
1033
+ str(output_dir) if output_dir else "-",
1034
+ )
1035
+
1036
+ for selector, spec in sorted(project_config.hybrid_apps.items()):
1037
+ table.add_row(
1038
+ selector,
1039
+ "hybrid",
1040
+ spec,
1041
+ "runtime",
1042
+ "-",
1043
+ )
1044
+
1045
+ console.print(table)
1046
+
1047
+
1048
+ @click.command()
1049
+ @outdir_option
1050
+ def list_stacks(outdir: str | None) -> None:
1051
+ """List all available stacks."""
1052
+ from rich.table import Table
1053
+
1054
+ selectors = list_available_stacks(outdir)
1055
+ if not selectors:
1056
+ print_no_stacks_message(outdir)
1057
+ return
1058
+
1059
+ table = Table(title="Available Stacks")
1060
+ table.add_column("Selector", style="cyan")
1061
+ table.add_column("Stack Name", style="magenta")
1062
+ table.add_column("App", style="blue")
1063
+ table.add_column("Kind", style="yellow")
1064
+ table.add_column("Status", style="red")
1065
+ table.add_column("Path", style="green")
1066
+
1067
+ selector_map, _, _ = discover_stacks(outdir)
1068
+ for selector in selectors:
1069
+ stack_path = selector_map[selector]
1070
+ phased_export = has_legacy_phased_artifacts(stack_path)
1071
+ table.add_row(
1072
+ selector,
1073
+ stack_path.name,
1074
+ stack_path.parent.name,
1075
+ "phased-export" if phased_export else "terraform-stack",
1076
+ "export-only" if phased_export else "legacy-runtime",
1077
+ str(stack_path),
1078
+ )
1079
+
1080
+ console.print(table)
1081
+
1082
+
1083
+ @click.command()
1084
+ @stack_option
1085
+ @legacy_bin_option
1086
+ @outdir_option
1087
+ @click.option(
1088
+ "--color/--no-color",
1089
+ default=True,
1090
+ help="Enable/disable colored diff output",
1091
+ )
1092
+ def diff(stack: str | None, legacy_bin: str | None, outdir: str | None, color: bool) -> None:
1093
+ """Show a diff of planned changes (formatted plan)."""
1094
+ stack_name = get_stack_name(stack, outdir)
1095
+ stack_dir = find_stack_directory(stack_name, outdir)
1096
+ _reject_phased_stack_dir(stack_dir, command_name="diff")
1097
+ legacy_bin = get_legacy_binary(app_value=legacy_bin)
1098
+
1099
+ # Create a plan file
1100
+ plan_file = stack_dir / "tfplan"
1101
+
1102
+ console.print(f"[bold blue]Creating plan for stack '{stack_name}'...[/bold blue]")
1103
+
1104
+ # Run terraform plan and save to file
1105
+ plan_cmd = [legacy_bin, "plan", "-out", str(plan_file)]
1106
+ result = subprocess.run(
1107
+ plan_cmd,
1108
+ check=False,
1109
+ cwd=stack_dir,
1110
+ capture_output=True,
1111
+ text=True,
1112
+ )
1113
+
1114
+ if result.returncode != 0:
1115
+ console.print("[bold red]Failed to create plan:[/bold red]")
1116
+ console.print(result.stderr)
1117
+ sys.exit(1)
1118
+
1119
+ # Show the plan in a more readable format
1120
+ show_cmd = [
1121
+ legacy_bin,
1122
+ "show",
1123
+ "-no-color" if not color else "",
1124
+ str(plan_file),
1125
+ ]
1126
+ show_cmd = [arg for arg in show_cmd if arg] # Remove empty strings
1127
+
1128
+ result = subprocess.run(
1129
+ show_cmd,
1130
+ check=False,
1131
+ cwd=stack_dir,
1132
+ capture_output=True,
1133
+ text=True,
1134
+ )
1135
+
1136
+ if result.returncode == 0:
1137
+ output = result.stdout
1138
+
1139
+ # Parse and format the output
1140
+ lines = output.split("\n")
1141
+ in_resource = False
1142
+ resource_changes = []
1143
+ current_resource = []
1144
+
1145
+ for line in lines:
1146
+ if line.strip().startswith("#"):
1147
+ if current_resource:
1148
+ resource_changes.append("\n".join(current_resource))
1149
+ current_resource = [line]
1150
+ in_resource = True
1151
+ elif in_resource and line.strip():
1152
+ current_resource.append(line)
1153
+ elif in_resource and not line.strip():
1154
+ if current_resource:
1155
+ resource_changes.append("\n".join(current_resource))
1156
+ current_resource = []
1157
+ in_resource = False
1158
+
1159
+ if current_resource:
1160
+ resource_changes.append("\n".join(current_resource))
1161
+
1162
+ # Display formatted output
1163
+ if resource_changes:
1164
+ console.print("\n[bold]Planned Changes:[/bold]\n")
1165
+ for change in resource_changes:
1166
+ if "will be created" in change:
1167
+ console.print(f"[green]{change}[/green]\n")
1168
+ elif "will be destroyed" in change:
1169
+ console.print(f"[red]{change}[/red]\n")
1170
+ elif "will be updated" in change or "will be replaced" in change:
1171
+ console.print(f"[yellow]{change}[/yellow]\n")
1172
+ else:
1173
+ console.print(f"{change}\n")
1174
+ else:
1175
+ console.print("[dim]No changes planned.[/dim]")
1176
+ else:
1177
+ console.print("[bold red]Failed to show plan:[/bold red]")
1178
+ console.print(result.stderr)
1179
+ sys.exit(1)
1180
+
1181
+ # Clean up plan file
1182
+ plan_file.unlink(missing_ok=True)