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.
- netherframe/cli/__init__.py +1 -0
- netherframe/cli/__main__.py +4 -0
- netherframe/cli/commands/__init__.py +93 -0
- netherframe/cli/commands/backend.py +305 -0
- netherframe/cli/commands/config_command.py +98 -0
- netherframe/cli/commands/convert.py +40 -0
- netherframe/cli/commands/discover.py +679 -0
- netherframe/cli/commands/drift.py +499 -0
- netherframe/cli/commands/encode.py +130 -0
- netherframe/cli/commands/generation.py +861 -0
- netherframe/cli/commands/graph_state.py +439 -0
- netherframe/cli/commands/hybrid.py +461 -0
- netherframe/cli/commands/idiff.py +493 -0
- netherframe/cli/commands/infrastructure.py +1182 -0
- netherframe/cli/commands/init_command.py +11 -0
- netherframe/cli/commands/lint.py +49 -0
- netherframe/cli/commands/providers.py +315 -0
- netherframe/cli/commands/shell_command.py +17 -0
- netherframe/cli/commands/skill.py +167 -0
- netherframe/cli/commands/synthesis.py +732 -0
- netherframe/cli/commands/terraform_command.py +17 -0
- netherframe/cli/commands/watch_command.py +117 -0
- netherframe/cli/entrypoint.py +18 -0
- netherframe/cli/logging.py +33 -0
- netherframe/cli/main.py +177 -0
- netherframe/cli/options.py +32 -0
- netherframe/cli/py.typed +0 -0
- netherframe/cli/services/__init__.py +1 -0
- netherframe/cli/services/app_loader.py +62 -0
- netherframe/cli/services/app_resolver.py +205 -0
- netherframe/cli/services/graph_onboarding.py +144 -0
- netherframe/cli/services/legacy_cli.py +51 -0
- netherframe/cli/services/project_config.py +107 -0
- netherframe/cli/services/provider_batch.py +620 -0
- netherframe/cli/services/stack_inventory.py +342 -0
- netherframe/cli/skills/netherframe/SKILL.md +53 -0
- netherframe/cli/skills/netherframe/agents/openai.yaml +3 -0
- netherframe/cli/skills/netherframe/references/authoring.md +77 -0
- netherframe/cli/skills/netherframe/references/execution.md +70 -0
- netherframe/cli/skills/netherframe/references/migration.md +69 -0
- netherframe/cli/state_migration.py +111 -0
- netherframe/cli/tui/__init__.py +1 -0
- netherframe/cli/tui/plan_filters.py +200 -0
- netherframe/cli/tui/plan_models.py +51 -0
- netherframe/cli/tui/plan_viewer.py +745 -0
- netherframe/cli/ui.py +25 -0
- netherframe_cli-0.2.1.dist-info/METADATA +86 -0
- netherframe_cli-0.2.1.dist-info/RECORD +92 -0
- netherframe_cli-0.2.1.dist-info/WHEEL +4 -0
- netherframe_cli-0.2.1.dist-info/entry_points.txt +3 -0
- netherframe_cli-0.2.1.dist-info/licenses/LICENSE +21 -0
- nf/cli/__init__.py +4 -0
- nf/cli/__main__.py +4 -0
- nf/cli/commands/__init__.py +4 -0
- nf/cli/commands/backend.py +4 -0
- nf/cli/commands/config_command.py +4 -0
- nf/cli/commands/convert.py +4 -0
- nf/cli/commands/discover.py +4 -0
- nf/cli/commands/drift.py +4 -0
- nf/cli/commands/encode.py +4 -0
- nf/cli/commands/generation.py +4 -0
- nf/cli/commands/graph_state.py +4 -0
- nf/cli/commands/hybrid.py +4 -0
- nf/cli/commands/idiff.py +4 -0
- nf/cli/commands/infrastructure.py +4 -0
- nf/cli/commands/init_command.py +4 -0
- nf/cli/commands/lint.py +4 -0
- nf/cli/commands/providers.py +4 -0
- nf/cli/commands/shell_command.py +4 -0
- nf/cli/commands/skill.py +4 -0
- nf/cli/commands/synthesis.py +4 -0
- nf/cli/commands/terraform_command.py +4 -0
- nf/cli/commands/watch_command.py +4 -0
- nf/cli/entrypoint.py +4 -0
- nf/cli/logging.py +4 -0
- nf/cli/main.py +4 -0
- nf/cli/options.py +4 -0
- nf/cli/py.typed +0 -0
- nf/cli/services/__init__.py +4 -0
- nf/cli/services/app_loader.py +4 -0
- nf/cli/services/app_resolver.py +4 -0
- nf/cli/services/graph_onboarding.py +4 -0
- nf/cli/services/legacy_cli.py +4 -0
- nf/cli/services/project_config.py +4 -0
- nf/cli/services/provider_batch.py +4 -0
- nf/cli/services/stack_inventory.py +4 -0
- nf/cli/state_migration.py +4 -0
- nf/cli/tui/__init__.py +4 -0
- nf/cli/tui/plan_filters.py +4 -0
- nf/cli/tui/plan_models.py +4 -0
- nf/cli/tui/plan_viewer.py +4 -0
- nf/cli/ui.py +4 -0
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
"""Batch provider generation support."""
|
|
2
|
+
|
|
3
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
import tomllib
|
|
7
|
+
from datetime import datetime, timedelta, UTC
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
import tomli_w
|
|
13
|
+
import urllib3
|
|
14
|
+
from netherframe.cli.ui import console
|
|
15
|
+
|
|
16
|
+
# Simple in-memory cache for version lookups during a single session
|
|
17
|
+
_version_cache: dict[str, str | None] = {}
|
|
18
|
+
_all_versions_cache: dict[str, list[str] | None] = {}
|
|
19
|
+
# Bare provider name -> the "namespace/name" the registry resolves it to
|
|
20
|
+
_source_cache: dict[str, str] = {}
|
|
21
|
+
|
|
22
|
+
REGISTRY_URL = "https://registry.terraform.io"
|
|
23
|
+
|
|
24
|
+
# File-based cache for persistent storage across runs
|
|
25
|
+
CACHE_DIR_ENV = "NF_PROVIDER_VERSION_CACHE_DIR"
|
|
26
|
+
_CACHE_EXPIRY_HOURS = 24 # Cache provider versions for 24 hours
|
|
27
|
+
DEFAULT_PROVIDER_CONFIG_FILES = (
|
|
28
|
+
"nf-providers.yaml",
|
|
29
|
+
"nf-providers.yml",
|
|
30
|
+
"nf-providers.json",
|
|
31
|
+
"nf-providers.toml",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# Create a global connection pool for better performance
|
|
35
|
+
# Note: maxsize should be higher than the number of parallel workers to avoid contention
|
|
36
|
+
_http_pool = urllib3.PoolManager(
|
|
37
|
+
num_pools=20, # Number of connection pools to cache (increased for parallel operations)
|
|
38
|
+
maxsize=50, # Maximum number of connections per pool (increased to prevent blocking)
|
|
39
|
+
block=False, # Don't block when pool is full, create new connections
|
|
40
|
+
timeout=urllib3.Timeout(connect=5.0, read=10.0),
|
|
41
|
+
headers={
|
|
42
|
+
"User-Agent": "Netherframe/1.0",
|
|
43
|
+
"Accept": "application/json",
|
|
44
|
+
},
|
|
45
|
+
retries=urllib3.Retry(
|
|
46
|
+
total=3,
|
|
47
|
+
backoff_factor=0.3,
|
|
48
|
+
status_forcelist=[500, 502, 503, 504],
|
|
49
|
+
),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def version_cache_dir() -> Path:
|
|
54
|
+
"""The provider version cache: ``$NF_PROVIDER_VERSION_CACHE_DIR``, else ``~/.cache/nf/provider-versions``.
|
|
55
|
+
|
|
56
|
+
The variable is read on every use, so setting it redirects the cache however early this
|
|
57
|
+
module was imported.
|
|
58
|
+
"""
|
|
59
|
+
return Path(os.environ.get(CACHE_DIR_ENV) or Path.home() / ".cache" / "nf" / "provider-versions").expanduser()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _get_cache_file(provider_name: str, cache_type: str) -> Path:
|
|
63
|
+
"""Get the cache file path for a provider."""
|
|
64
|
+
cache_dir = version_cache_dir()
|
|
65
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
# Replace / with - for filesystem safety
|
|
67
|
+
safe_name = provider_name.replace("/", "-")
|
|
68
|
+
return cache_dir / f"{safe_name}.{cache_type}.json"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _is_cache_valid(cache_file: Path) -> bool:
|
|
72
|
+
"""Check if a cache file is still valid."""
|
|
73
|
+
if not cache_file.exists():
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
# Check if cache is expired
|
|
77
|
+
mtime = datetime.fromtimestamp(cache_file.stat().st_mtime, tz=UTC)
|
|
78
|
+
age = datetime.now(tz=UTC) - mtime
|
|
79
|
+
return age < timedelta(hours=_CACHE_EXPIRY_HOURS)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _load_from_cache(provider_name: str, cache_type: str) -> Any:
|
|
83
|
+
"""Load data from file cache if valid."""
|
|
84
|
+
cache_file = _get_cache_file(provider_name, cache_type)
|
|
85
|
+
if _is_cache_valid(cache_file):
|
|
86
|
+
try:
|
|
87
|
+
with cache_file.open("r") as f:
|
|
88
|
+
return json.load(f)
|
|
89
|
+
except Exception:
|
|
90
|
+
# If cache is corrupted, delete it
|
|
91
|
+
cache_file.unlink(missing_ok=True)
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _save_to_cache(provider_name: str, cache_type: str, data: Any) -> None:
|
|
96
|
+
"""Save data to file cache."""
|
|
97
|
+
cache_file = _get_cache_file(provider_name, cache_type)
|
|
98
|
+
try:
|
|
99
|
+
with cache_file.open("w") as f:
|
|
100
|
+
json.dump(data, f)
|
|
101
|
+
except Exception:
|
|
102
|
+
# Non-critical, just log if needed
|
|
103
|
+
pass
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def load_provider_config(config_file: Path) -> dict[str, Any]:
|
|
107
|
+
"""Load provider configuration from YAML, JSON, or TOML file."""
|
|
108
|
+
content = config_file.read_text()
|
|
109
|
+
|
|
110
|
+
if config_file.suffix.lower() in [".yaml", ".yml"]:
|
|
111
|
+
try:
|
|
112
|
+
import yaml
|
|
113
|
+
|
|
114
|
+
return yaml.safe_load(content)
|
|
115
|
+
except ImportError as e:
|
|
116
|
+
console.print(
|
|
117
|
+
"[bold red]YAML support requires PyYAML. Install with: pip install pyyaml[/bold red]",
|
|
118
|
+
)
|
|
119
|
+
raise click.ClickException("PyYAML not installed") from e
|
|
120
|
+
elif config_file.suffix.lower() == ".json":
|
|
121
|
+
return json.loads(content)
|
|
122
|
+
elif config_file.suffix.lower() == ".toml":
|
|
123
|
+
data = tomllib.loads(content)
|
|
124
|
+
|
|
125
|
+
# Handle TOML special case: merge providers from root and defaults
|
|
126
|
+
root_providers = data.get("providers", [])
|
|
127
|
+
default_providers = data.get("defaults", {}).get("providers", [])
|
|
128
|
+
|
|
129
|
+
if root_providers and default_providers:
|
|
130
|
+
# Merge both arrays, root providers take precedence
|
|
131
|
+
# First, create a map of root providers by name for easy lookup
|
|
132
|
+
root_provider_map = {}
|
|
133
|
+
for provider in root_providers:
|
|
134
|
+
if isinstance(provider, dict):
|
|
135
|
+
root_provider_map[provider.get("name")] = provider
|
|
136
|
+
else:
|
|
137
|
+
root_provider_map[provider] = provider
|
|
138
|
+
|
|
139
|
+
# Add providers from defaults that aren't in root
|
|
140
|
+
merged_providers = list(root_providers)
|
|
141
|
+
for provider in default_providers:
|
|
142
|
+
provider_name = provider.get("name") if isinstance(provider, dict) else provider
|
|
143
|
+
if provider_name not in root_provider_map:
|
|
144
|
+
merged_providers.append(provider)
|
|
145
|
+
|
|
146
|
+
data["providers"] = merged_providers
|
|
147
|
+
if "defaults" in data and "providers" in data["defaults"]:
|
|
148
|
+
del data["defaults"]["providers"]
|
|
149
|
+
elif default_providers and not root_providers:
|
|
150
|
+
# Move defaults.providers to root if no root providers exist
|
|
151
|
+
data["providers"] = default_providers
|
|
152
|
+
if "defaults" in data and "providers" in data["defaults"]:
|
|
153
|
+
del data["defaults"]["providers"]
|
|
154
|
+
|
|
155
|
+
return data
|
|
156
|
+
else:
|
|
157
|
+
raise click.ClickException(
|
|
158
|
+
f"Unsupported config file format: {config_file.suffix}",
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def find_provider_config_file(config_file: str | Path | None) -> Path:
|
|
163
|
+
"""Resolve an explicit provider config path or discover a default one."""
|
|
164
|
+
if config_file is not None:
|
|
165
|
+
return Path(config_file)
|
|
166
|
+
|
|
167
|
+
for filename in DEFAULT_PROVIDER_CONFIG_FILES:
|
|
168
|
+
candidate = Path(filename)
|
|
169
|
+
if candidate.exists():
|
|
170
|
+
console.print(f"[dim]Using config file: {candidate}[/dim]")
|
|
171
|
+
return candidate
|
|
172
|
+
|
|
173
|
+
console.print("[bold red]No configuration file found.[/bold red]")
|
|
174
|
+
console.print("Create nf-providers.yaml or specify with --config")
|
|
175
|
+
raise click.ClickException("No config file")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def create_example_config() -> None:
|
|
179
|
+
"""Create an example configuration file."""
|
|
180
|
+
example_config = """# NF Provider Generation Configuration
|
|
181
|
+
|
|
182
|
+
defaults:
|
|
183
|
+
version: latest
|
|
184
|
+
output_base: providers
|
|
185
|
+
|
|
186
|
+
providers:
|
|
187
|
+
# Simple format - uses defaults
|
|
188
|
+
- hashicorp/aws
|
|
189
|
+
- hashicorp/google
|
|
190
|
+
- hashicorp/azurerm
|
|
191
|
+
|
|
192
|
+
# Detailed format - override defaults
|
|
193
|
+
- name: keycloak/keycloak
|
|
194
|
+
version: "~> 4.0"
|
|
195
|
+
output_dir: providers/custom/keycloak
|
|
196
|
+
|
|
197
|
+
- name: hashicorp/random
|
|
198
|
+
version: "~> 3.0"
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
Path("nf-providers.yaml.example").write_text(example_config)
|
|
202
|
+
|
|
203
|
+
console.print(
|
|
204
|
+
"[bold green]Created example configuration: nf-providers.yaml.example[/bold green]",
|
|
205
|
+
)
|
|
206
|
+
console.print("Rename to nf-providers.yaml and customize for your needs.")
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class ProviderNameError(click.ClickException):
|
|
210
|
+
"""A bare provider name the registry does not resolve to exactly one provider."""
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def resolve_registry_source(provider_name: str) -> str:
|
|
214
|
+
"""The ``namespace/name`` a provider name means on the Terraform registry.
|
|
215
|
+
|
|
216
|
+
A source address (``keycloak/keycloak``) names its namespace itself. A bare name (``aws``)
|
|
217
|
+
does not, so the registry is asked the way Terraform asks it about an unqualified name
|
|
218
|
+
(``/v1/providers/-/<name>/versions``, which knows only hashicorp's providers). A name it does
|
|
219
|
+
not know (``keycloak``), or whose provider it reports moved to another namespace (``github``
|
|
220
|
+
to ``integrations/github``), raises a ProviderNameError asking for the source address
|
|
221
|
+
instead of assuming ``hashicorp/<name>``. Other lookup failures raise as they are.
|
|
222
|
+
"""
|
|
223
|
+
if "/" in provider_name:
|
|
224
|
+
return provider_name
|
|
225
|
+
if provider_name in _source_cache:
|
|
226
|
+
return _source_cache[provider_name]
|
|
227
|
+
cached = _load_from_cache(provider_name, "source")
|
|
228
|
+
if isinstance(cached, str) and "/" in cached:
|
|
229
|
+
_source_cache[provider_name] = cached
|
|
230
|
+
return cached
|
|
231
|
+
|
|
232
|
+
response = _http_pool.request("GET", f"{REGISTRY_URL}/v1/providers/-/{provider_name}/versions")
|
|
233
|
+
if response.status == 404:
|
|
234
|
+
raise ProviderNameError(
|
|
235
|
+
f"The Terraform registry has no provider named {provider_name!r} without a namespace (only hashicorp's providers have one); name it by its source address, <namespace>/{provider_name}",
|
|
236
|
+
)
|
|
237
|
+
if response.status != 200:
|
|
238
|
+
raise RuntimeError(f"HTTP {response.status} looking up the namespace of {provider_name}")
|
|
239
|
+
data = json.loads(response.data.decode("utf-8"))
|
|
240
|
+
source = data.get("id")
|
|
241
|
+
if not isinstance(source, str) or "/" not in source:
|
|
242
|
+
raise RuntimeError(f"The registry named no provider for {provider_name}")
|
|
243
|
+
moved_to = data.get("moved_to")
|
|
244
|
+
if isinstance(moved_to, str) and moved_to:
|
|
245
|
+
raise ProviderNameError(
|
|
246
|
+
f"Provider name {provider_name!r} is ambiguous: the registry's {source} has moved to {moved_to}; name the provider by its source address ({moved_to}, or {source} for the one that moved)",
|
|
247
|
+
)
|
|
248
|
+
_source_cache[provider_name] = source
|
|
249
|
+
_save_to_cache(provider_name, "source", source)
|
|
250
|
+
return source
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _registry_source_or_none(provider_name: str) -> str | None:
|
|
254
|
+
"""``resolve_registry_source``, reporting a failed lookup (network, registry errors) as None."""
|
|
255
|
+
from netherframe.core.logging import get_logger
|
|
256
|
+
|
|
257
|
+
try:
|
|
258
|
+
return resolve_registry_source(provider_name)
|
|
259
|
+
except ProviderNameError:
|
|
260
|
+
raise
|
|
261
|
+
except Exception as e:
|
|
262
|
+
get_logger(__name__).error("Error looking up the namespace of %s: %s", provider_name, e)
|
|
263
|
+
console.print(f"[yellow]Warning: Could not look up the namespace of {provider_name}: {e}[/yellow]")
|
|
264
|
+
return None
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def fetch_all_versions(provider_name: str) -> list[str] | None:
|
|
268
|
+
"""Fetch all available versions of a provider from the Terraform registry.
|
|
269
|
+
|
|
270
|
+
Args:
|
|
271
|
+
provider_name: Provider source address ("hashicorp/aws"), or a bare name the registry
|
|
272
|
+
resolves (see ``resolve_registry_source``)
|
|
273
|
+
|
|
274
|
+
Returns:
|
|
275
|
+
List of version strings sorted in descending order, or None if unable to fetch
|
|
276
|
+
|
|
277
|
+
Raises:
|
|
278
|
+
ProviderNameError: A bare name the registry does not resolve to one provider
|
|
279
|
+
|
|
280
|
+
"""
|
|
281
|
+
from netherframe.core.logging import get_logger
|
|
282
|
+
|
|
283
|
+
logger = get_logger(__name__)
|
|
284
|
+
|
|
285
|
+
source = _registry_source_or_none(provider_name)
|
|
286
|
+
if source is None:
|
|
287
|
+
return None
|
|
288
|
+
provider_name = source
|
|
289
|
+
|
|
290
|
+
# Check in-memory cache first
|
|
291
|
+
if provider_name in _all_versions_cache:
|
|
292
|
+
logger.trace(f"Using in-memory cached versions for {provider_name}")
|
|
293
|
+
return _all_versions_cache[provider_name]
|
|
294
|
+
|
|
295
|
+
# Check file cache
|
|
296
|
+
cached_data = _load_from_cache(provider_name, "all-versions")
|
|
297
|
+
if cached_data is not None:
|
|
298
|
+
logger.debug("Using file-cached versions for %s", provider_name)
|
|
299
|
+
_all_versions_cache[provider_name] = cached_data
|
|
300
|
+
return cached_data
|
|
301
|
+
|
|
302
|
+
try:
|
|
303
|
+
namespace, name = provider_name.split("/", 1)
|
|
304
|
+
|
|
305
|
+
# Fetch provider versions from Terraform registry API
|
|
306
|
+
url = f"{REGISTRY_URL}/v1/providers/{namespace}/{name}/versions"
|
|
307
|
+
|
|
308
|
+
logger.debug("Fetching all versions from: %s", url)
|
|
309
|
+
start_time = time.time()
|
|
310
|
+
|
|
311
|
+
# Use connection pool for better performance
|
|
312
|
+
response = _http_pool.request("GET", url)
|
|
313
|
+
|
|
314
|
+
fetch_time = time.time() - start_time
|
|
315
|
+
logger.debug(f"Fetched versions for {provider_name} in {fetch_time:.2f}s")
|
|
316
|
+
|
|
317
|
+
if response.status != 200:
|
|
318
|
+
logger.error(f"HTTP {response.status} for {url}")
|
|
319
|
+
return None
|
|
320
|
+
|
|
321
|
+
data = json.loads(response.data.decode("utf-8"))
|
|
322
|
+
|
|
323
|
+
versions = []
|
|
324
|
+
|
|
325
|
+
# Extract version strings from the response
|
|
326
|
+
for version_info in data.get("versions", []):
|
|
327
|
+
version = version_info.get("version")
|
|
328
|
+
if version:
|
|
329
|
+
versions.append(version)
|
|
330
|
+
|
|
331
|
+
logger.trace(f"Found {len(versions)} raw versions for {provider_name}")
|
|
332
|
+
|
|
333
|
+
# Sort versions in descending order (latest first)
|
|
334
|
+
# Handle semantic versions with possible non-numeric parts
|
|
335
|
+
def version_key(version: str) -> tuple[object, ...]:
|
|
336
|
+
parts: list[object] = []
|
|
337
|
+
for part in version.split("."):
|
|
338
|
+
# Try to convert to int, otherwise keep as string
|
|
339
|
+
try:
|
|
340
|
+
parts.append(int(part))
|
|
341
|
+
except ValueError:
|
|
342
|
+
# Handle pre-release versions like "1.0.0-rc1"
|
|
343
|
+
# Just use the base number if possible
|
|
344
|
+
numeric_part = ""
|
|
345
|
+
for char in part:
|
|
346
|
+
if char.isdigit():
|
|
347
|
+
numeric_part += char
|
|
348
|
+
else:
|
|
349
|
+
break
|
|
350
|
+
if numeric_part:
|
|
351
|
+
parts.append(int(numeric_part))
|
|
352
|
+
else:
|
|
353
|
+
parts.append(part)
|
|
354
|
+
return tuple(parts)
|
|
355
|
+
|
|
356
|
+
try:
|
|
357
|
+
versions.sort(key=version_key, reverse=True)
|
|
358
|
+
except Exception:
|
|
359
|
+
# Fallback to simple string sort if our custom sort fails
|
|
360
|
+
versions.sort(reverse=True)
|
|
361
|
+
|
|
362
|
+
# Cache the result in memory and file
|
|
363
|
+
_all_versions_cache[provider_name] = versions
|
|
364
|
+
_save_to_cache(provider_name, "all-versions", versions)
|
|
365
|
+
logger.debug(f"Cached {len(versions)} versions for {provider_name}")
|
|
366
|
+
return versions
|
|
367
|
+
|
|
368
|
+
except Exception as e:
|
|
369
|
+
logger.error("Error fetching versions for %s: %s", provider_name, e)
|
|
370
|
+
console.print(
|
|
371
|
+
f"[yellow]Warning: Could not fetch versions for {provider_name}: {e}[/yellow]",
|
|
372
|
+
)
|
|
373
|
+
_all_versions_cache[provider_name] = None
|
|
374
|
+
return None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def fetch_latest_version(provider_name: str) -> str | None:
|
|
378
|
+
"""Fetch the latest version of a provider from the Terraform registry.
|
|
379
|
+
|
|
380
|
+
Args:
|
|
381
|
+
provider_name: Provider source address ("hashicorp/aws"), or a bare name the registry
|
|
382
|
+
resolves (see ``resolve_registry_source``)
|
|
383
|
+
|
|
384
|
+
Returns:
|
|
385
|
+
Latest version string or None if unable to fetch
|
|
386
|
+
|
|
387
|
+
Raises:
|
|
388
|
+
ProviderNameError: A bare name the registry does not resolve to one provider
|
|
389
|
+
|
|
390
|
+
"""
|
|
391
|
+
from netherframe.core.logging import get_logger
|
|
392
|
+
|
|
393
|
+
logger = get_logger(__name__)
|
|
394
|
+
|
|
395
|
+
source = _registry_source_or_none(provider_name)
|
|
396
|
+
if source is None:
|
|
397
|
+
return None
|
|
398
|
+
provider_name = source
|
|
399
|
+
|
|
400
|
+
# Check in-memory cache first
|
|
401
|
+
if provider_name in _version_cache:
|
|
402
|
+
logger.trace(
|
|
403
|
+
f"Using in-memory cached latest version for {provider_name}: {_version_cache[provider_name]}",
|
|
404
|
+
)
|
|
405
|
+
return _version_cache[provider_name]
|
|
406
|
+
|
|
407
|
+
# Check file cache
|
|
408
|
+
cached_data = _load_from_cache(provider_name, "latest-version")
|
|
409
|
+
if cached_data is not None:
|
|
410
|
+
logger.debug(
|
|
411
|
+
"Using file-cached latest version for %s: %s",
|
|
412
|
+
provider_name,
|
|
413
|
+
cached_data,
|
|
414
|
+
)
|
|
415
|
+
_version_cache[provider_name] = cached_data
|
|
416
|
+
return cached_data
|
|
417
|
+
|
|
418
|
+
try:
|
|
419
|
+
namespace, name = provider_name.split("/", 1)
|
|
420
|
+
|
|
421
|
+
# Fetch provider info from Terraform registry API
|
|
422
|
+
url = f"{REGISTRY_URL}/v1/providers/{namespace}/{name}"
|
|
423
|
+
|
|
424
|
+
logger.debug("Fetching latest version from: %s", url)
|
|
425
|
+
start_time = time.time()
|
|
426
|
+
|
|
427
|
+
# Use connection pool for better performance
|
|
428
|
+
response = _http_pool.request("GET", url)
|
|
429
|
+
|
|
430
|
+
fetch_time = time.time() - start_time
|
|
431
|
+
logger.debug(f"Fetched latest version for {provider_name} in {fetch_time:.2f}s")
|
|
432
|
+
|
|
433
|
+
if response.status != 200:
|
|
434
|
+
logger.error(f"HTTP {response.status} for {url}")
|
|
435
|
+
return None
|
|
436
|
+
|
|
437
|
+
data = json.loads(response.data.decode("utf-8"))
|
|
438
|
+
|
|
439
|
+
version = data.get("version")
|
|
440
|
+
# Cache the result in memory and file
|
|
441
|
+
_version_cache[provider_name] = version
|
|
442
|
+
_save_to_cache(provider_name, "latest-version", version)
|
|
443
|
+
logger.debug("Latest version for %s: %s", provider_name, version)
|
|
444
|
+
return version
|
|
445
|
+
|
|
446
|
+
except Exception as e:
|
|
447
|
+
logger.error("Error fetching latest version for %s: %s", provider_name, e)
|
|
448
|
+
console.print(
|
|
449
|
+
f"[yellow]Warning: Could not fetch latest version for {provider_name}: {e}[/yellow]",
|
|
450
|
+
)
|
|
451
|
+
_version_cache[provider_name] = None
|
|
452
|
+
return None
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def save_config_file(config_file: Path, config_data: dict[str, Any]) -> None:
|
|
456
|
+
"""Save provider configuration back to file.
|
|
457
|
+
|
|
458
|
+
Args:
|
|
459
|
+
config_file: Path to configuration file
|
|
460
|
+
config_data: Configuration data to save
|
|
461
|
+
|
|
462
|
+
"""
|
|
463
|
+
if config_file.suffix.lower() in [".yaml", ".yml"]:
|
|
464
|
+
try:
|
|
465
|
+
import yaml
|
|
466
|
+
|
|
467
|
+
content = yaml.dump(config_data, default_flow_style=False, sort_keys=False)
|
|
468
|
+
except ImportError as e:
|
|
469
|
+
raise click.ClickException(
|
|
470
|
+
"Cannot save YAML file: PyYAML not installed",
|
|
471
|
+
) from e
|
|
472
|
+
elif config_file.suffix.lower() == ".json":
|
|
473
|
+
content = json.dumps(config_data, indent=2)
|
|
474
|
+
elif config_file.suffix.lower() == ".toml":
|
|
475
|
+
content = tomli_w.dumps(config_data)
|
|
476
|
+
else:
|
|
477
|
+
raise click.ClickException(
|
|
478
|
+
f"Unsupported config file format: {config_file.suffix}",
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
config_file.write_text(content)
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def create_starter_specs(config_format: str = "all") -> None:
|
|
485
|
+
"""Create starter provider specification files in requested format(s).
|
|
486
|
+
|
|
487
|
+
Args:
|
|
488
|
+
config_format: File format to create ("yaml", "json", "toml", or "all")
|
|
489
|
+
|
|
490
|
+
"""
|
|
491
|
+
# Common provider configuration data
|
|
492
|
+
starter_config = {
|
|
493
|
+
"defaults": {"version": "latest", "output_base": "providers"},
|
|
494
|
+
"providers": [
|
|
495
|
+
# Simple string format
|
|
496
|
+
"hashicorp/aws",
|
|
497
|
+
"hashicorp/google",
|
|
498
|
+
"hashicorp/azurerm",
|
|
499
|
+
# Detailed dict format
|
|
500
|
+
{
|
|
501
|
+
"name": "hashicorp/kubernetes",
|
|
502
|
+
"version": "~> 2.0",
|
|
503
|
+
"output_dir": "providers/k8s",
|
|
504
|
+
},
|
|
505
|
+
{"name": "hashicorp/random", "version": "~> 3.0"},
|
|
506
|
+
],
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
formats_to_create = []
|
|
510
|
+
if config_format.lower() == "all":
|
|
511
|
+
formats_to_create = ["yaml", "json", "toml"]
|
|
512
|
+
elif config_format.lower() in ["yaml", "yml"]:
|
|
513
|
+
formats_to_create = ["yaml"]
|
|
514
|
+
elif config_format.lower() == "json":
|
|
515
|
+
formats_to_create = ["json"]
|
|
516
|
+
elif config_format.lower() == "toml":
|
|
517
|
+
formats_to_create = ["toml"]
|
|
518
|
+
else:
|
|
519
|
+
console.print(f"[bold red]Unknown format: {config_format}[/bold red]")
|
|
520
|
+
console.print("Supported formats: yaml, json, toml, all")
|
|
521
|
+
return
|
|
522
|
+
|
|
523
|
+
created_files = []
|
|
524
|
+
|
|
525
|
+
# Create YAML starter
|
|
526
|
+
if "yaml" in formats_to_create:
|
|
527
|
+
yaml_file = Path("nf-providers.yaml.starter")
|
|
528
|
+
try:
|
|
529
|
+
import yaml
|
|
530
|
+
|
|
531
|
+
# Add header comment
|
|
532
|
+
yaml_content = """# NF Provider Generation Configuration
|
|
533
|
+
#
|
|
534
|
+
# This starter configuration demonstrates various ways to specify providers.
|
|
535
|
+
# Rename this file to 'nf-providers.yaml' to use it.
|
|
536
|
+
#
|
|
537
|
+
# Defaults apply to all providers unless overridden
|
|
538
|
+
# 'version' can be: "latest", "~> X.Y", "X.Y.Z", etc.
|
|
539
|
+
# 'output_base' is the base directory for generated providers
|
|
540
|
+
|
|
541
|
+
"""
|
|
542
|
+
yaml_content += yaml.dump(
|
|
543
|
+
starter_config,
|
|
544
|
+
default_flow_style=False,
|
|
545
|
+
sort_keys=False,
|
|
546
|
+
)
|
|
547
|
+
yaml_file.write_text(yaml_content)
|
|
548
|
+
created_files.append(yaml_file.name)
|
|
549
|
+
except ImportError:
|
|
550
|
+
console.print("[yellow]Skipping YAML: PyYAML not installed[/yellow]")
|
|
551
|
+
|
|
552
|
+
# Create JSON starter
|
|
553
|
+
if "json" in formats_to_create:
|
|
554
|
+
json_file = Path("nf-providers.json.starter")
|
|
555
|
+
# Add comments as a special field (JSON doesn't support comments)
|
|
556
|
+
json_config = {
|
|
557
|
+
"_comment": [
|
|
558
|
+
"NF Provider Generation Configuration",
|
|
559
|
+
"Rename this file to 'nf-providers.json' to use it.",
|
|
560
|
+
"The 'defaults' section applies to all providers unless overridden.",
|
|
561
|
+
"'version' can be: 'latest', '~> X.Y', 'X.Y.Z', etc.",
|
|
562
|
+
],
|
|
563
|
+
**starter_config,
|
|
564
|
+
}
|
|
565
|
+
json_content = json.dumps(json_config, indent=2)
|
|
566
|
+
json_file.write_text(json_content)
|
|
567
|
+
created_files.append(json_file.name)
|
|
568
|
+
|
|
569
|
+
# Create TOML starter
|
|
570
|
+
if "toml" in formats_to_create:
|
|
571
|
+
toml_file = Path("nf-providers.toml.starter")
|
|
572
|
+
try:
|
|
573
|
+
# TOML format needs special handling
|
|
574
|
+
toml_content = """# NF Provider Generation Configuration
|
|
575
|
+
#
|
|
576
|
+
# This starter configuration demonstrates various ways to specify providers.
|
|
577
|
+
# Rename this file to 'nf-providers.toml' to use it.
|
|
578
|
+
|
|
579
|
+
[defaults]
|
|
580
|
+
version = "latest"
|
|
581
|
+
output_base = "providers"
|
|
582
|
+
|
|
583
|
+
# For TOML, place the providers array under defaults section
|
|
584
|
+
# This will be automatically detected and handled correctly
|
|
585
|
+
providers = [
|
|
586
|
+
"hashicorp/aws",
|
|
587
|
+
"hashicorp/google",
|
|
588
|
+
"hashicorp/azurerm",
|
|
589
|
+
"hashicorp/random"
|
|
590
|
+
]
|
|
591
|
+
|
|
592
|
+
# Alternative: Use table array format for detailed configuration
|
|
593
|
+
# Note: You cannot mix simple strings with detailed tables in TOML
|
|
594
|
+
# If you need detailed config, use this format instead:
|
|
595
|
+
#
|
|
596
|
+
# [[providers]]
|
|
597
|
+
# name = "hashicorp/kubernetes"
|
|
598
|
+
# version = "~> 2.0"
|
|
599
|
+
# output_dir = "providers/k8s"
|
|
600
|
+
#
|
|
601
|
+
# [[providers]]
|
|
602
|
+
# name = "hashicorp/random"
|
|
603
|
+
# version = "~> 3.0"
|
|
604
|
+
"""
|
|
605
|
+
toml_file.write_text(toml_content)
|
|
606
|
+
created_files.append(toml_file.name)
|
|
607
|
+
except Exception as e:
|
|
608
|
+
console.print(f"[yellow]Error creating TOML starter: {e}[/yellow]")
|
|
609
|
+
|
|
610
|
+
# Report created files
|
|
611
|
+
if created_files:
|
|
612
|
+
console.print("\n[bold green]Created starter configuration files:[/bold green]")
|
|
613
|
+
for file in created_files:
|
|
614
|
+
console.print(f" • {file}")
|
|
615
|
+
console.print("\n[dim]Rename to remove '.starter' extension to use.[/dim]")
|
|
616
|
+
console.print(
|
|
617
|
+
"[dim]Example: mv nf-providers.yaml.starter nf-providers.yaml[/dim]",
|
|
618
|
+
)
|
|
619
|
+
else:
|
|
620
|
+
console.print("[bold red]No starter files were created.[/bold red]")
|