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,17 @@
1
+ """Terraform command utilities for NF CLI."""
2
+
3
+ import click
4
+
5
+
6
+ @click.command()
7
+ def console() -> None:
8
+ """Start Terraform console."""
9
+ click.echo("Terraform console not yet implemented")
10
+
11
+
12
+ @click.command()
13
+ @click.argument("command", required=False)
14
+ def terraform(command: str | None = None) -> None:
15
+ """Run raw Terraform commands."""
16
+ cmd = command or "help"
17
+ click.echo(f"Running terraform {cmd} not yet implemented")
@@ -0,0 +1,117 @@
1
+ """Watch command for NF CLI."""
2
+
3
+ import time
4
+ from collections.abc import Callable
5
+ from pathlib import Path
6
+
7
+ import click
8
+ from watchdog.events import FileSystemEvent, FileSystemEventHandler
9
+ from watchdog.observers import Observer
10
+
11
+ from netherframe.core.logging import get_logger
12
+
13
+ from netherframe.cli.logging import trace_operation
14
+ from .synthesis import run_synthesis
15
+
16
+ logger = get_logger(__name__)
17
+
18
+
19
+ class NfFileHandler(FileSystemEventHandler):
20
+ """Handle file system events for NF files."""
21
+
22
+ def __init__(self, synth_callback: Callable[[], None]) -> None:
23
+ self.synth_callback = synth_callback
24
+ self.last_synth = 0
25
+ self.min_interval = 1.0 # Minimum seconds between synths
26
+
27
+ def should_process(self, event: FileSystemEvent) -> bool:
28
+ """Check if we should process this event."""
29
+ if event.is_directory:
30
+ return False
31
+
32
+ src_path = event.src_path.decode() if isinstance(event.src_path, bytes) else event.src_path
33
+ path = Path(src_path)
34
+
35
+ # Ignore hidden files and directories
36
+ if any(part.startswith(".") for part in path.parts):
37
+ return False
38
+
39
+ # Process Python files and config files
40
+ return path.suffix in [".py", ".toml", ".yaml", ".yml"]
41
+
42
+ def on_any_event(self, event: FileSystemEvent) -> None:
43
+ """Handle any file system event."""
44
+ if not self.should_process(event):
45
+ return
46
+
47
+ logger.trace(f"File system event: {event.event_type} on {event.src_path}")
48
+
49
+ # Throttle synth calls
50
+ current_time = time.time()
51
+ if current_time - self.last_synth < self.min_interval:
52
+ return
53
+
54
+ logger.info(f"Detected change in {event.src_path}")
55
+ self.last_synth = current_time
56
+
57
+ try:
58
+ self.synth_callback()
59
+ except Exception as e:
60
+ logger.error("Error during synthesis: %s", e)
61
+
62
+
63
+ @click.command(name="watch")
64
+ @click.option("--interval", "-i", default=2, help="Watch interval in seconds")
65
+ @click.option(
66
+ "--path",
67
+ "-p",
68
+ type=click.Path(exists=True),
69
+ default=".",
70
+ help="Path to watch",
71
+ )
72
+ @trace_operation("watch_command")
73
+ def watch(interval: int, path: str) -> None:
74
+ """Watch for file changes and re-synthesize."""
75
+ watch_path = Path(path).resolve()
76
+ click.echo(f"Watching {watch_path} for changes...")
77
+ click.echo("Press Ctrl+C to stop")
78
+
79
+ @trace_operation("run_synth")
80
+ def run_synth() -> None:
81
+ """Run synthesis."""
82
+ click.echo("\nRunning synthesis...")
83
+ logger.trace("Starting synthesis from file watcher")
84
+ try:
85
+ success = run_synthesis()
86
+ except click.ClickException as e:
87
+ click.echo("Synthesis failed\n", err=True)
88
+ click.echo(str(e), err=True)
89
+ return
90
+ except Exception as e: # noqa: BLE001
91
+ click.echo("Synthesis failed\n", err=True)
92
+ click.echo(str(e), err=True)
93
+ return
94
+
95
+ if success:
96
+ click.echo("Synthesis complete\n")
97
+ return
98
+
99
+ click.echo("Synthesis failed\n", err=True)
100
+
101
+ # Run initial synthesis
102
+ run_synth()
103
+
104
+ # Set up file watcher
105
+ event_handler = NfFileHandler(run_synth)
106
+ observer = Observer()
107
+ observer.schedule(event_handler, str(watch_path), recursive=True)
108
+ observer.start()
109
+
110
+ try:
111
+ while True:
112
+ time.sleep(interval)
113
+ except KeyboardInterrupt:
114
+ click.echo("\nStopping watcher...")
115
+ observer.stop()
116
+
117
+ observer.join()
@@ -0,0 +1,18 @@
1
+ """Configure the CLI process before importing the application or gRPC."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+
8
+ def main() -> None:
9
+ """Run nf with fork support disabled for its fork/exec subprocess launches.
10
+
11
+ Keep this module stdlib-only: gRPC reads the setting during initialization.
12
+ Library imports must not change the embedding application's fork behavior.
13
+ """
14
+ os.environ.setdefault("GRPC_ENABLE_FORK_SUPPORT", "0")
15
+
16
+ from netherframe.cli.main import main as run_cli
17
+
18
+ run_cli()
@@ -0,0 +1,33 @@
1
+ """CLI-specific logging helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import wraps
6
+ from typing import Any, TypeVar, cast
7
+ from collections.abc import Callable
8
+
9
+ from netherframe.core.logging import get_logger
10
+
11
+ F = TypeVar("F", bound=Callable[..., Any])
12
+
13
+
14
+ def trace_operation(operation: str) -> Callable[[F], F]:
15
+ """Decorator to trace CLI operations at TRACE level."""
16
+
17
+ def decorator(func: F) -> F:
18
+ func_logger = get_logger(func.__module__)
19
+
20
+ @wraps(func)
21
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
22
+ func_logger.trace(f"Starting operation: {operation}")
23
+ try:
24
+ result = func(*args, **kwargs)
25
+ func_logger.trace(f"Completed operation: {operation}")
26
+ return result
27
+ except Exception as exc:
28
+ func_logger.trace(f"Failed operation: {operation} - {exc}")
29
+ raise
30
+
31
+ return cast("F", wrapper)
32
+
33
+ return decorator
@@ -0,0 +1,177 @@
1
+ """Main CLI entry point for NF - streamlined and modular."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ # Suppress logging by default; CLI enables logging explicitly via flags.
8
+ os.environ.setdefault("NF_NO_AUTO_LOGGING", "1")
9
+
10
+ import click
11
+
12
+ from netherframe.core.logging import LogFormat, configure_logging, get_logger, reset_logging
13
+
14
+ from .commands import LazyGroup
15
+ from .logging import trace_operation
16
+ from .options import logging_options
17
+ from .ui import console, print_header, print_section
18
+
19
+ logger = get_logger(__name__)
20
+
21
+
22
+ def _configure_hotpath_logging_env(trace: bool, log_level: str | None) -> None:
23
+ """Control static hot-path logging gates for subprocessed app execution."""
24
+ effective_level = (log_level or "").upper()
25
+ hotpath_enabled = trace or effective_level in {"DEBUG", "TRACE"}
26
+ os.environ["NF_RESOURCE_HOTPATH_LOGGING"] = "1" if hotpath_enabled else "0"
27
+
28
+
29
+ @click.group(name="nf", cls=LazyGroup)
30
+ @click.version_option(package_name="netherframe.cli")
31
+ @logging_options
32
+ @click.pass_context
33
+ @trace_operation("cli_main")
34
+ def cli(
35
+ ctx: click.Context,
36
+ log_level: str | None,
37
+ log_format: str | None,
38
+ trace: bool,
39
+ ) -> None:
40
+ """NF - Netherframe Infrastructure as Code Framework.
41
+
42
+ A Python framework that provides infrastructure as code capabilities,
43
+ allowing developers to define infrastructure using Python while
44
+ leveraging provider ecosystems.
45
+ """
46
+ log_level = log_level or os.environ.get("NF_LOG_LEVEL")
47
+ log_format = log_format or os.environ.get("NF_LOG_FORMAT")
48
+ _configure_hotpath_logging_env(trace, log_level)
49
+
50
+ # Configure logging
51
+ if log_level or log_format or trace:
52
+ format_type = LogFormat.TEXT # default
53
+ if log_format and log_format.lower() == "json":
54
+ format_type = LogFormat.JSON
55
+ elif log_format and log_format.lower() == "pretty":
56
+ format_type = LogFormat.PRETTY
57
+
58
+ level = log_level or "INFO"
59
+ if trace:
60
+ level = "TRACE"
61
+ reset_logging()
62
+ configure_logging(
63
+ level=level,
64
+ log_format=format_type,
65
+ )
66
+ logger.debug("CLI logging configured")
67
+ if trace:
68
+ logger.trace("TRACE level logging enabled")
69
+
70
+ if os.environ.get("GRPC_ENABLE_FORK_SUPPORT") == "0":
71
+ logger.debug("GRPC_ENABLE_FORK_SUPPORT=0 disables gRPC fork handling to avoid diagnostics during CLI fork/exec launches; set GRPC_ENABLE_FORK_SUPPORT=1 before starting nf to opt out (unsetting it restores the CLI default).")
72
+
73
+
74
+ @cli.command(name="help")
75
+ def help_cmd() -> None:
76
+ """Show help information and common usage examples."""
77
+ print_header("NF - Netherframe Infrastructure as Code Framework")
78
+ console.print()
79
+
80
+ print_section("Common Commands:")
81
+ console.print(
82
+ " [green]nf synth[/green] - Synthesize apps to Terraform configuration",
83
+ )
84
+ console.print(
85
+ " [green]nf deploy[/green] - Deploy infrastructure using Terraform or hybrid execution",
86
+ )
87
+ console.print(
88
+ " [green]nf plan[/green] - Show planned infrastructure changes",
89
+ )
90
+ console.print(
91
+ " [green]nf apply[/green] - Apply infrastructure changes",
92
+ )
93
+ console.print(" [green]nf destroy[/green] - Destroy infrastructure")
94
+
95
+ console.print()
96
+ print_section("Discovery Commands:")
97
+ console.print(
98
+ " [green]nf discover list-providers[/green] - List available discovery providers",
99
+ )
100
+ console.print(
101
+ " [green]nf discover list-resources[/green] - List supported resource types",
102
+ )
103
+ console.print(
104
+ " [green]nf discover resources[/green] - Discover live infrastructure",
105
+ )
106
+
107
+ console.print()
108
+ print_section("Provider Commands:")
109
+ console.print(
110
+ " [green]nf providers list[/green] - List available provider packages",
111
+ )
112
+ console.print(
113
+ " [green]nf providers describe[/green] - Describe a provider set",
114
+ )
115
+ console.print(" [green]nf providers search[/green] - Search for providers")
116
+
117
+ console.print()
118
+ print_section("Generation Commands:")
119
+ console.print(
120
+ " [green]nf generate providers[/green] - Generate provider package(s)",
121
+ )
122
+ console.print(
123
+ " [green]nf generate functions[/green] - Generate Terraform functions",
124
+ )
125
+ console.print(
126
+ " [green]nf generate imports[/green] - Generate import configuration",
127
+ )
128
+ console.print(
129
+ " [green]nf encode[/green] - Add nf_autoid encoding cookies to source files",
130
+ )
131
+
132
+ console.print()
133
+ print_section("App and Stack Management:")
134
+ console.print(" [green]nf list-apps[/green] - List configured legacy and hybrid apps")
135
+ console.print(" [green]nf list-stacks[/green] - List synthesized legacy stacks and phased export bundles")
136
+ console.print(
137
+ " [green]nf shell[/green] - Open shell in stack directory",
138
+ )
139
+ console.print(" [green]nf cd[/green] - Change to stack directory")
140
+
141
+ console.print()
142
+ print_section("Drift Detection:")
143
+ console.print(
144
+ " [green]nf drift detect[/green] - Detect infrastructure drift",
145
+ )
146
+ console.print(" [green]nf drift fix[/green] - Fix detected drift")
147
+ console.print(
148
+ " [green]nf drift check[/green] - Check if drift exists (for CI/CD)",
149
+ )
150
+
151
+ console.print()
152
+ print_section("AI Agent Guidance:")
153
+ console.print(" [green]nf skill[/green] - Read the bundled agent skill")
154
+ console.print(" [green]nf skill install[/green] - Export it to .agents/skills/netherframe")
155
+ console.print()
156
+ print_section("Examples:")
157
+ console.print(" [dim]# Discover AWS resources[/dim]")
158
+ console.print(" nf discover resources aws --region us-east-1\n")
159
+ console.print(" [dim]# Generate AWS provider[/dim]")
160
+ console.print(" nf generate providers hashicorp/aws\n")
161
+ console.print(" [dim]# Synthesize and deploy[/dim]")
162
+ console.print(" nf deploy\n")
163
+ console.print(" [dim]# Generate common providers[/dim]")
164
+ console.print(" nf generate providers --set common")
165
+
166
+ console.print("\n[dim]For detailed help on any command:[/dim]")
167
+ console.print(" nf <command> --help")
168
+
169
+
170
+ @trace_operation("main")
171
+ def main() -> None:
172
+ """Entry point for the nf CLI."""
173
+ cli()
174
+
175
+
176
+ if __name__ == "__main__":
177
+ main()
@@ -0,0 +1,32 @@
1
+ """Shared Click options for the CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ import click
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Callable
11
+
12
+ LOG_LEVELS = ["TRACE", "DEBUG", "INFO", "WARNING", "ERROR"]
13
+ LOG_FORMATS = ["text", "json", "pretty"]
14
+
15
+
16
+ def logging_options(func: Callable[..., object]) -> Callable[..., object]:
17
+ func = click.option(
18
+ "--trace",
19
+ is_flag=True,
20
+ help="Enable TRACE level logging",
21
+ )(func)
22
+ func = click.option(
23
+ "--log-format",
24
+ type=click.Choice(LOG_FORMATS, case_sensitive=False),
25
+ help="Set log output format",
26
+ )(func)
27
+ func = click.option(
28
+ "--log-level",
29
+ type=click.Choice(LOG_LEVELS),
30
+ help="Set logging level",
31
+ )(func)
32
+ return func
File without changes
@@ -0,0 +1 @@
1
+ """Service layer for CLI logic."""
@@ -0,0 +1,62 @@
1
+ """Helpers for loading configured Netherframe apps in-process."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import click
11
+
12
+
13
+ def _ensure_cli_import_context() -> None:
14
+ """Prepare import state for loading local project apps."""
15
+ cwd = str(Path.cwd())
16
+ if cwd not in sys.path:
17
+ sys.path.insert(0, cwd)
18
+
19
+ try:
20
+ from netherframe.codec.autoid import register_codec
21
+
22
+ register_codec()
23
+ except Exception:
24
+ # Loading configured apps should still work when the codec package
25
+ # is unavailable or already registered.
26
+ pass
27
+
28
+
29
+ def load_app_from_spec(app_spec: str) -> Any:
30
+ """Load an app object or app factory result from a configured app spec."""
31
+ if ":" not in app_spec:
32
+ raise click.ClickException(
33
+ f"Invalid app spec '{app_spec}'. Expected 'module.path:app_attr'.",
34
+ )
35
+
36
+ module_path, app_attr = app_spec.rsplit(":", 1)
37
+ _ensure_cli_import_context()
38
+
39
+ try:
40
+ module = importlib.import_module(module_path)
41
+ except Exception as exc:
42
+ raise click.ClickException(
43
+ f"Failed to import module '{module_path}' from app spec '{app_spec}': {exc}",
44
+ ) from exc
45
+
46
+ if not hasattr(module, app_attr):
47
+ raise click.ClickException(
48
+ f"Module '{module_path}' has no attribute '{app_attr}' from app spec '{app_spec}'.",
49
+ )
50
+
51
+ app_or_factory = getattr(module, app_attr)
52
+ try:
53
+ app = app_or_factory() if callable(app_or_factory) else app_or_factory
54
+ except Exception as exc:
55
+ raise click.ClickException(
56
+ f"Failed to construct app '{app_spec}': {exc}",
57
+ ) from exc
58
+
59
+ if app is None:
60
+ raise click.ClickException(f"App '{app_spec}' resolved to None.")
61
+
62
+ return app
@@ -0,0 +1,205 @@
1
+ """Resolve app names to their synthesis output directories."""
2
+
3
+ from pathlib import Path
4
+
5
+ from netherframe.core.logging import get_logger
6
+
7
+ from netherframe.cli.logging import trace_operation
8
+ from netherframe.cli.services.stack_inventory import has_legacy_phased_artifacts
9
+
10
+ logger = get_logger(__name__)
11
+
12
+ # Default output directory name
13
+ DEFAULT_OUTDIR = ".nf.out"
14
+
15
+
16
+ @trace_operation("find_app_directory")
17
+ def find_app_directory(
18
+ app_name_or_path: str,
19
+ search_from: Path | None = None,
20
+ ) -> Path | None:
21
+ """Find the app directory given an app name or path.
22
+
23
+ This function attempts to resolve an app in the following order:
24
+ 1. If it's already a valid path to an app directory, return it
25
+ 2. If it's an app name, search for it in .nf.out directories
26
+ 3. Search in current directory's .nf.out
27
+ 4. Search in parent directories' .nf.out (up to root)
28
+
29
+ Args:
30
+ app_name_or_path: Either an app name (e.g., "my-app") or a path
31
+ search_from: Directory to start searching from (defaults to current)
32
+
33
+ Returns:
34
+ Path to the app directory if found, None otherwise
35
+
36
+ """
37
+ # Start from current directory if not specified
38
+ if search_from is None:
39
+ search_from = Path.cwd()
40
+
41
+ logger.trace(f"Searching for app: {app_name_or_path} from {search_from}")
42
+
43
+ # First, check if it's already a valid path
44
+ as_path = Path(app_name_or_path)
45
+ if as_path.is_absolute() and as_path.exists() and as_path.is_dir():
46
+ # Check if it's an app directory (has nf.tf.json or subdirs with nf.tf.json)
47
+ if _is_app_directory(as_path):
48
+ logger.debug("Found app directory at absolute path: %s", as_path)
49
+ return as_path
50
+
51
+ # If it's a relative path that exists
52
+ if not as_path.is_absolute():
53
+ full_path = search_from / as_path
54
+ if full_path.exists() and full_path.is_dir() and _is_app_directory(full_path):
55
+ logger.debug("Found app directory at relative path: %s", full_path)
56
+ return full_path
57
+
58
+ # Now treat it as an app name and search for it
59
+ app_name = as_path.name # Get just the last component
60
+
61
+ # Search in .nf.out directories
62
+ current = search_from
63
+ while current != current.parent: # Stop at root
64
+ outdir = current / DEFAULT_OUTDIR
65
+ if outdir.exists() and outdir.is_dir():
66
+ app_dir = outdir / app_name
67
+ if app_dir.exists() and app_dir.is_dir() and _is_app_directory(app_dir):
68
+ logger.debug("Found app '%s' in %s", app_name, outdir)
69
+ return app_dir
70
+ current = current.parent
71
+
72
+ # Also check the root directory
73
+ root_outdir = Path("/") / DEFAULT_OUTDIR
74
+ if root_outdir.exists():
75
+ app_dir = root_outdir / app_name
76
+ if app_dir.exists() and app_dir.is_dir() and _is_app_directory(app_dir):
77
+ logger.debug("Found app '%s' in %s", app_name, root_outdir)
78
+ return app_dir
79
+
80
+ logger.debug("Could not find app '%s'", app_name_or_path)
81
+ return None
82
+
83
+
84
+ @trace_operation("list_available_apps")
85
+ def list_available_apps(search_from: Path | None = None) -> list[tuple[str, Path]]:
86
+ """List all available apps in .nf.out directories.
87
+
88
+ Args:
89
+ search_from: Directory to start searching from (defaults to current)
90
+
91
+ Returns:
92
+ List of (app_name, app_path) tuples
93
+
94
+ """
95
+ if search_from is None:
96
+ search_from = Path.cwd()
97
+
98
+ apps = []
99
+ visited = set()
100
+
101
+ # Search in .nf.out directories
102
+ current = search_from
103
+ while current != current.parent: # Stop at root
104
+ outdir = current / DEFAULT_OUTDIR
105
+ if outdir.exists() and outdir.is_dir() and outdir not in visited:
106
+ visited.add(outdir)
107
+ for item in outdir.iterdir():
108
+ if item.is_dir() and _is_app_directory(item):
109
+ apps.append((item.name, item))
110
+ current = current.parent
111
+
112
+ # Sort by app name
113
+ apps.sort(key=lambda x: x[0])
114
+ return apps
115
+
116
+
117
+ @trace_operation("find_stack_in_app")
118
+ def find_stack_in_app(app_dir: Path, stack_name: str) -> Path | None:
119
+ """Find a stack within an app directory.
120
+
121
+ Args:
122
+ app_dir: Path to the app directory
123
+ stack_name: Name of the stack to find
124
+
125
+ Returns:
126
+ Path to the stack directory if found, None otherwise
127
+
128
+ """
129
+ stack_dir = app_dir / stack_name
130
+ if stack_dir.exists() and stack_dir.is_dir():
131
+ # Check if it's a valid stack (regular synthesized config or explicit phased export bundle)
132
+ if (stack_dir / "nf.tf.json").exists() or has_legacy_phased_artifacts(stack_dir):
133
+ return stack_dir
134
+ return None
135
+
136
+
137
+ def _is_app_directory(path: Path) -> bool:
138
+ """Check if a directory is a valid app directory.
139
+
140
+ An app directory either:
141
+ 1. Contains subdirectories with nf.tf.json files (multi-stack app)
142
+ 2. Contains nf.tf.json directly (single-stack app)
143
+ 3. Contains phased export-only stack bundles
144
+ """
145
+ # Check for subdirectories with nf.tf.json
146
+ has_stack_subdirs = False
147
+ for item in path.iterdir():
148
+ if item.is_dir() and (item / "nf.tf.json").exists():
149
+ has_stack_subdirs = True
150
+ break
151
+
152
+ if has_stack_subdirs:
153
+ return True
154
+
155
+ # Check if it's a single-stack app
156
+ if (path / "nf.tf.json").exists():
157
+ return True
158
+
159
+ # Check for export-only phased stack bundles
160
+ return has_legacy_phased_artifacts(path)
161
+
162
+
163
+ @trace_operation("resolve_app_and_stack")
164
+ def resolve_app_and_stack(
165
+ app_or_path: str,
166
+ stack_name: str | None = None,
167
+ ) -> tuple[Path | None, Path | None]:
168
+ """Resolve app and optionally stack from input.
169
+
170
+ Args:
171
+ app_or_path: App name or path
172
+ stack_name: Optional stack name within the app
173
+
174
+ Returns:
175
+ Tuple of (app_path, stack_path) where stack_path may be None
176
+
177
+ """
178
+ app_dir = find_app_directory(app_or_path)
179
+ if not app_dir:
180
+ return (None, None)
181
+
182
+ if stack_name:
183
+ stack_dir = find_stack_in_app(app_dir, stack_name)
184
+ return (app_dir, stack_dir)
185
+
186
+ return (app_dir, None)
187
+
188
+
189
+ def get_app_name_from_path(app_path: Path) -> str:
190
+ """Extract the app name from an app path.
191
+
192
+ This handles both .nf.out/app-name and full paths.
193
+ """
194
+ # If the parent is .nf.out, use the directory name
195
+ if app_path.parent.name == DEFAULT_OUTDIR:
196
+ return app_path.name
197
+
198
+ # Otherwise, try to extract from the path
199
+ parts = app_path.parts
200
+ for i, part in enumerate(parts):
201
+ if part == DEFAULT_OUTDIR and i + 1 < len(parts):
202
+ return parts[i + 1]
203
+
204
+ # Default to the directory name
205
+ return app_path.name