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,111 @@
1
+ """Interactive CLI helpers for state migration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from netherframe.core.backends.state_engine import LocalStateBackend
8
+ from netherframe.core.state_migration import StateMigrator
9
+
10
+
11
+ class MigrationWizard:
12
+ """Interactive wizard for migrating Terraform state to Netherframe."""
13
+
14
+ def __init__(self) -> None:
15
+ """Initialize the migration wizard."""
16
+ self.migrator = StateMigrator()
17
+
18
+ def run(self) -> bool:
19
+ """Run the interactive migration wizard."""
20
+ print("=== Terraform to Netherframe State Migration Wizard ===")
21
+ print()
22
+
23
+ stack_id = input("Enter the stack ID for imported resources: ").strip()
24
+ if not stack_id:
25
+ print("ERROR: Stack ID is required")
26
+ return False
27
+
28
+ state_path_input = input(
29
+ "Enter path to terraform.tfstate file (or 'pull' to pull from current directory): ",
30
+ ).strip()
31
+
32
+ if state_path_input.lower() == "pull":
33
+ print("Pulling Terraform state from current directory...")
34
+ state = StateMigrator.pull_terraform_state(Path.cwd(), stack_id)
35
+ if state is None:
36
+ print("ERROR: Failed to pull Terraform state")
37
+ return False
38
+ else:
39
+ tf_state_path = Path(state_path_input)
40
+ if not tf_state_path.exists():
41
+ print(f"ERROR: State file not found: {tf_state_path}")
42
+ return False
43
+
44
+ try:
45
+ state = StateMigrator.import_terraform_state(tf_state_path, stack_id)
46
+ except Exception as e:
47
+ print(f"ERROR: Failed to import state: {e}")
48
+ return False
49
+
50
+ print(f"Successfully imported {len(state.resources)} resources")
51
+ print()
52
+
53
+ app_path_input = input(
54
+ "Enter path to Netherframe app file for compatibility check (optional, press Enter to skip): ",
55
+ ).strip()
56
+
57
+ if app_path_input:
58
+ app_path = Path(app_path_input)
59
+ if app_path.exists():
60
+ print("Checking compatibility...")
61
+ if state_path_input.lower() != "pull":
62
+ issues = StateMigrator.validate_state_compatibility(
63
+ tf_state_path,
64
+ app_path,
65
+ )
66
+
67
+ if issues:
68
+ print("\nCompatibility issues found:")
69
+ for issue in issues:
70
+ print(f" - {issue}")
71
+
72
+ continue_input = input("\nContinue anyway? (yes/no): ").strip().lower()
73
+ if continue_input != "yes":
74
+ print("Migration cancelled")
75
+ return False
76
+ else:
77
+ print("No compatibility issues found")
78
+ print()
79
+
80
+ output_path_input = input(
81
+ "Enter output path for Netherframe state (default: nf.tfstate): ",
82
+ ).strip()
83
+ output_path = Path(output_path_input) if output_path_input else Path("nf.tfstate")
84
+ output_path.parent.mkdir(parents=True, exist_ok=True)
85
+
86
+ print(f"\nSaving Netherframe state to {output_path}...")
87
+ try:
88
+ backend = LocalStateBackend(output_path)
89
+ backend.save(state)
90
+ print("State saved successfully!")
91
+ print()
92
+ print("Next steps:")
93
+ print("1. Update your Netherframe app to use the migrated state")
94
+ print("2. Run 'nf plan' to verify the state matches your infrastructure")
95
+ print("3. Consider backing up the original Terraform state")
96
+ return True
97
+ except Exception as e:
98
+ print(f"ERROR: Failed to save state: {e}")
99
+ return False
100
+
101
+
102
+ def main() -> None:
103
+ """CLI entry point for state migration."""
104
+ import sys
105
+
106
+ wizard = MigrationWizard()
107
+ sys.exit(0 if wizard.run() else 1)
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
@@ -0,0 +1 @@
1
+ """TUI components for NF CLI."""
@@ -0,0 +1,200 @@
1
+ """Query and action filtering helpers for the plan viewer TUI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import codeop
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Callable
11
+
12
+ from .plan_models import ResourceChange
13
+
14
+ _ALLOWED_FILTER_FIELDS = {
15
+ "resource_id",
16
+ "action",
17
+ "resource_type",
18
+ "resource_name",
19
+ "description",
20
+ "stack",
21
+ "has_changes",
22
+ "has_before",
23
+ "has_after",
24
+ }
25
+
26
+
27
+ def next_action_filter(current: set[str], action: str) -> set[str]:
28
+ """Compute next action filter set for action-key shortcuts."""
29
+ all_actions = {"create", "update", "delete"}
30
+ if action not in all_actions:
31
+ return set(current)
32
+ if set(current) == {action}:
33
+ return all_actions
34
+ return {action}
35
+
36
+
37
+ def _is_likely_incomplete_expression(expression: str, message: str) -> bool:
38
+ """Heuristic to treat common in-progress expressions as pending."""
39
+ stripped = expression.strip()
40
+ if not stripped:
41
+ return True
42
+
43
+ lower = stripped.lower()
44
+ if message in {
45
+ "unexpected EOF while parsing",
46
+ "unterminated string literal",
47
+ "EOL while scanning string literal",
48
+ }:
49
+ return True
50
+ if "was never closed" in message:
51
+ return True
52
+
53
+ incomplete_suffixes = (
54
+ "and",
55
+ "or",
56
+ "not",
57
+ "in",
58
+ "not in",
59
+ "==",
60
+ "!=",
61
+ "<",
62
+ "<=",
63
+ ">",
64
+ ">=",
65
+ )
66
+ if any(lower.endswith(suffix) for suffix in incomplete_suffixes):
67
+ return True
68
+ if stripped[-1] in {"(", "[", "{", ","}:
69
+ return True
70
+
71
+ if stripped.count("(") > stripped.count(")"):
72
+ return True
73
+ if stripped.count("[") > stripped.count("]"):
74
+ return True
75
+ if stripped.count("{") > stripped.count("}"):
76
+ return True
77
+
78
+ if message == "invalid syntax" and (stripped.endswith(('"', "'")) is False and lower.endswith((" and", " or", " not"))):
79
+ return True
80
+ return False
81
+
82
+
83
+ def _filter_context(change: ResourceChange) -> dict[str, Any]:
84
+ """Build safe expression context for one change."""
85
+ return {
86
+ "resource_id": change.resource_id,
87
+ "action": change.action,
88
+ "resource_type": change.resource_type,
89
+ "resource_name": change.resource_name,
90
+ "description": change.description,
91
+ "stack": change.stack or "",
92
+ "has_changes": bool(change.attribute_changes),
93
+ "has_before": bool(change.before_state),
94
+ "has_after": bool(change.after_state),
95
+ }
96
+
97
+
98
+ def build_query_matcher(
99
+ query: str,
100
+ ) -> tuple[Callable[[ResourceChange], bool], str | None, bool]:
101
+ """Build a matcher for plain text or `py:` expression filter queries."""
102
+ cleaned = query.strip()
103
+ if not cleaned:
104
+ return (lambda _change: True), None, False
105
+
106
+ if cleaned.lower().startswith("py:"):
107
+ expression = cleaned[3:].strip()
108
+ if not expression:
109
+ return (lambda _change: True), None, False
110
+
111
+ try:
112
+ compiled = codeop.compile_command(
113
+ expression,
114
+ filename="<idiff-filter>",
115
+ symbol="eval",
116
+ )
117
+ except (OverflowError, SyntaxError, ValueError) as exc:
118
+ message = getattr(exc, "msg", str(exc))
119
+ if _is_likely_incomplete_expression(expression, message):
120
+ return (lambda _change: True), None, True
121
+ return (lambda _change: False), f"Invalid filter expression: {message}", False
122
+
123
+ if compiled is None:
124
+ return (lambda _change: True), None, True
125
+
126
+ try:
127
+ expr_ast = ast.parse(expression, mode="eval")
128
+ except SyntaxError as exc:
129
+ return (lambda _change: False), f"Invalid filter expression: {exc.msg}", False
130
+
131
+ allowed_nodes = (
132
+ ast.Expression,
133
+ ast.BoolOp,
134
+ ast.And,
135
+ ast.Or,
136
+ ast.UnaryOp,
137
+ ast.Not,
138
+ ast.Compare,
139
+ ast.Eq,
140
+ ast.NotEq,
141
+ ast.In,
142
+ ast.NotIn,
143
+ ast.Gt,
144
+ ast.GtE,
145
+ ast.Lt,
146
+ ast.LtE,
147
+ ast.Name,
148
+ ast.Load,
149
+ ast.Constant,
150
+ ast.List,
151
+ ast.Tuple,
152
+ ast.Set,
153
+ ast.Dict,
154
+ )
155
+ for node in ast.walk(expr_ast):
156
+ if not isinstance(node, allowed_nodes):
157
+ return (
158
+ (lambda _change: False),
159
+ "Unsupported expression in filter. Use names/literals/comparisons/and-or-not.",
160
+ False,
161
+ )
162
+ if isinstance(node, ast.Name) and node.id not in _ALLOWED_FILTER_FIELDS:
163
+ return (
164
+ (lambda _change: False),
165
+ f"Unknown filter field: '{node.id}'.",
166
+ False,
167
+ )
168
+
169
+ compiled_expr = compile(expr_ast, "<idiff-filter>", "eval")
170
+
171
+ def _match_expr(change: ResourceChange) -> bool:
172
+ try:
173
+ return bool(
174
+ eval( # noqa: S307
175
+ compiled_expr,
176
+ {"__builtins__": {}},
177
+ _filter_context(change),
178
+ ),
179
+ )
180
+ except Exception:
181
+ return False
182
+
183
+ return _match_expr, None, False
184
+
185
+ lowered = cleaned.lower()
186
+
187
+ def _match_text(change: ResourceChange) -> bool:
188
+ haystack = " ".join(
189
+ [
190
+ change.resource_id,
191
+ change.resource_type,
192
+ change.resource_name,
193
+ change.action,
194
+ change.description,
195
+ change.stack or "",
196
+ ],
197
+ ).lower()
198
+ return lowered in haystack
199
+
200
+ return _match_text, None, False
@@ -0,0 +1,51 @@
1
+ """Shared data models for the plan viewer TUI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ class ResourceChange:
9
+ """Represents a single resource change in the plan."""
10
+
11
+ def __init__(
12
+ self,
13
+ resource_id: str,
14
+ action: str,
15
+ description: str,
16
+ details: dict[str, Any] | None = None,
17
+ ) -> None:
18
+ self.resource_id = resource_id
19
+ self.action = action
20
+ self.description = description
21
+ self.details = details or {}
22
+
23
+ detail_data = self.details
24
+ self.resource_type = detail_data.get("resource_type", "")
25
+ self.resource_name = detail_data.get("resource_name", "")
26
+ self.stack = detail_data.get("stack", "")
27
+ self.attribute_changes = detail_data.get("attribute_changes", [])
28
+ self.before_state = detail_data.get("before_state", {})
29
+ self.after_state = detail_data.get("after_state", {})
30
+ # Attribute paths the provider planned as unknown (a hybrid plan's known_after_apply)
31
+ self.known_after_apply = detail_data.get("known_after_apply") or []
32
+
33
+ @property
34
+ def icon(self) -> str:
35
+ """Get icon for the action type."""
36
+ icons = {
37
+ "create": "+",
38
+ "update": "~",
39
+ "delete": "-",
40
+ }
41
+ return icons.get(self.action, "?")
42
+
43
+ @property
44
+ def color(self) -> str:
45
+ """Get color for the action type."""
46
+ colors = {
47
+ "create": "green",
48
+ "update": "yellow",
49
+ "delete": "red",
50
+ }
51
+ return colors.get(self.action, "white")