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,499 @@
1
+ """Drift detection commands for the NF CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from netherframe.core.serialization import orjson_compat as json
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import click
11
+ from netherframe.cli.ui import console
12
+ from rich.panel import Panel
13
+ from rich.table import Table
14
+
15
+
16
+ def find_python_files(paths: list[Path]) -> list[Path]:
17
+ """Find all Python files in the given paths."""
18
+ python_files: list[Path] = []
19
+
20
+ for path in paths:
21
+ if path.is_file() and path.suffix == ".py":
22
+ python_files.append(path)
23
+ elif path.is_dir():
24
+ python_files.extend(path.rglob("*.py"))
25
+
26
+ return python_files
27
+
28
+
29
+ def _load_provider_settings(
30
+ provider_config_path: Path | None,
31
+ ) -> tuple[dict[str, dict[str, Any]], dict[str, str]]:
32
+ """Load provider configs and optional source overrides from JSON file."""
33
+ if provider_config_path is None:
34
+ return {}, {}
35
+
36
+ try:
37
+ raw_data = json.loads(provider_config_path.read_text(encoding="utf-8"))
38
+ except Exception as exc:
39
+ raise click.ClickException(f"Failed to read provider config file: {exc}") from exc
40
+
41
+ if not isinstance(raw_data, dict):
42
+ raise click.ClickException("Provider config JSON must be an object")
43
+
44
+ provider_block = raw_data.get("providers", raw_data)
45
+ source_block = raw_data.get("sources", {})
46
+
47
+ provider_configs: dict[str, dict[str, Any]] = {}
48
+ if isinstance(provider_block, dict):
49
+ for key, value in provider_block.items():
50
+ if isinstance(value, dict):
51
+ provider_configs[str(key)] = value
52
+
53
+ provider_sources: dict[str, str] = {}
54
+ if isinstance(source_block, dict):
55
+ for key, value in source_block.items():
56
+ if isinstance(value, str):
57
+ provider_sources[str(key)] = value
58
+
59
+ return provider_configs, provider_sources
60
+
61
+
62
+ def display_drift_results(drifts: list[Any], fix: bool = False) -> None: # noqa: ARG001
63
+ """Display drift detection results in a formatted way."""
64
+ if not drifts:
65
+ console.print("[green]✓ No drift detected![/green]")
66
+ return
67
+
68
+ added: list[Any] = []
69
+ removed: list[Any] = []
70
+ modified: list[Any] = []
71
+
72
+ for drift in drifts:
73
+ drift_type_name = str(drift.drift_type)
74
+ if hasattr(drift.drift_type, "name"):
75
+ drift_type_name = str(drift.drift_type.name)
76
+ elif hasattr(drift.drift_type, "value"):
77
+ drift_type_name = str(drift.drift_type.value)
78
+
79
+ if "ADDED" in drift_type_name.upper() or drift_type_name == "added":
80
+ added.append(drift)
81
+ elif "REMOVED" in drift_type_name.upper() or drift_type_name == "removed":
82
+ removed.append(drift)
83
+ elif "MODIFIED" in drift_type_name.upper() or drift_type_name == "modified":
84
+ modified.append(drift)
85
+
86
+ console.print(
87
+ Panel(
88
+ f"[bold]Drift Detection Summary[/bold]\n\n"
89
+ f"[green]Added:[/green] {len(added)} resources\n"
90
+ f"[red]Removed:[/red] {len(removed)} resources\n"
91
+ f"[yellow]Modified:[/yellow] {len(modified)} resources\n"
92
+ f"[bold]Total:[/bold] {len(drifts)} drifted resources",
93
+ title="Drift Summary",
94
+ border_style="blue",
95
+ ),
96
+ )
97
+
98
+ if removed:
99
+ console.print("\n[bold red]Removed Resources:[/bold red]")
100
+ for drift in removed:
101
+ console.print(f" - {drift.resource_id} ({drift.resource_type})")
102
+ if drift.location:
103
+ console.print(f" Location: {drift.location.file_path}:{drift.location.line}")
104
+
105
+ if added:
106
+ console.print("\n[bold green]Added Resources:[/bold green]")
107
+ for drift in added:
108
+ console.print(f" - {drift.resource_id} ({drift.resource_type})")
109
+
110
+ if modified:
111
+ console.print("\n[bold yellow]Modified Resources:[/bold yellow]")
112
+ for drift in modified:
113
+ console.print(f" - {drift.resource_id} ({drift.resource_type})")
114
+ if drift.location:
115
+ console.print(f" Location: {drift.location.file_path}:{drift.location.line}")
116
+
117
+ if drift.attribute_drifts:
118
+ table = Table(show_header=True, header_style="bold", box=None)
119
+ table.add_column("Attribute", style="cyan")
120
+ table.add_column("Expected", style="green")
121
+ table.add_column("Actual", style="red")
122
+
123
+ for attr_name, attr_drift in drift.attribute_drifts.items():
124
+ table.add_row(
125
+ attr_name,
126
+ str(attr_drift.expected_value),
127
+ str(attr_drift.actual_value),
128
+ )
129
+
130
+ console.print(table)
131
+ console.print()
132
+
133
+
134
+ DEFAULT_LOCAL_STATE = Path(".nf.out") / "nf.tfstate"
135
+
136
+
137
+ def _load_drift_state(state_path: Path | None, *, use_state: bool) -> Any | None:
138
+ """The state drift detection refreshes resources from, or None to import everything.
139
+
140
+ ``--state`` names a Netherframe state file. Otherwise the project's configured backend
141
+ (.netherframe/backend.json) is used, then hybrid mode's default local state file.
142
+ """
143
+ if not use_state:
144
+ return None
145
+
146
+ from netherframe.core.backends.backend_config import BackendConfigManager
147
+ from netherframe.core.backends.backend_registry import BackendRegistry
148
+ from netherframe.core.backends.state_engine import LocalStateBackend
149
+
150
+ if state_path is not None:
151
+ source, backend = str(state_path), LocalStateBackend(state_path)
152
+ elif (config := BackendConfigManager.load_config()) is not None:
153
+ source = f"the {config.backend_type} backend in {BackendConfigManager.get_config_path()}"
154
+ if config.backend_type == "local" and not config.config.get("path"):
155
+ # Hybrid execution keeps local state here when no path is configured.
156
+ source, backend = f"{DEFAULT_LOCAL_STATE} ({source})", LocalStateBackend(DEFAULT_LOCAL_STATE)
157
+ else:
158
+ backend = BackendRegistry.create_state_backend(config.backend_type, config.config)
159
+ elif DEFAULT_LOCAL_STATE.is_file():
160
+ source, backend = str(DEFAULT_LOCAL_STATE), LocalStateBackend(DEFAULT_LOCAL_STATE)
161
+ else:
162
+ console.print("[dim]No state found; every resource is imported (use --state to name a state file).[/dim]")
163
+ return None
164
+
165
+ try:
166
+ state = backend.load()
167
+ except Exception as exc:
168
+ raise click.ClickException(f"Could not load state from {source}: {exc}") from exc
169
+ console.print(f"[dim]Refreshing resources found in state from {source} ({len(state.resources)} resources).[/dim]")
170
+ return state
171
+
172
+
173
+ def _detect_with_mode(
174
+ python_files: list[Path],
175
+ *,
176
+ filter_set: set[str] | None,
177
+ legacy: bool,
178
+ state_file: Path,
179
+ strict: bool,
180
+ allow_id_guessing: bool,
181
+ providers: tuple[str, ...],
182
+ provider_config: Path | None,
183
+ state_path: Path | None = None,
184
+ use_state: bool = True,
185
+ ) -> list[Any]:
186
+ """Run drift detection using selected mode and options."""
187
+ if legacy:
188
+ if not state_file.exists():
189
+ raise click.ClickException(f"Legacy state file not found: {state_file}")
190
+
191
+ from netherframe.core.drift import detect_legacy_drift
192
+
193
+ return detect_legacy_drift(python_files, state_file, filter_set)
194
+
195
+ provider_configs, provider_sources = _load_provider_settings(provider_config)
196
+
197
+ from netherframe.core.drift import detect_drift
198
+
199
+ target_paths: list[str | Path] = list(python_files)
200
+
201
+ return detect_drift(
202
+ target_paths,
203
+ filter_types=filter_set,
204
+ strict=strict,
205
+ allow_id_guessing=allow_id_guessing,
206
+ providers=providers or None,
207
+ provider_sources=provider_sources or None,
208
+ provider_configs=provider_configs or None,
209
+ state=_load_drift_state(state_path, use_state=use_state),
210
+ )
211
+
212
+
213
+ @click.group()
214
+ def drift() -> None:
215
+ """Drift detection and correction commands."""
216
+
217
+
218
+ @drift.command()
219
+ @click.argument("paths", nargs=-1, type=click.Path(exists=True, path_type=Path))
220
+ @click.option(
221
+ "--filter",
222
+ "-f",
223
+ "filter_types",
224
+ multiple=True,
225
+ help="Filter by resource type (e.g., aws_instance)",
226
+ )
227
+ @click.option(
228
+ "--legacy",
229
+ "-l",
230
+ is_flag=True,
231
+ help="Use legacy state file mode instead of live providers",
232
+ )
233
+ @click.option(
234
+ "--state-file",
235
+ type=click.Path(path_type=Path),
236
+ default="legacy.tfstate",
237
+ help="Legacy state file path",
238
+ )
239
+ @click.option(
240
+ "--strict/--no-strict",
241
+ default=True,
242
+ help="Fail detection if resources cannot be read",
243
+ )
244
+ @click.option(
245
+ "--allow-id-guessing",
246
+ is_flag=True,
247
+ help="Allow fallback guessing of import IDs when no explicit resolver matches",
248
+ )
249
+ @click.option(
250
+ "--provider",
251
+ "providers",
252
+ multiple=True,
253
+ help="Provider source or name (e.g., hashicorp/aws or aws). Repeatable.",
254
+ )
255
+ @click.option(
256
+ "--provider-config",
257
+ type=click.Path(exists=True, path_type=Path),
258
+ help="Path to JSON file with provider configuration",
259
+ )
260
+ @click.option(
261
+ "--state",
262
+ "state_path",
263
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
264
+ help="Netherframe state file; resources in it are refreshed from state instead of imported (default: the configured backend, or .nf.out/nf.tfstate)",
265
+ )
266
+ @click.option("--no-state", is_flag=True, help="Import every resource instead of refreshing from state")
267
+ def detect(
268
+ paths: tuple[Path, ...],
269
+ filter_types: tuple[str, ...],
270
+ legacy: bool,
271
+ state_file: Path,
272
+ strict: bool,
273
+ allow_id_guessing: bool,
274
+ providers: tuple[str, ...],
275
+ provider_config: Path | None,
276
+ state_path: Path | None,
277
+ no_state: bool,
278
+ ) -> None:
279
+ """Detect drift between code and actual infrastructure state.
280
+
281
+ Examples:
282
+ nf drift detect
283
+ nf drift detect src/
284
+ nf drift detect --legacy --state-file legacy.tfstate
285
+ nf drift detect -f aws_instance
286
+ nf drift detect --provider hashicorp/aws --provider-config providers.json
287
+ nf drift detect --state .nf.out/nf.tfstate
288
+ """
289
+ path_list = list(paths) if paths else [Path.cwd()]
290
+ python_files = find_python_files(path_list)
291
+ if not python_files:
292
+ console.print("[red]No Python files found in specified paths.[/red]")
293
+ sys.exit(1)
294
+
295
+ console.print(f"[bold blue]Detecting drift in {len(python_files)} files...[/bold blue]\n")
296
+ filter_set = set(filter_types) if filter_types else None
297
+
298
+ try:
299
+ drifts = _detect_with_mode(
300
+ python_files,
301
+ filter_set=filter_set,
302
+ legacy=legacy,
303
+ state_file=state_file,
304
+ strict=strict,
305
+ allow_id_guessing=allow_id_guessing,
306
+ providers=providers,
307
+ provider_config=provider_config,
308
+ state_path=state_path,
309
+ use_state=not no_state,
310
+ )
311
+
312
+ display_drift_results(drifts)
313
+ if drifts:
314
+ sys.exit(1)
315
+
316
+ except click.ClickException:
317
+ raise
318
+ except Exception as exc:
319
+ console.print(f"[bold red]Error detecting drift: {exc}[/bold red]")
320
+ raise click.ClickException(str(exc)) from exc
321
+
322
+
323
+ @drift.command()
324
+ @click.argument("paths", nargs=-1, type=click.Path(exists=True, path_type=Path))
325
+ @click.option("--filter", "-f", "filter_types", multiple=True, help="Filter by resource type")
326
+ @click.option("--legacy", "-l", is_flag=True, help="Use legacy state file mode")
327
+ @click.option(
328
+ "--state-file",
329
+ type=click.Path(path_type=Path),
330
+ default="legacy.tfstate",
331
+ help="Legacy state file path",
332
+ )
333
+ @click.option("--strict/--no-strict", default=True, help="Fail detection if resources cannot be read")
334
+ @click.option("--allow-id-guessing", is_flag=True, help="Allow fallback guessing of import IDs")
335
+ @click.option("--provider", "providers", multiple=True, help="Provider source or name. Repeatable.")
336
+ @click.option(
337
+ "--provider-config",
338
+ type=click.Path(exists=True, path_type=Path),
339
+ help="Path to JSON file with provider configuration",
340
+ )
341
+ @click.option("--dry-run", is_flag=True, help="Show what would be fixed without applying")
342
+ @click.option("--auto-approve", is_flag=True, help="Skip confirmation prompt")
343
+ @click.option(
344
+ "--state",
345
+ "state_path",
346
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
347
+ help="Netherframe state file; resources in it are refreshed from state instead of imported (default: the configured backend, or .nf.out/nf.tfstate)",
348
+ )
349
+ @click.option("--no-state", is_flag=True, help="Import every resource instead of refreshing from state")
350
+ def fix(
351
+ paths: tuple[Path, ...],
352
+ filter_types: tuple[str, ...],
353
+ legacy: bool,
354
+ state_file: Path,
355
+ strict: bool,
356
+ allow_id_guessing: bool,
357
+ providers: tuple[str, ...],
358
+ provider_config: Path | None,
359
+ state_path: Path | None,
360
+ no_state: bool,
361
+ dry_run: bool,
362
+ auto_approve: bool,
363
+ ) -> None:
364
+ """Fix detected drift by updating code to match actual state."""
365
+ path_list = list(paths) if paths else [Path.cwd()]
366
+ python_files = find_python_files(path_list)
367
+ if not python_files:
368
+ console.print("[red]No Python files found in specified paths.[/red]")
369
+ sys.exit(1)
370
+
371
+ console.print(f"[bold blue]Detecting drift in {len(python_files)} files...[/bold blue]\n")
372
+ filter_set = set(filter_types) if filter_types else None
373
+
374
+ try:
375
+ drifts = _detect_with_mode(
376
+ python_files,
377
+ filter_set=filter_set,
378
+ legacy=legacy,
379
+ state_file=state_file,
380
+ strict=strict,
381
+ allow_id_guessing=allow_id_guessing,
382
+ providers=providers,
383
+ provider_config=provider_config,
384
+ state_path=state_path,
385
+ use_state=not no_state,
386
+ )
387
+
388
+ if not drifts:
389
+ console.print("[green]✓ No drift detected![/green]")
390
+ return
391
+
392
+ display_drift_results(drifts)
393
+
394
+ if not dry_run and not auto_approve and not click.confirm("\nDo you want to fix these drifts?"):
395
+ console.print("[yellow]Fix cancelled.[/yellow]")
396
+ return
397
+
398
+ from netherframe.core.drift import fix_drift
399
+
400
+ patches = fix_drift(drifts, dry_run=dry_run)
401
+
402
+ if dry_run:
403
+ console.print("\n[bold]Patches that would be applied:[/bold]")
404
+ for patch in patches:
405
+ console.print(f"\n[cyan]File: {patch.file_path}[/cyan]")
406
+ console.print(f"[dim]Resource: {patch.resource_id}[/dim]")
407
+ console.print(f"[dim]{patch.description}[/dim]")
408
+ else:
409
+ console.print(f"\n[green]✓ Applied {len(patches)} drift patch(es)![/green]")
410
+
411
+ except click.ClickException:
412
+ raise
413
+ except Exception as exc:
414
+ console.print(f"[bold red]Error fixing drift: {exc}[/bold red]")
415
+ raise click.ClickException(str(exc)) from exc
416
+
417
+
418
+ @drift.command()
419
+ @click.argument("paths", nargs=-1, type=click.Path(exists=True, path_type=Path))
420
+ @click.option("--filter", "-f", "filter_types", multiple=True, help="Filter by resource type")
421
+ @click.option("--legacy", "-l", is_flag=True, help="Use legacy state file mode")
422
+ @click.option(
423
+ "--state-file",
424
+ type=click.Path(path_type=Path),
425
+ default="legacy.tfstate",
426
+ help="Legacy state file path",
427
+ )
428
+ @click.option("--strict/--no-strict", default=True, help="Fail detection if resources cannot be read")
429
+ @click.option("--allow-id-guessing", is_flag=True, help="Allow fallback guessing of import IDs")
430
+ @click.option("--provider", "providers", multiple=True, help="Provider source or name. Repeatable.")
431
+ @click.option(
432
+ "--provider-config",
433
+ type=click.Path(exists=True, path_type=Path),
434
+ help="Path to JSON file with provider configuration",
435
+ )
436
+ @click.option(
437
+ "--state",
438
+ "state_path",
439
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
440
+ help="Netherframe state file; resources in it are refreshed from state instead of imported (default: the configured backend, or .nf.out/nf.tfstate)",
441
+ )
442
+ @click.option("--no-state", is_flag=True, help="Import every resource instead of refreshing from state")
443
+ def check(
444
+ paths: tuple[Path, ...],
445
+ filter_types: tuple[str, ...],
446
+ legacy: bool,
447
+ state_file: Path,
448
+ strict: bool,
449
+ allow_id_guessing: bool,
450
+ providers: tuple[str, ...],
451
+ provider_config: Path | None,
452
+ state_path: Path | None,
453
+ no_state: bool,
454
+ ) -> None:
455
+ """Check if drift exists (useful for CI/CD).
456
+
457
+ Exit codes:
458
+ 0 - No drift detected
459
+ 1 - Drift detected
460
+ 2 - Error occurred
461
+ """
462
+ path_list = list(paths) if paths else [Path.cwd()]
463
+ python_files = find_python_files(path_list)
464
+ if not python_files:
465
+ console.print("[red]No Python files found in specified paths.[/red]")
466
+ sys.exit(2)
467
+
468
+ filter_set = set(filter_types) if filter_types else None
469
+
470
+ try:
471
+ drifts = _detect_with_mode(
472
+ python_files,
473
+ filter_set=filter_set,
474
+ legacy=legacy,
475
+ state_file=state_file,
476
+ strict=strict,
477
+ allow_id_guessing=allow_id_guessing,
478
+ providers=providers,
479
+ provider_config=provider_config,
480
+ state_path=state_path,
481
+ use_state=not no_state,
482
+ )
483
+
484
+ if drifts:
485
+ console.print(f"[red]✗ Drift detected: {len(drifts)} resources[/red]")
486
+ sys.exit(1)
487
+
488
+ console.print("[green]✓ No drift detected![/green]")
489
+ sys.exit(0)
490
+
491
+ except click.ClickException as exc:
492
+ console.print(f"[bold red]Error checking drift: {exc}[/bold red]")
493
+ sys.exit(2)
494
+ except Exception as exc:
495
+ console.print(f"[bold red]Error checking drift: {exc}[/bold red]")
496
+ sys.exit(2)
497
+
498
+
499
+ __all__ = ["drift"]
@@ -0,0 +1,130 @@
1
+ """Source file encoding helpers for NF CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import glob
6
+ import re
7
+ from pathlib import Path
8
+
9
+ import click
10
+
11
+ ENCODING_HEADER = "# coding: nf_autoid"
12
+ _ENCODING_RE = re.compile(r"^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)")
13
+ _GLOB_CHARS = set("*?[]")
14
+
15
+
16
+ def _read_source(path: Path) -> tuple[str, str]:
17
+ """Read a source file while preserving its newline style."""
18
+ with path.open("r", encoding="utf-8", newline="") as handle:
19
+ contents = handle.read()
20
+
21
+ newline = "\n"
22
+ if "\r\n" in contents:
23
+ newline = "\r\n"
24
+ return contents, newline
25
+
26
+
27
+ def _rewrite_with_autoid_header(
28
+ contents: str,
29
+ newline: str,
30
+ *,
31
+ force: bool,
32
+ ) -> tuple[str, bool, str]:
33
+ """Insert or normalize the nf_autoid coding cookie."""
34
+ lines = contents.splitlines(keepends=True)
35
+ insert_at = 1 if lines and lines[0].startswith("#!") else 0
36
+
37
+ for index, line in enumerate(lines[:2]):
38
+ match = _ENCODING_RE.match(line)
39
+ if not match:
40
+ continue
41
+ desired_line = f"{ENCODING_HEADER}{newline}"
42
+ if line == desired_line:
43
+ return contents, False, "already encoded"
44
+ if not force:
45
+ return contents, False, f"existing encoding preserved ({match.group(1)})"
46
+ lines[index] = desired_line
47
+ return "".join(lines), True, "encoding replaced"
48
+
49
+ lines.insert(insert_at, f"{ENCODING_HEADER}{newline}")
50
+ return "".join(lines), True, "encoding added"
51
+
52
+
53
+ def encode_file(path: Path, *, force: bool) -> tuple[bool, str]:
54
+ """Add the nf_autoid coding cookie to a single file."""
55
+ contents, newline = _read_source(path)
56
+ rewritten, changed, reason = _rewrite_with_autoid_header(
57
+ contents,
58
+ newline,
59
+ force=force,
60
+ )
61
+ if not changed:
62
+ return False, reason
63
+
64
+ with path.open("w", encoding="utf-8", newline="") as handle:
65
+ handle.write(rewritten)
66
+ return True, reason
67
+
68
+
69
+ def _expand_path_spec(spec: str) -> list[Path]:
70
+ """Expand a file, directory, or glob spec into Python source files."""
71
+ path = Path(spec)
72
+
73
+ if path.is_file():
74
+ return [path]
75
+
76
+ if path.is_dir():
77
+ return sorted(candidate for candidate in path.rglob("*.py") if candidate.is_file())
78
+
79
+ if any(char in spec for char in _GLOB_CHARS):
80
+ matches = sorted(Path(match) for match in glob.glob(spec, recursive=True))
81
+ expanded: list[Path] = []
82
+ for match in matches:
83
+ if match.is_file():
84
+ expanded.append(match)
85
+ elif match.is_dir():
86
+ expanded.extend(sorted(candidate for candidate in match.rglob("*.py") if candidate.is_file()))
87
+ return expanded
88
+
89
+ raise click.ClickException(f"No such file or directory: {spec}")
90
+
91
+
92
+ def _resolve_files(specs: tuple[str, ...]) -> list[Path]:
93
+ """Resolve user-provided path specs into a de-duplicated file list."""
94
+ resolved: list[Path] = []
95
+ seen: set[Path] = set()
96
+
97
+ for spec in specs:
98
+ matches = _expand_path_spec(spec)
99
+ if not matches:
100
+ raise click.ClickException(f"No Python files matched: {spec}")
101
+ for path in matches:
102
+ if path in seen:
103
+ continue
104
+ seen.add(path)
105
+ resolved.append(path)
106
+
107
+ return resolved
108
+
109
+
110
+ @click.command()
111
+ @click.option(
112
+ "--force",
113
+ is_flag=True,
114
+ help="Replace an existing encoding cookie instead of preserving it.",
115
+ )
116
+ @click.argument("files", nargs=-1, required=True)
117
+ def encode(files: tuple[str, ...], force: bool) -> None:
118
+ """Add the nf_autoid coding cookie to files, directories, or glob matches."""
119
+ resolved_files = _resolve_files(files)
120
+ updated = 0
121
+
122
+ for path in resolved_files:
123
+ changed, reason = encode_file(path, force=force)
124
+ if changed:
125
+ click.echo(f"encoded {path}")
126
+ updated += 1
127
+ else:
128
+ click.echo(f"unchanged {path} ({reason})")
129
+
130
+ click.echo(f"Processed {len(resolved_files)} file(s); updated {updated}.")