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,861 @@
1
+ """Generation-related commands for the NF CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import TypedDict
8
+
9
+ import click
10
+ from netherframe.generation.api import (
11
+ PROVIDER_SETS,
12
+ generate_functions,
13
+ generate_imports,
14
+ generate_provider,
15
+ get_provider_set,
16
+ )
17
+ from netherframe.generation.providers.schema_loading import SchemaLoading
18
+ from netherframe.cli.ui import console
19
+ from netherframe.core.logging import get_logger
20
+ from rich.table import Table
21
+
22
+ # Import provider batch utilities
23
+ from netherframe.cli.services.provider_batch import (
24
+ find_provider_config_file,
25
+ fetch_all_versions,
26
+ fetch_latest_version,
27
+ load_provider_config,
28
+ save_config_file,
29
+ )
30
+
31
+ logger = get_logger(__name__)
32
+
33
+ SCHEMA_LOADING_CHOICES = tuple(mode.value for mode in SchemaLoading)
34
+ SCHEMA_LOADING_TO_ENUM = {mode.value: mode for mode in SchemaLoading}
35
+
36
+
37
+ class ProviderGenerationConfig(TypedDict):
38
+ version: str
39
+ output_dir: str | None
40
+
41
+
42
+ def resolve_schema_loading(schema_loading: str | None) -> SchemaLoading | None:
43
+ """Resolve schema loading from CLI option."""
44
+ if not schema_loading:
45
+ return None
46
+ return SCHEMA_LOADING_TO_ENUM[schema_loading.lower()]
47
+
48
+
49
+ def parse_version_constraint(version_str: str) -> tuple[str, str | None]:
50
+ """Parse a version string to determine constraint type.
51
+
52
+ Returns:
53
+ Tuple of (constraint_type, pattern) where:
54
+ - constraint_type: "latest", "exact", or "wildcard"
55
+ - pattern: None for latest/exact, or the pattern with asterisks for wildcard
56
+
57
+ """
58
+ if version_str == "latest" or version_str == "*":
59
+ return ("latest", None)
60
+ if "*" in version_str:
61
+ return ("wildcard", version_str)
62
+ # Check if it's a complete semantic version (X.Y.Z)
63
+ parts = version_str.split(".")
64
+ if len(parts) == 3 and all(part.isdigit() for part in parts):
65
+ return ("exact", None) # Full version like "6.14.0" is exact
66
+ # Partial versions like "6.14" or "6" are treated as wildcards
67
+ return ("wildcard", version_str)
68
+
69
+
70
+ def version_matches_constraint(version: str, constraint: str) -> bool:
71
+ """Check if a version matches a wildcard constraint.
72
+
73
+ Args:
74
+ version: The version to check (e.g., "6.14.2")
75
+ constraint: The constraint pattern (e.g., "6.14.*")
76
+
77
+ Returns:
78
+ True if version matches the constraint
79
+
80
+ """
81
+ if "*" not in constraint:
82
+ # No explicit wildcard - treat partial versions as implicit wildcards
83
+ # "6.14" means "6.14.*" (matches any 6.14.x)
84
+ # "6" means "6.*" (matches any 6.x.x)
85
+ version_parts = version.split(".")
86
+ constraint_parts = constraint.split(".")
87
+
88
+ # Check if all constraint parts match the beginning of version
89
+ for i, constraint_part in enumerate(constraint_parts):
90
+ if i >= len(version_parts) or version_parts[i] != constraint_part:
91
+ return False
92
+ return True
93
+
94
+ # Explicit wildcard matching
95
+ version_parts = version.split(".")
96
+ constraint_parts = constraint.split(".")
97
+
98
+ # Check each part
99
+ for i, constraint_part in enumerate(constraint_parts):
100
+ if constraint_part == "*":
101
+ # Wildcard matches anything from this point
102
+ return True
103
+ if i >= len(version_parts) or version_parts[i] != constraint_part:
104
+ return False
105
+
106
+ return True
107
+
108
+
109
+ def find_latest_matching_version(provider_name: str, constraint: str) -> str | None:
110
+ """Find the latest version that matches a constraint.
111
+
112
+ Fetches all available versions and finds the latest one that matches.
113
+ """
114
+ logger.debug(
115
+ "Finding latest matching version for %s with constraint: %s",
116
+ provider_name,
117
+ constraint,
118
+ )
119
+
120
+ # First try the latest version as an optimization
121
+ latest = fetch_latest_version(provider_name)
122
+ if latest and version_matches_constraint(latest, constraint):
123
+ logger.debug("Latest version %s matches constraint %s", latest, constraint)
124
+ return latest
125
+
126
+ logger.debug(
127
+ "Latest version %s doesn't match constraint %s, fetching all versions...",
128
+ latest,
129
+ constraint,
130
+ )
131
+
132
+ # If the latest doesn't match, fetch all versions and find the best match
133
+ all_versions = fetch_all_versions(provider_name)
134
+ if not all_versions:
135
+ logger.warning("No versions found for provider %s", provider_name)
136
+ return None
137
+
138
+ logger.debug(
139
+ f"Found {len(all_versions)} versions for {provider_name}, checking for matches...",
140
+ )
141
+
142
+ # Find the latest version that matches the constraint
143
+ for version in all_versions:
144
+ if version_matches_constraint(version, constraint):
145
+ logger.debug("Found matching version: %s", version)
146
+ return version
147
+
148
+ logger.warning(
149
+ "No version matches constraint %s for provider %s",
150
+ constraint,
151
+ provider_name,
152
+ )
153
+ return None
154
+
155
+
156
+ @click.group()
157
+ def generate() -> None:
158
+ """Code generation utilities for Netherframe."""
159
+
160
+
161
+ @generate.command("providers")
162
+ @click.argument("provider_names", nargs=-1)
163
+ @click.option(
164
+ "--set",
165
+ "-s",
166
+ type=click.Choice(list(PROVIDER_SETS.keys()), case_sensitive=False),
167
+ help="Use a predefined set of providers",
168
+ )
169
+ @click.option(
170
+ "--config",
171
+ "-c",
172
+ type=click.Path(exists=True),
173
+ help="Load providers from config file (YAML, JSON, or TOML)",
174
+ )
175
+ @click.option(
176
+ "--output-dir",
177
+ default="providers",
178
+ help="Base output directory for provider packages",
179
+ )
180
+ @click.option(
181
+ "--version",
182
+ "provider_version",
183
+ default="latest",
184
+ help="Provider version to use for all providers",
185
+ )
186
+ @click.option("--binding-revision", type=click.IntRange(min=0), default=0, show_default=True, help="Binding revision appended to the Python package version; leaves the provider pin unchanged")
187
+ @click.option(
188
+ "--parallel",
189
+ "-p",
190
+ is_flag=True,
191
+ help="Generate providers in parallel",
192
+ )
193
+ @click.option(
194
+ "--clean",
195
+ is_flag=True,
196
+ help="Replace existing packages only after successful clean generation",
197
+ )
198
+ @click.option(
199
+ "--skip-formatting",
200
+ is_flag=True,
201
+ help="Skip code formatting for faster generation",
202
+ )
203
+ @click.option(
204
+ "--include-generated-at",
205
+ is_flag=True,
206
+ help="Include generation timestamps in README.md and pyproject.toml",
207
+ )
208
+ @click.option(
209
+ "--no-package",
210
+ is_flag=True,
211
+ help="Generate only code files without package structure",
212
+ )
213
+ @click.option(
214
+ "--schema-loading",
215
+ type=click.Choice(SCHEMA_LOADING_CHOICES, case_sensitive=False),
216
+ help="Schema loading strategy: disk (default) or memory",
217
+ )
218
+ @click.option(
219
+ "--verbose",
220
+ "-v",
221
+ is_flag=True,
222
+ help="Show detailed output",
223
+ )
224
+ @click.option(
225
+ "--yes",
226
+ "-y",
227
+ is_flag=True,
228
+ help="Skip confirmation prompts",
229
+ )
230
+ @click.option(
231
+ "--update-versions",
232
+ is_flag=True,
233
+ help="Update provider versions in config file to latest",
234
+ )
235
+ @click.option(
236
+ "--clear-cache",
237
+ is_flag=True,
238
+ help="Clear version cache before resolving",
239
+ )
240
+ def providers_cmd(
241
+ provider_names: tuple[str, ...],
242
+ set: str | None, # noqa: A002
243
+ config: str | None,
244
+ output_dir: str,
245
+ provider_version: str,
246
+ parallel: bool,
247
+ clean: bool,
248
+ skip_formatting: bool,
249
+ include_generated_at: bool,
250
+ binding_revision: int,
251
+ no_package: bool,
252
+ schema_loading: str | None,
253
+ verbose: bool,
254
+ yes: bool,
255
+ update_versions: bool,
256
+ clear_cache: bool,
257
+ ) -> None:
258
+ """Generate provider packages.
259
+
260
+ Examples:
261
+ nf generate providers hashicorp/aws
262
+ nf generate providers hashicorp/aws hashicorp/google
263
+ nf generate providers --set common
264
+ nf generate providers --set cloud --parallel
265
+ nf generate providers --config nf-providers.yaml
266
+ nf generate providers --config providers.toml --update-versions
267
+
268
+ Config file example (YAML):
269
+ providers:
270
+ - name: hashicorp/aws
271
+ version: "~> 5.0"
272
+ - name: hashicorp/google
273
+ version: "~> 4.0"
274
+
275
+ """
276
+ if binding_revision and no_package:
277
+ raise click.UsageError("--binding-revision requires package scaffolding; remove --no-package")
278
+
279
+ resolved_schema_loading = resolve_schema_loading(schema_loading)
280
+
281
+ # Clear cache if requested
282
+ if clear_cache:
283
+ import shutil
284
+
285
+ from netherframe.cli.services.provider_batch import version_cache_dir
286
+
287
+ cache_dir = version_cache_dir()
288
+ if cache_dir.exists():
289
+ shutil.rmtree(cache_dir)
290
+ console.print("[bold green]✓[/bold green] Version cache cleared")
291
+
292
+ # Config file handling
293
+ if config:
294
+ config_path = find_provider_config_file(config)
295
+ try:
296
+ config_data = load_provider_config(config_path)
297
+ except Exception as e:
298
+ console.print(f"[bold red]Error loading config:[/bold red] {e}")
299
+ sys.exit(1)
300
+
301
+ # Extract providers from config
302
+ config_providers = config_data.get("providers", [])
303
+ defaults = config_data.get("defaults", {})
304
+
305
+ if not config_providers:
306
+ console.print("[bold red]No providers defined in configuration.[/bold red]")
307
+ sys.exit(1)
308
+
309
+ # Update versions if requested
310
+ if update_versions:
311
+ console.print(
312
+ "\n[bold blue]Fetching latest provider versions...[/bold blue]",
313
+ )
314
+ updated = False
315
+
316
+ for i, provider in enumerate(config_providers):
317
+ if isinstance(provider, str):
318
+ provider_name = provider
319
+ current_version = defaults.get("version", "latest")
320
+ else:
321
+ provider_name = provider.get("name")
322
+ current_version = provider.get(
323
+ "version",
324
+ defaults.get("version", "latest"),
325
+ )
326
+
327
+ # Parse version constraint
328
+ constraint_type, pattern = parse_version_constraint(current_version)
329
+
330
+ if constraint_type == "latest":
331
+ # Already set to latest, skip
332
+ continue
333
+ if constraint_type == "exact":
334
+ # Exact version pin, don't update
335
+ console.print(
336
+ f" • {provider_name}: {current_version} [dim](pinned)[/dim]",
337
+ )
338
+ continue
339
+ # Wildcard constraint - find latest matching version
340
+ if pattern is None:
341
+ continue
342
+ latest = find_latest_matching_version(provider_name, pattern)
343
+ if latest and latest != current_version:
344
+ console.print(
345
+ f" • {provider_name}: {current_version} → {latest} [dim](constraint: {pattern})[/dim]",
346
+ )
347
+ if isinstance(provider, dict):
348
+ # Update to the latest matching version, keep the constraint pattern
349
+ provider["version"] = pattern # Keep the constraint, not the resolved version
350
+ else:
351
+ # Convert string to dict
352
+ config_providers[i] = {
353
+ "name": provider_name,
354
+ "version": pattern,
355
+ }
356
+ updated = True
357
+ else:
358
+ console.print(
359
+ f" • {provider_name}: {current_version} [dim](up to date)[/dim]",
360
+ )
361
+
362
+ if updated:
363
+ config_data["providers"] = config_providers
364
+ save_config_file(config_path, config_data)
365
+ console.print("[bold green]✓[/bold green] Config file updated")
366
+
367
+ # Build provider list from config
368
+ provider_list: list[str] = []
369
+ provider_configs: dict[str, ProviderGenerationConfig] = {}
370
+
371
+ for provider in config_providers:
372
+ if isinstance(provider, str):
373
+ provider_name = provider
374
+ provider_configs[provider_name] = {
375
+ "version": defaults.get("version", provider_version),
376
+ "output_dir": None,
377
+ }
378
+ else:
379
+ provider_name = provider.get("name")
380
+ if not isinstance(provider_name, str) or not provider_name:
381
+ raise click.ClickException("Provider config entries must include a name")
382
+ provider_configs[provider_name] = {
383
+ "version": str(
384
+ provider.get(
385
+ "version",
386
+ defaults.get("version", provider_version),
387
+ ),
388
+ ),
389
+ "output_dir": (str(provider.get("output_dir")) if provider.get("output_dir") is not None else None),
390
+ }
391
+ provider_list.append(provider_name)
392
+
393
+ console.print(
394
+ f"[bold blue]Loading {len(provider_list)} providers from config:[/bold blue]",
395
+ )
396
+ for p in provider_list:
397
+ version = provider_configs[p]["version"]
398
+ console.print(f" • {p} (version: {version})")
399
+
400
+ elif set:
401
+ provider_list = get_provider_set(set)
402
+ provider_configs: dict[str, ProviderGenerationConfig] = {p: {"version": provider_version, "output_dir": None} for p in provider_list}
403
+ console.print(f"[bold blue]Using provider set '{set}':[/bold blue]")
404
+ for p in provider_list:
405
+ console.print(f" • {p}")
406
+ elif provider_names:
407
+ provider_list = list(provider_names)
408
+ provider_configs: dict[str, ProviderGenerationConfig] = {p: {"version": provider_version, "output_dir": None} for p in provider_list}
409
+ else:
410
+ console.print(
411
+ "[bold red]Error:[/bold red] Specify provider names, use --set, or --config",
412
+ )
413
+ console.print("\nAvailable sets:")
414
+ for set_name in PROVIDER_SETS:
415
+ providers = get_provider_set(set_name)
416
+ console.print(f" • {set_name}: {len(providers)} providers")
417
+ console.print("\nOr use a config file with --config")
418
+ sys.exit(1)
419
+
420
+ # Confirm unless --yes
421
+ if not yes:
422
+ console.print(
423
+ f"\n[bold yellow]About to generate {len(provider_list)} providers[/bold yellow]",
424
+ )
425
+ if clean:
426
+ console.print(
427
+ "[bold yellow]--clean replaces existing packages after generation succeeds.[/bold yellow]",
428
+ )
429
+ if not click.confirm("\nContinue?"):
430
+ console.print("[yellow]Cancelled.[/yellow]")
431
+ return
432
+
433
+ # Resolve "latest" and wildcard versions before generation
434
+ needs_version_resolution = any(cfg["version"] == "latest" or "*" in cfg["version"] for cfg in provider_configs.values())
435
+
436
+ if needs_version_resolution:
437
+ console.print("\n[bold blue]Resolving versions...[/bold blue]")
438
+
439
+ # Collect providers that need resolution
440
+ providers_to_resolve = []
441
+ for provider_name, config_data in provider_configs.items():
442
+ version = config_data["version"]
443
+ constraint_type, pattern = parse_version_constraint(version)
444
+ if constraint_type == "latest":
445
+ providers_to_resolve.append((provider_name, "latest", None))
446
+ elif constraint_type == "wildcard":
447
+ providers_to_resolve.append((provider_name, "wildcard", pattern))
448
+
449
+ logger.info(f"Resolving versions for {len(providers_to_resolve)} providers")
450
+
451
+ # Resolve versions in parallel if we have multiple providers
452
+ if len(providers_to_resolve) > 1:
453
+ import concurrent.futures
454
+ import time
455
+
456
+ logger.debug("Using parallel version resolution with ThreadPoolExecutor")
457
+ resolution_start = time.time()
458
+
459
+ with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
460
+ # Submit all tasks
461
+ future_to_provider = {}
462
+ for provider_name, constraint_type, pattern in providers_to_resolve:
463
+ logger.trace(
464
+ f"Submitting resolution task for {provider_name} ({constraint_type})",
465
+ )
466
+ if constraint_type == "latest":
467
+ future = executor.submit(fetch_latest_version, provider_name)
468
+ else: # wildcard
469
+ if pattern is None:
470
+ continue
471
+ future = executor.submit(
472
+ find_latest_matching_version,
473
+ provider_name,
474
+ pattern,
475
+ )
476
+ future_to_provider[future] = (
477
+ provider_name,
478
+ constraint_type,
479
+ pattern,
480
+ )
481
+
482
+ logger.debug(f"Submitted {len(future_to_provider)} resolution tasks")
483
+
484
+ # Process results as they complete
485
+ completed = 0
486
+ for future in concurrent.futures.as_completed(future_to_provider):
487
+ completed += 1
488
+ provider_name, constraint_type, pattern = future_to_provider[future]
489
+ try:
490
+ result = future.result()
491
+ elapsed = time.time() - resolution_start
492
+ logger.debug(
493
+ f"Resolved {provider_name} ({completed}/{len(providers_to_resolve)}) after {elapsed:.2f}s",
494
+ )
495
+
496
+ if result:
497
+ provider_configs[provider_name]["version"] = result
498
+ if constraint_type == "latest":
499
+ console.print(f" • {provider_name}: latest → {result}")
500
+ else:
501
+ console.print(
502
+ f" • {provider_name}: {pattern} → {result}",
503
+ )
504
+ elif constraint_type == "latest":
505
+ console.print(
506
+ f" [yellow]• {provider_name}: Failed to resolve latest version, using 'latest'[/yellow]",
507
+ )
508
+ else:
509
+ console.print(
510
+ f" [yellow]• {provider_name}: {pattern} (no matching version found, keeping constraint)[/yellow]",
511
+ )
512
+ if pattern is not None:
513
+ provider_configs[provider_name]["version"] = pattern
514
+ except Exception as e:
515
+ logger.error(
516
+ "Error resolving version for %s: %s",
517
+ provider_name,
518
+ e,
519
+ )
520
+ console.print(
521
+ f" [yellow]• {provider_name}: Error resolving version: {e}[/yellow]",
522
+ )
523
+ if constraint_type == "wildcard" and pattern is not None:
524
+ provider_configs[provider_name]["version"] = pattern
525
+
526
+ total_time = time.time() - resolution_start
527
+ logger.info(f"Resolved all versions in {total_time:.2f}s")
528
+ else:
529
+ # Single provider - resolve sequentially
530
+ for provider_name, constraint_type, pattern in providers_to_resolve:
531
+ if constraint_type == "latest":
532
+ actual_version = fetch_latest_version(provider_name)
533
+ if actual_version:
534
+ provider_configs[provider_name]["version"] = actual_version
535
+ console.print(f" • {provider_name}: latest → {actual_version}")
536
+ else:
537
+ console.print(
538
+ f" [yellow]• {provider_name}: Failed to resolve latest version, using 'latest'[/yellow]",
539
+ )
540
+ elif constraint_type == "wildcard":
541
+ if pattern is None:
542
+ continue
543
+ # For wildcards, resolve to the latest matching version
544
+ latest_matching = find_latest_matching_version(
545
+ provider_name,
546
+ pattern,
547
+ )
548
+ if latest_matching:
549
+ provider_configs[provider_name]["version"] = latest_matching
550
+ console.print(
551
+ f" • {provider_name}: {pattern} → {latest_matching}",
552
+ )
553
+ else:
554
+ # If we can't find a matching version, keep the constraint
555
+ console.print(
556
+ f" [yellow]• {provider_name}: {pattern} (no matching version found, keeping constraint)[/yellow]",
557
+ )
558
+ # Keep the original constraint pattern
559
+ provider_configs[provider_name]["version"] = pattern
560
+
561
+ console.print(
562
+ f"\n[bold green]Generating {len(provider_list)} providers...[/bold green]",
563
+ )
564
+ if resolved_schema_loading:
565
+ console.print(f"[dim]Schema loading: {resolved_schema_loading.value}[/dim]")
566
+
567
+ # Add timing for generation phase
568
+ import time as timing_module
569
+
570
+ generation_start = timing_module.time()
571
+ logger.info(f"Starting provider generation for {len(provider_list)} providers")
572
+
573
+ # Generate providers with specific configs
574
+ results = {}
575
+
576
+ if parallel:
577
+ # Parallel generation
578
+ import concurrent.futures
579
+
580
+ def generate_single(provider_name: str) -> tuple[str, bool]:
581
+ """Generate a single provider."""
582
+ provider_start = timing_module.time()
583
+ logger.debug("Starting generation of %s", provider_name)
584
+
585
+ provider_config = provider_configs[provider_name]
586
+ provider_version_value = provider_config["version"]
587
+
588
+ # Parse provider name
589
+ if "/" in provider_name:
590
+ org, short = provider_name.split("/", 1)
591
+ else:
592
+ org = "hashicorp"
593
+ short = provider_name
594
+
595
+ # Determine output directory
596
+ if provider_config["output_dir"]:
597
+ provider_output = provider_config["output_dir"]
598
+ else:
599
+ provider_output = Path(output_dir) / org / short
600
+
601
+ try:
602
+ exit_code = generate_provider(
603
+ provider_name=provider_name,
604
+ output_dir=str(provider_output),
605
+ provider_version=provider_version_value,
606
+ schema_loading=resolved_schema_loading,
607
+ create_package=not no_package,
608
+ verbose=verbose,
609
+ clean=clean,
610
+ skip_formatting=skip_formatting,
611
+ include_generated_at=include_generated_at,
612
+ binding_revision=binding_revision,
613
+ )
614
+ provider_time = timing_module.time() - provider_start
615
+ logger.info(f"Generated {provider_name} in {provider_time:.2f}s")
616
+ return provider_name, exit_code == 0
617
+ except Exception as e:
618
+ provider_time = timing_module.time() - provider_start
619
+ logger.error(
620
+ f"Failed to generate {provider_name} after {provider_time:.2f}s: {e}",
621
+ )
622
+ return provider_name, False
623
+
624
+ logger.debug("Creating ThreadPoolExecutor for parallel generation")
625
+ with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
626
+ futures = {executor.submit(generate_single, name): name for name in provider_list}
627
+
628
+ logger.debug(f"Submitted {len(futures)} generation tasks to executor")
629
+
630
+ completed = 0
631
+ for future in concurrent.futures.as_completed(futures):
632
+ completed += 1
633
+ provider_name, success = future.result()
634
+ results[provider_name] = success
635
+ elapsed = timing_module.time() - generation_start
636
+ logger.debug(
637
+ f"Completed {completed}/{len(futures)} providers after {elapsed:.2f}s total",
638
+ )
639
+ else:
640
+ # Sequential generation
641
+ for provider_name in provider_list:
642
+ provider_config = provider_configs[provider_name]
643
+ provider_version_value = provider_config["version"]
644
+
645
+ console.print(f"\n[bold blue]Generating {provider_name}...[/bold blue]")
646
+
647
+ # Parse provider name
648
+ if "/" in provider_name:
649
+ org, short = provider_name.split("/", 1)
650
+ else:
651
+ org = "hashicorp"
652
+ short = provider_name
653
+
654
+ # Determine output directory
655
+ if provider_config["output_dir"]:
656
+ provider_output = provider_config["output_dir"]
657
+ else:
658
+ provider_output = Path(output_dir) / org / short
659
+
660
+ try:
661
+ exit_code = generate_provider(
662
+ provider_name=provider_name,
663
+ output_dir=str(provider_output),
664
+ provider_version=provider_version_value,
665
+ schema_loading=resolved_schema_loading,
666
+ create_package=not no_package,
667
+ verbose=verbose,
668
+ clean=clean,
669
+ skip_formatting=skip_formatting,
670
+ include_generated_at=include_generated_at,
671
+ binding_revision=binding_revision,
672
+ )
673
+ results[provider_name] = exit_code == 0
674
+ except Exception as e:
675
+ console.print(f"[bold red]✗[/bold red] {provider_name} failed: {e}")
676
+ results[provider_name] = False
677
+
678
+ # Log generation completion time
679
+ generation_time = timing_module.time() - generation_start
680
+ logger.info(f"All provider generation completed in {generation_time:.2f}s")
681
+
682
+ # Show results
683
+ success_count = sum(1 for success in results.values() if success)
684
+ console.print(
685
+ f"\n[bold]Results:[/bold] {success_count}/{len(provider_list)} successful",
686
+ )
687
+
688
+ if success_count < len(provider_list):
689
+ console.print("\n[bold red]Failed providers:[/bold red]")
690
+ for provider, success in results.items():
691
+ if not success:
692
+ console.print(f" • {provider}")
693
+ logger.info("Exiting with failure due to failed providers")
694
+ sys.exit(1)
695
+ else:
696
+ console.print(
697
+ "\n[bold green]✓ All providers generated successfully![/bold green]",
698
+ )
699
+ logger.info("All providers generated successfully, command complete")
700
+
701
+
702
+ @generate.command("functions")
703
+ @click.option(
704
+ "--legacy-binary",
705
+ default="terraform",
706
+ show_default=True,
707
+ help="Legacy binary to introspect (for example: terraform or tofu)",
708
+ )
709
+ @click.option(
710
+ "-o",
711
+ "--output",
712
+ help="Output file path",
713
+ )
714
+ @click.option(
715
+ "--dry-run",
716
+ is_flag=True,
717
+ help="Print generated code without writing",
718
+ )
719
+ def functions_cmd(legacy_binary: str, output: str | None, dry_run: bool) -> None:
720
+ """Generate Terraform/OpenTofu functions.
721
+
722
+ Examples:
723
+ nf generate functions
724
+ nf generate functions --legacy-binary tofu
725
+ nf generate functions --dry-run
726
+
727
+ """
728
+ console.print(
729
+ f"[bold blue]Generating functions from {legacy_binary} metadata...[/bold blue]",
730
+ )
731
+
732
+ try:
733
+ result = generate_functions(
734
+ output_path=output,
735
+ legacy_binary=legacy_binary,
736
+ dry_run=dry_run,
737
+ )
738
+
739
+ if dry_run:
740
+ console.print("\n[bold]Generated code:[/bold]")
741
+ console.print("─" * 60)
742
+ print(result)
743
+ console.print("─" * 60)
744
+ console.print("\n[dim]Dry run complete. No files written.[/dim]")
745
+ else:
746
+ console.print(
747
+ "[bold green]✓[/bold green] Functions generated successfully!",
748
+ )
749
+ if output:
750
+ console.print(f"[dim]Output: {output}[/dim]")
751
+
752
+ except Exception as e:
753
+ console.print(f"[bold red]✗[/bold red] Error: {e}")
754
+ sys.exit(1)
755
+
756
+
757
+ @generate.command("imports")
758
+ @click.argument("state_file", type=click.Path(exists=True))
759
+ @click.option(
760
+ "-o",
761
+ "--output",
762
+ default="imports.json",
763
+ help="Output file for import configuration",
764
+ )
765
+ @click.option(
766
+ "--resource-types",
767
+ multiple=True,
768
+ help="Only import these resource types",
769
+ )
770
+ @click.option(
771
+ "--exclude-types",
772
+ multiple=True,
773
+ help="Exclude these resource types",
774
+ )
775
+ @click.option(
776
+ "--stack-name",
777
+ default="imported",
778
+ help="Name for the generated stack",
779
+ )
780
+ @click.option(
781
+ "--dry-run",
782
+ is_flag=True,
783
+ help="Show what would be imported without writing",
784
+ )
785
+ def imports_cmd(
786
+ state_file: str,
787
+ output: str,
788
+ resource_types: tuple[str, ...],
789
+ exclude_types: tuple[str, ...],
790
+ stack_name: str,
791
+ dry_run: bool,
792
+ ) -> None:
793
+ """Generate import configuration from Terraform state.
794
+
795
+ Examples:
796
+ nf generate imports terraform.tfstate
797
+ nf generate imports state.json --resource-types aws_instance
798
+ nf generate imports state.json --exclude-types aws_iam_role
799
+
800
+ """
801
+ console.print(f"[bold blue]Analyzing state file: {state_file}[/bold blue]")
802
+
803
+ try:
804
+ result = generate_imports(
805
+ state_file=state_file,
806
+ output_file=output,
807
+ resource_types=list(resource_types) if resource_types else None,
808
+ exclude_types=list(exclude_types) if exclude_types else None,
809
+ stack_name=stack_name,
810
+ dry_run=dry_run,
811
+ )
812
+
813
+ if dry_run:
814
+ from netherframe.core.serialization import orjson_compat as json
815
+
816
+ console.print("\n[bold]Import configuration:[/bold]")
817
+ console.print(json.dumps(result, indent=2))
818
+ console.print("\n[dim]Dry run complete. No files written.[/dim]")
819
+ else:
820
+ console.print(
821
+ f"[bold green]✓[/bold green] Import configuration written to: {output}",
822
+ )
823
+
824
+ except Exception as e:
825
+ console.print(f"[bold red]✗[/bold red] Error: {e}")
826
+ sys.exit(1)
827
+
828
+
829
+ @generate.command("list-sets")
830
+ def list_sets() -> None:
831
+ """List available provider sets."""
832
+ table = Table(title="Available Provider Sets")
833
+ table.add_column("Set Name", style="cyan")
834
+ table.add_column("Providers", style="green")
835
+ table.add_column("Count", style="yellow")
836
+
837
+ for set_name in sorted(PROVIDER_SETS.keys()):
838
+ providers = get_provider_set(set_name)
839
+ table.add_row(
840
+ set_name,
841
+ ", ".join(providers[:3]) + ("..." if len(providers) > 3 else ""),
842
+ str(len(providers)),
843
+ )
844
+
845
+ console.print(table)
846
+
847
+
848
+ @generate.command("example-config")
849
+ @click.option(
850
+ "--format",
851
+ "-f",
852
+ "config_format",
853
+ type=click.Choice(["yaml", "json", "toml", "all"], case_sensitive=False),
854
+ default="all",
855
+ help="Format for example configuration files (default: all)",
856
+ )
857
+ def create_config(config_format: str) -> None:
858
+ """Create example provider configuration files in various formats."""
859
+ from netherframe.cli.services.provider_batch import create_starter_specs
860
+
861
+ create_starter_specs(config_format)