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,679 @@
1
+ """Discovery-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 TYPE_CHECKING, Any, TypedDict
8
+
9
+ import click
10
+ from netherframe.cli.ui import console
11
+ from netherframe.core.orchestration.event_loop import run_sync
12
+ from netherframe.core.serialization import orjson_compat as json
13
+ from rich.console import Console
14
+ from rich.table import Table
15
+
16
+ if TYPE_CHECKING:
17
+ from netherframe.core.infrastructure.discovery import DiscoveredResource
18
+
19
+
20
+ class DiscoveryProviderInfo(TypedDict):
21
+ name: str
22
+ module: str
23
+ description: str
24
+ class_: type[Any]
25
+
26
+
27
+ def _get_available_providers() -> dict[str, DiscoveryProviderInfo]:
28
+ """Get available discovery providers with their descriptions."""
29
+ providers: dict[str, DiscoveryProviderInfo] = {}
30
+
31
+ # Try to import AWS discoverer
32
+ try:
33
+ from netherframe.discovery.hashicorp.aws import AWSDiscoverer
34
+
35
+ providers["aws"] = {
36
+ "name": "AWS",
37
+ "module": "netherframe.discovery.hashicorp.aws",
38
+ "description": "AWS resource discovery using HashiCorp provider",
39
+ "class_": AWSDiscoverer,
40
+ }
41
+ except ImportError:
42
+ pass
43
+
44
+ # Try to import GitLab discoverer
45
+ try:
46
+ from netherframe.discovery.gitlabhq.gitlab import GitLabDiscoverer
47
+
48
+ providers["gitlab"] = {
49
+ "name": "GitLab",
50
+ "module": "netherframe.discovery.gitlabhq.gitlab",
51
+ "description": "GitLab resource discovery",
52
+ "class_": GitLabDiscoverer,
53
+ }
54
+ except ImportError:
55
+ pass
56
+
57
+ # Try to import Keycloak discoverer
58
+ try:
59
+ from netherframe.discovery.keycloak.keycloak import KeycloakDiscoverer
60
+
61
+ providers["keycloak"] = {
62
+ "name": "Keycloak",
63
+ "module": "netherframe.discovery.keycloak.keycloak",
64
+ "description": "Keycloak resource discovery",
65
+ "class_": KeycloakDiscoverer,
66
+ }
67
+ except ImportError:
68
+ pass
69
+
70
+ return providers
71
+
72
+
73
+ @click.group()
74
+ def discover() -> None:
75
+ """Discovery and introspection utilities for Netherframe."""
76
+
77
+
78
+ @discover.command("list-providers")
79
+ @click.option(
80
+ "--json",
81
+ "output_json",
82
+ is_flag=True,
83
+ help="Output in JSON format",
84
+ )
85
+ def list_providers(output_json: bool) -> None:
86
+ """List available discovery providers.
87
+
88
+ Shows all installed discovery providers and their capabilities.
89
+
90
+ Examples:
91
+ nf discover list-providers
92
+ nf discover list-providers --json
93
+
94
+ """
95
+ providers = _get_available_providers()
96
+
97
+ if not providers:
98
+ console.print("[yellow]No discovery providers available.[/yellow]")
99
+ console.print("Install discovery packages:")
100
+ console.print(" [dim]pip install netherframe.discovery.hashicorp.aws[/dim]")
101
+ console.print(" [dim]pip install netherframe.discovery.gitlabhq.gitlab[/dim]")
102
+ console.print(" [dim]pip install netherframe.discovery.keycloak.keycloak[/dim]")
103
+ return
104
+
105
+ if output_json:
106
+ # JSON output
107
+ json_data = {
108
+ provider_id: {
109
+ "name": info["name"],
110
+ "module": info["module"],
111
+ "description": info["description"],
112
+ }
113
+ for provider_id, info in providers.items()
114
+ }
115
+ console.print(json.dumps(json_data, indent=2))
116
+ else:
117
+ # Rich table output
118
+ table = Table(title="Available Discovery Providers")
119
+ table.add_column("Provider", style="cyan")
120
+ table.add_column("Name", style="green")
121
+ table.add_column("Module", style="blue")
122
+ table.add_column("Description", style="white")
123
+
124
+ for provider_id, info in providers.items():
125
+ table.add_row(
126
+ provider_id,
127
+ info["name"],
128
+ info["module"],
129
+ info["description"],
130
+ )
131
+
132
+ console.print(table)
133
+
134
+
135
+ @discover.command("list-resources")
136
+ @click.argument("provider")
137
+ @click.option(
138
+ "--json",
139
+ "output_json",
140
+ is_flag=True,
141
+ help="Output in JSON format",
142
+ )
143
+ @click.option(
144
+ "--filter",
145
+ "filter_pattern",
146
+ help="Filter resource types by pattern (e.g., 'aws_ec2_*')",
147
+ )
148
+ def list_resources(
149
+ provider: str,
150
+ output_json: bool,
151
+ filter_pattern: str | None,
152
+ ) -> None:
153
+ """List supported resource types for a provider.
154
+
155
+ Shows all resource types that can be discovered by the specified provider.
156
+
157
+ Examples:
158
+ nf discover list-resources aws
159
+ nf discover list-resources aws --filter "aws_ec2_*"
160
+ nf discover list-resources gitlab --json
161
+
162
+ """
163
+ providers = _get_available_providers()
164
+
165
+ if provider not in providers:
166
+ console.print(f"[bold red]Provider '{provider}' not found.[/bold red]")
167
+ console.print("Available providers:")
168
+ for pid, info in providers.items():
169
+ console.print(f" • {pid} ({info['name']})")
170
+ sys.exit(1)
171
+
172
+ try:
173
+ discoverer_class = providers[provider]["class_"]
174
+ discoverer = discoverer_class()
175
+
176
+ # Get supported resource types
177
+ resource_types = discoverer.get_supported_resource_types()
178
+
179
+ # Apply filter if specified
180
+ if filter_pattern:
181
+ import fnmatch
182
+
183
+ resource_types = [rt for rt in resource_types if fnmatch.fnmatch(rt, filter_pattern)]
184
+
185
+ if not resource_types:
186
+ if filter_pattern:
187
+ console.print(
188
+ f"[yellow]No resource types match pattern '{filter_pattern}'[/yellow]",
189
+ )
190
+ else:
191
+ console.print(
192
+ "[yellow]No resource types available for this provider.[/yellow]",
193
+ )
194
+ return
195
+
196
+ if output_json:
197
+ # JSON output
198
+ json_data = {
199
+ "provider": provider,
200
+ "resource_types": sorted(resource_types),
201
+ "count": len(resource_types),
202
+ }
203
+ console.print(json.dumps(json_data, indent=2))
204
+ else:
205
+ # Rich table output
206
+ title = f"Resource Types for {providers[provider]['name']}"
207
+ if filter_pattern:
208
+ title += f" (filtered: {filter_pattern})"
209
+
210
+ table = Table(title=title)
211
+ table.add_column("Resource Type", style="cyan")
212
+ table.add_column("Service", style="green")
213
+
214
+ # Group by service prefix for better organization
215
+ service_groups = {}
216
+ for rt in sorted(resource_types):
217
+ if "_" in rt:
218
+ service = rt.split("_", 2)[1] # e.g., aws_ec2_instance -> ec2
219
+ else:
220
+ service = "other"
221
+
222
+ if service not in service_groups:
223
+ service_groups[service] = []
224
+ service_groups[service].append(rt)
225
+
226
+ for service, types in sorted(service_groups.items()):
227
+ for rt in types:
228
+ table.add_row(rt, service)
229
+
230
+ console.print(table)
231
+ console.print(f"\n[dim]Total: {len(resource_types)} resource types[/dim]")
232
+
233
+ except Exception as e:
234
+ console.print(f"[bold red]Error listing resources:[/bold red] {e}")
235
+ sys.exit(1)
236
+
237
+
238
+ @discover.command("resources")
239
+ @click.argument("provider")
240
+ @click.option(
241
+ "--resource-types",
242
+ multiple=True,
243
+ help="Specific resource types to discover (can specify multiple)",
244
+ )
245
+ @click.option(
246
+ "--json",
247
+ "output_json",
248
+ is_flag=True,
249
+ help="Output in JSON format",
250
+ )
251
+ @click.option(
252
+ "--region",
253
+ help="AWS region (for AWS provider)",
254
+ )
255
+ @click.option(
256
+ "--profile",
257
+ help="AWS profile (for AWS provider)",
258
+ )
259
+ @click.option(
260
+ "--url",
261
+ help="Server URL (for GitLab/Keycloak providers)",
262
+ )
263
+ @click.option(
264
+ "--token",
265
+ help="Access token (for GitLab provider)",
266
+ )
267
+ @click.option(
268
+ "--username",
269
+ help="Username (for Keycloak provider)",
270
+ )
271
+ @click.option(
272
+ "--password",
273
+ help="Password (for Keycloak provider)",
274
+ )
275
+ @click.option(
276
+ "--client-id",
277
+ help="Client ID (for Keycloak provider)",
278
+ )
279
+ @click.option(
280
+ "--client-secret",
281
+ help="Client secret (for Keycloak provider)",
282
+ )
283
+ @click.option(
284
+ "--limit",
285
+ type=int,
286
+ help="Limit number of resources to discover",
287
+ )
288
+ def discover_resources(
289
+ provider: str,
290
+ resource_types: tuple[str, ...],
291
+ output_json: bool,
292
+ region: str | None,
293
+ profile: str | None,
294
+ url: str | None,
295
+ token: str | None,
296
+ username: str | None,
297
+ password: str | None,
298
+ client_id: str | None,
299
+ client_secret: str | None,
300
+ limit: int | None,
301
+ ) -> None:
302
+ """Discover live resources from a provider.
303
+
304
+ Connects to the specified provider and discovers actual infrastructure resources.
305
+
306
+ Examples:
307
+ nf discover resources aws --region us-east-1
308
+ nf discover resources aws --resource-types aws_instance --resource-types aws_vpc
309
+ nf discover resources gitlab --url https://gitlab.com --token $GITLAB_TOKEN
310
+ nf discover resources keycloak --url http://localhost:8080 --username admin --password admin
311
+
312
+ """
313
+ try:
314
+ from netherframe.core.logging import get_logger
315
+ except ImportError as exc:
316
+ console.print(f"[bold red]Discovery modules not available:[/bold red] {exc}")
317
+ console.print(
318
+ "Install discovery dependencies: [dim]pip install netherframe.discovery.hashicorp.aws[/dim]",
319
+ )
320
+ sys.exit(1)
321
+
322
+ logger = get_logger(__name__)
323
+
324
+ providers = _get_available_providers()
325
+
326
+ if provider not in providers:
327
+ console.print(f"[bold red]Provider '{provider}' not found.[/bold red]")
328
+ console.print("Available providers:")
329
+ for pid, info in providers.items():
330
+ console.print(f" • {pid} ({info['name']})")
331
+ sys.exit(1)
332
+
333
+ # Build configuration based on provider
334
+ config = {}
335
+
336
+ if provider == "aws":
337
+ if region:
338
+ config["region"] = region
339
+ if profile:
340
+ config["profile"] = profile
341
+ elif provider == "gitlab":
342
+ if url:
343
+ config["url"] = url
344
+ if token:
345
+ config["token"] = token
346
+ elif provider == "keycloak":
347
+ if url:
348
+ config["server_url"] = url
349
+ if username:
350
+ config["username"] = username
351
+ if password:
352
+ config["password"] = password
353
+ if client_id:
354
+ config["client_id"] = client_id
355
+ if client_secret:
356
+ config["client_secret"] = client_secret
357
+
358
+ try:
359
+ # Create discoverer instance
360
+ discoverer_class = providers[provider]["class_"]
361
+ discoverer = discoverer_class()
362
+
363
+ # Validate configuration
364
+ discoverer.validate_config(config)
365
+
366
+ # Get resource types to discover
367
+ if resource_types:
368
+ types_to_discover = list(resource_types)
369
+ else:
370
+ # Discover all supported types
371
+ types_to_discover = discoverer.get_supported_resource_types()
372
+ if limit:
373
+ types_to_discover = types_to_discover[:limit]
374
+
375
+ console.print(
376
+ f"[bold blue]Discovering {len(types_to_discover)} resource types from {providers[provider]['name']}...[/bold blue]",
377
+ )
378
+
379
+ # Run discovery (ResourceDiscoverer.discover_resources is synchronous)
380
+ async def run_discovery() -> list[DiscoveredResource]:
381
+ return discoverer.discover_resources(config, {"resource_types": types_to_discover})
382
+
383
+ # Run discovery through the shared AnyIO entrypoint so CLI/backend
384
+ # selection stays consistent with the runtime.
385
+ resources: list[DiscoveredResource] = run_sync(run_discovery)
386
+
387
+ if not resources:
388
+ console.print("[yellow]No resources discovered.[/yellow]")
389
+ return
390
+
391
+ if output_json:
392
+ # JSON output
393
+ json_data = {
394
+ "provider": provider,
395
+ "discovered_count": len(resources),
396
+ "resources": [
397
+ {
398
+ "type": resource.resource_type,
399
+ "import_id": resource.import_id,
400
+ "name": (resource.metadata or {}).get("name"),
401
+ "attributes": dict(resource.attributes),
402
+ # Arguments discovery could not read; the user must supply them.
403
+ **({"arguments_to_supply": arguments} if (arguments := resource.arguments_to_supply) else {}),
404
+ }
405
+ for resource in resources
406
+ ],
407
+ }
408
+ console.print(json.dumps(json_data, indent=2))
409
+ else:
410
+ # Rich table output
411
+ table = Table(
412
+ title=f"Discovered Resources from {providers[provider]['name']}",
413
+ )
414
+ table.add_column("Type", style="cyan")
415
+ table.add_column("Import ID", style="green")
416
+ table.add_column("Name", style="yellow")
417
+ table.add_column("Attributes", style="dim")
418
+
419
+ for resource in resources[:50]: # Limit display to 50 for readability
420
+ name = (resource.metadata or {}).get("name")
421
+ attrs_count = len(resource.attributes)
422
+ table.add_row(
423
+ resource.resource_type,
424
+ resource.import_id,
425
+ str(name) if name else "[dim]no name[/dim]",
426
+ f"{attrs_count} attributes" + (" [yellow](incomplete)[/yellow]" if resource.arguments_to_supply else ""),
427
+ )
428
+
429
+ console.print(table)
430
+
431
+ if len(resources) > 50:
432
+ console.print(
433
+ f"\n[dim]Showing first 50 of {len(resources)} resources. Use --json for complete output.[/dim]",
434
+ )
435
+ else:
436
+ console.print(
437
+ f"\n[dim]Total: {len(resources)} resources discovered[/dim]",
438
+ )
439
+
440
+ # Name every argument users must fill in themselves (e.g. secrets the API never
441
+ # returns); the JSON output carries them as each resource's arguments_to_supply.
442
+ notices = [notice for resource in resources if (notice := resource.describe_arguments_to_supply()) is not None]
443
+ if notices:
444
+ console.print(f"\n[bold yellow]{len(notices)} discovered resources need arguments that discovery could not read:[/bold yellow]")
445
+ for notice in notices:
446
+ console.print(f" - {notice}", markup=False, highlight=False, soft_wrap=True)
447
+
448
+ except Exception as e:
449
+ logger.error("Discovery failed: %s", e)
450
+ console.print(f"[bold red]Discovery failed:[/bold red] {e}")
451
+ sys.exit(1)
452
+
453
+
454
+ CODIFIERS = ("keycloak",)
455
+
456
+
457
+ @discover.command("codify")
458
+ @click.argument("provider", type=click.Choice(CODIFIERS))
459
+ @click.option("--url", envvar="KEYCLOAK_URL", required=True, help="Keycloak server URL (or KEYCLOAK_URL)")
460
+ @click.option("--realm", "realm", required=True, help="The realm to codify")
461
+ @click.option("--output", "-o", "output", type=click.Path(dir_okay=False, path_type=Path), help="File to write the code to (default: standard output)")
462
+ @click.option("--username", envvar="KEYCLOAK_USER", help="Admin username (or KEYCLOAK_USER)")
463
+ @click.option("--password", envvar="KEYCLOAK_PASSWORD", help="Admin password (prefer KEYCLOAK_PASSWORD)")
464
+ @click.option("--client-id", envvar="KEYCLOAK_CLIENT_ID", default="admin-cli", show_default=True, help="Client to authenticate with (or KEYCLOAK_CLIENT_ID)")
465
+ @click.option("--client-secret", envvar="KEYCLOAK_CLIENT_SECRET", help="Client secret, for client credentials (prefer KEYCLOAK_CLIENT_SECRET)")
466
+ @click.option("--auth-realm", envvar="KEYCLOAK_REALM", default="master", show_default=True, help="Realm to authenticate in (or KEYCLOAK_REALM)")
467
+ @click.option("--include-users", is_flag=True, help="Codify users too")
468
+ @click.option("--include-builtin", is_flag=True, help="Codify the clients, client scopes, roles and flows every realm is created with")
469
+ @click.option(
470
+ "--manifest",
471
+ "manifest_path",
472
+ type=click.Path(dir_okay=False, path_type=Path),
473
+ help="Adoption manifest to write (default with --output: beside it, <name>.adopt.json)",
474
+ )
475
+ @click.option("--bindings", type=click.Choice(["auto", "typed", "generic"]), default="auto", show_default=True, help="Generated typed classes, generic Resource constructs, or typed when installed")
476
+ @click.option("--provider-version", default="latest", show_default=True, help="keycloak/keycloak provider version in the provider cache")
477
+ @click.option("--provider-binary", type=click.Path(exists=True, dir_okay=False), help="Provider binary to use instead of the cache")
478
+ @click.option("--insecure", is_flag=True, help="Do not verify the server's TLS certificate")
479
+ def codify(
480
+ provider: str,
481
+ url: str,
482
+ realm: str,
483
+ output: Path | None,
484
+ username: str | None,
485
+ password: str | None,
486
+ client_id: str,
487
+ client_secret: str | None,
488
+ auth_realm: str,
489
+ include_users: bool,
490
+ include_builtin: bool,
491
+ manifest_path: Path | None,
492
+ bindings: str,
493
+ provider_version: str,
494
+ provider_binary: str | None,
495
+ insecure: bool,
496
+ ) -> None:
497
+ """Write Netherframe code for live objects: a Keycloak realm and what it holds.
498
+
499
+ Every object is imported through the provider, so the code reproduces the provider's state.
500
+ Secrets are never written: the code reads them from environment variables it names. The
501
+ adoption manifest beside the code (--manifest) lists the existing object each construct stands
502
+ for: nf plan --adopt-from <manifest> shows them as imports.
503
+
504
+ Examples:
505
+ KEYCLOAK_USER=admin KEYCLOAK_PASSWORD=... nf discover codify keycloak --url http://localhost:8080 --realm demo -o realm_demo.py
506
+
507
+ """
508
+ del provider # keycloak is the only codifier so far
509
+ try:
510
+ from netherframe.discovery.keycloak.keycloak.codify import CodifyOptions, codify_realm, summarize
511
+ from netherframe.discovery.keycloak.keycloak.connection import KeycloakConnection
512
+ from netherframe.generation.discovered_code import format_adoption_manifest
513
+ except ImportError as exc:
514
+ raise click.ClickException(f"Keycloak discovery is not installed ({exc}): pip install netherframe.discovery.keycloak.keycloak") from exc
515
+
516
+ try:
517
+ connection = KeycloakConnection.from_config(
518
+ {
519
+ "server_url": url,
520
+ "username": username,
521
+ "password": password,
522
+ "client_id": client_id,
523
+ "client_secret": client_secret,
524
+ "realm_name": auth_realm,
525
+ "verify_ssl": not insecure,
526
+ "provider_version": provider_version,
527
+ "provider_binary": provider_binary,
528
+ },
529
+ )
530
+ options = CodifyOptions(
531
+ include_users=include_users,
532
+ include_builtin=include_builtin,
533
+ typed={"auto": None, "typed": True, "generic": False}[bindings],
534
+ server_url=url,
535
+ provider_realm=auth_realm,
536
+ provider_client_id=client_id,
537
+ provider_version=connection.effective_provider_version,
538
+ )
539
+ with connection.admin_api() as api, connection.provider_client() as client:
540
+ result = codify_realm(api, client, realm, options)
541
+ except (ValueError, RuntimeError) as exc:
542
+ raise click.ClickException(f"Codifying realm {realm!r} failed: {exc}") from exc
543
+
544
+ if output is None:
545
+ click.echo(result.source, nl=False)
546
+ else:
547
+ output.write_text(result.source, encoding="utf-8")
548
+ manifest_path = manifest_path or output.with_name(f"{output.stem}.adopt.json")
549
+ if manifest_path is not None:
550
+ manifest_path.write_text(format_adoption_manifest(result.manifest), encoding="utf-8")
551
+ err = Console(stderr=True)
552
+ counts = summarize(result.objects)
553
+ err.print(f"[bold green]Codified realm {realm}:[/bold green] {sum(counts.values())} constructs" + (f" in {output}" if output else ""))
554
+ for resource_type, count in counts.items():
555
+ err.print(f" {count:4d} {resource_type}", markup=False, highlight=False)
556
+ if manifest_path is not None:
557
+ err.print(f"Adoption manifest ({len(result.manifest['adopt'])} objects) in {manifest_path}: nf plan --adopt-from {manifest_path} shows them as imports", markup=False, highlight=False, soft_wrap=True)
558
+ if result.secrets:
559
+ err.print(f"[bold yellow]{len(result.secrets)} secrets are read from the environment:[/bold yellow]")
560
+ for secret in result.secrets:
561
+ err.print(f" {secret.env_var}: {secret.description}", markup=False, highlight=False, soft_wrap=True)
562
+ if result.failures or result.skipped:
563
+ err.print("[bold yellow]Not codified:[/bold yellow]")
564
+ for failure in result.failures:
565
+ err.print(f" {failure.target.resource_type} {failure.target.import_id}: {failure.reason}", markup=False, highlight=False)
566
+ for skipped in result.skipped:
567
+ err.print(f" {skipped}", markup=False, highlight=False)
568
+ if result.notices:
569
+ err.print("[bold yellow]Review configuration adjustments:[/bold yellow]")
570
+ for notice in result.notices:
571
+ err.print(f" {notice}", markup=False, highlight=False)
572
+
573
+
574
+ @discover.command("validate")
575
+ @click.argument("provider")
576
+ @click.option(
577
+ "--region",
578
+ help="AWS region (for AWS provider)",
579
+ )
580
+ @click.option(
581
+ "--profile",
582
+ help="AWS profile (for AWS provider)",
583
+ )
584
+ @click.option(
585
+ "--url",
586
+ help="Server URL (for GitLab/Keycloak providers)",
587
+ )
588
+ @click.option(
589
+ "--token",
590
+ help="Access token (for GitLab provider)",
591
+ )
592
+ @click.option(
593
+ "--username",
594
+ help="Username (for Keycloak provider)",
595
+ )
596
+ @click.option(
597
+ "--password",
598
+ help="Password (for Keycloak provider)",
599
+ )
600
+ @click.option(
601
+ "--client-id",
602
+ help="Client ID (for Keycloak provider)",
603
+ )
604
+ @click.option(
605
+ "--client-secret",
606
+ help="Client secret (for Keycloak provider)",
607
+ )
608
+ def validate_config(
609
+ provider: str,
610
+ region: str | None,
611
+ profile: str | None,
612
+ url: str | None,
613
+ token: str | None,
614
+ username: str | None,
615
+ password: str | None,
616
+ client_id: str | None,
617
+ client_secret: str | None,
618
+ ) -> None:
619
+ """Validate provider configuration.
620
+
621
+ Tests that the provider configuration is valid and can authenticate.
622
+
623
+ Examples:
624
+ nf discover validate aws --region us-east-1
625
+ nf discover validate gitlab --url https://gitlab.com --token $GITLAB_TOKEN
626
+ nf discover validate keycloak --url http://localhost:8080 --username admin --password admin
627
+
628
+ """
629
+ providers = _get_available_providers()
630
+
631
+ if provider not in providers:
632
+ console.print(f"[bold red]Provider '{provider}' not found.[/bold red]")
633
+ console.print("Available providers:")
634
+ for pid, info in providers.items():
635
+ console.print(f" • {pid} ({info['name']})")
636
+ sys.exit(1)
637
+
638
+ # Build configuration based on provider
639
+ config = {}
640
+
641
+ if provider == "aws":
642
+ if region:
643
+ config["region"] = region
644
+ if profile:
645
+ config["profile"] = profile
646
+ elif provider == "gitlab":
647
+ if url:
648
+ config["url"] = url
649
+ if token:
650
+ config["token"] = token
651
+ elif provider == "keycloak":
652
+ if url:
653
+ config["server_url"] = url
654
+ if username:
655
+ config["username"] = username
656
+ if password:
657
+ config["password"] = password
658
+ if client_id:
659
+ config["client_id"] = client_id
660
+ if client_secret:
661
+ config["client_secret"] = client_secret
662
+
663
+ try:
664
+ # Create discoverer instance
665
+ discoverer_class = providers[provider]["class_"]
666
+ discoverer = discoverer_class()
667
+
668
+ console.print(
669
+ f"[bold blue]Validating {providers[provider]['name']} configuration...[/bold blue]",
670
+ )
671
+
672
+ # Validate configuration
673
+ discoverer.validate_config(config)
674
+
675
+ console.print("[bold green]✓[/bold green] Configuration is valid!")
676
+
677
+ except Exception as e:
678
+ console.print(f"[bold red]✗[/bold red] Configuration validation failed: {e}")
679
+ sys.exit(1)