-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathush
More file actions
executable file
·905 lines (741 loc) · 32.5 KB
/
ush
File metadata and controls
executable file
·905 lines (741 loc) · 32.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
#!/usr/bin/env python3
"""
ush - ushadow Command Line Tool
Dynamic CLI that auto-discovers commands from OpenAPI spec.
All API endpoints are automatically available as CLI commands.
Examples:
ush # List all command groups
ush services # List services commands
ush services list # GET /api/services/
ush services start chronicle # POST /api/services/{name}/start
ush providers list # GET /api/providers/
ush wizard quickstart # GET /api/wizard/quickstart
"""
import json
import os
import re
import sys
from pathlib import Path
from typing import Any, Optional
from rich.console import Console
from rich.table import Table
# Shell mode imports (lazy loaded)
SHELL_AVAILABLE = True
try:
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.history import FileHistory
from prompt_toolkit.styles import Style
from prompt_toolkit.key_binding import KeyBindings
except ImportError:
SHELL_AVAILABLE = False
# Add project root to path
PROJECT_ROOT = Path(__file__).parent
sys.path.insert(0, str(PROJECT_ROOT))
from ushadow.client import UshadowClient
console = Console()
# =============================================================================
# OpenAPI Spec Loader
# =============================================================================
def load_openapi_spec() -> dict:
"""Load OpenAPI spec from file or fetch from server."""
spec_file = PROJECT_ROOT / "openapi.json"
if spec_file.exists():
with open(spec_file) as f:
return json.load(f)
# Try to fetch from server
try:
client = UshadowClient.from_env()
return client.api("GET", "/openapi.json", auth=False)
except Exception:
console.print("[red]❌ No openapi.json found. Run: curl http://localhost:8000/openapi.json > openapi.json[/red]")
sys.exit(1)
def parse_endpoints(spec: dict) -> dict[str, dict]:
"""
Parse OpenAPI spec into a command structure.
Returns:
{
"services": {
"list": {"method": "GET", "path": "/api/services/", "summary": "...", "params": []},
"start": {"method": "POST", "path": "/api/services/{name}/start", "params": ["name"]},
...
},
"providers": {...},
...
}
"""
commands = {}
for path, methods in spec.get("paths", {}).items():
for method, details in methods.items():
if method not in ("get", "post", "put", "delete"):
continue
# Extract tag (command group)
tags = details.get("tags", ["default"])
tag = tags[0] if tags else "default"
# Skip auth endpoints (handled separately)
if tag == "auth":
continue
# Parse command name from path
# /api/services/{name}/start -> "start"
# /api/services/ -> "list"
# /api/services/{name} -> "get"
cmd_name = extract_command_name(path, method)
# Extract parameters
params = details.get("parameters", [])
path_params = [p["name"] for p in params if p.get("in") == "path"]
query_params = [
{
"name": p["name"],
"required": p.get("required", False),
"description": p.get("description", ""),
"type": p.get("schema", {}).get("type", "string"),
"default": p.get("schema", {}).get("default"),
}
for p in params if p.get("in") == "query"
]
# Check if request body is required
has_body = "requestBody" in details
# Build command entry
if tag not in commands:
commands[tag] = {}
commands[tag][cmd_name] = {
"method": method.upper(),
"path": path,
"summary": details.get("summary", ""),
"description": details.get("description", ""),
"path_params": path_params,
"query_params": query_params,
"has_body": has_body,
"requires_auth": requires_auth(details),
}
return commands
def extract_command_name(path: str, method: str) -> str:
"""
Extract a clean command name from path and method.
/api/services/ + GET -> list
/api/services/{name} + GET -> get
/api/services/{name}/start + POST -> start
/api/services/{name}/logs + GET -> logs
/api/services/catalog + GET -> catalog
"""
# Remove /api/ prefix and tag
parts = path.strip("/").split("/")
if parts[0] == "api":
parts = parts[1:]
if parts:
parts = parts[1:] # Remove tag (services, providers, etc.)
# Handle empty path (list endpoint)
if not parts:
return "list"
# Filter out path parameters
parts = [p for p in parts if not p.startswith("{")]
if not parts:
# Path was just /{param} - this is a "get" operation
return "get" if method == "get" else method
# Join remaining parts with hyphens
name = "-".join(parts)
# Special case: if it's just the tag + method, use method name
if not name:
name = "get" if method == "get" else method
return name
def requires_auth(endpoint_details: dict) -> bool:
"""Check if endpoint requires authentication."""
security = endpoint_details.get("security", [])
# If security is empty list, it's explicitly public
# If security is not present, check global security
return len(security) > 0 or "security" not in endpoint_details
# =============================================================================
# Output Formatters (for pretty output on specific commands)
# =============================================================================
def format_services_list(data: list) -> None:
"""Pretty format for services list."""
table = Table(title="Services", show_header=True, header_style="bold magenta")
table.add_column("Name", style="cyan", width=25)
table.add_column("Status", width=20)
table.add_column("Installed", width=10)
table.add_column("Description", overflow="fold")
for svc in data:
status = svc.get("status", "unknown")
health = svc.get("health")
if status == "running":
status_str = f"🟢 {status}" if health == "healthy" else f"🟡 {status}"
elif status in ("stopped", "not_found", "exited"):
status_str = f"🔴 {status}"
else:
status_str = f"⚪ {status}"
installed = "✅" if svc.get("installed") else "❌"
desc = (svc.get("description") or "")[:40]
table.add_row(svc.get("service_name", "?"), status_str, installed, desc)
console.print(table)
def format_providers_list(data: list) -> None:
"""Pretty format for providers list."""
table = Table(title="Providers", show_header=True, header_style="bold magenta")
table.add_column("ID", style="cyan", width=15)
table.add_column("Name", width=20)
table.add_column("Capability", width=15)
for p in data:
table.add_row(
p.get("id", "?"),
p.get("name", "?"),
p.get("capability", "?"),
)
console.print(table)
# Registry of custom formatters: (tag, command) -> formatter function
FORMATTERS = {
("services", "list"): format_services_list,
("providers", "list"): format_providers_list,
}
# =============================================================================
# CLI Execution
# =============================================================================
def execute_command(
client: UshadowClient,
cmd_info: dict,
path_args: dict[str, str],
query_args: dict[str, Any],
body_data: Optional[dict],
tag: str,
cmd_name: str,
) -> Any:
"""Execute an API command and return the result."""
# Build the path with substituted parameters
path = cmd_info["path"]
for param, value in path_args.items():
path = path.replace(f"{{{param}}}", value)
# Add query parameters
if query_args:
query_str = "&".join(f"{k}={v}" for k, v in query_args.items() if v is not None)
if query_str:
path = f"{path}?{query_str}"
# Make the request
result = client.api(
cmd_info["method"],
path,
data=body_data,
auth=cmd_info["requires_auth"],
)
return result
def print_result(result: Any, tag: str, cmd_name: str) -> None:
"""Print the result, using custom formatter if available."""
formatter = FORMATTERS.get((tag, cmd_name))
if formatter and isinstance(result, list):
formatter(result)
elif isinstance(result, dict) and result.get("success") is not None:
# Action result
if result.get("success"):
console.print(f"[green]✅ {result.get('message', 'Success')}[/green]")
else:
console.print(f"[red]❌ {result.get('message', 'Failed')}[/red]")
else:
# Default: JSON output
console.print(json.dumps(result, indent=2))
def show_help(commands: dict, tag: Optional[str] = None) -> None:
"""Show help for available commands."""
if tag is None:
# Show all command groups
console.print("\n[bold]ushadow CLI[/bold] - Auto-generated from OpenAPI\n")
console.print("[bold]Command Groups:[/bold]")
for group in sorted(commands.keys()):
cmd_count = len(commands[group])
console.print(f" [cyan]{group:<20}[/cyan] ({cmd_count} commands)")
console.print("\n[dim]Usage: ush <group> <command> [args...][/dim]")
console.print("[dim] ush <group> --help[/dim]")
console.print("[dim] ush shell # Interactive mode with Tab completion[/dim]")
console.print("[dim] ush health # Check backend health[/dim]")
console.print("[dim] ush whoami # Show current user info[/dim]")
else:
# Show commands for a specific group
if tag not in commands:
console.print(f"[red]Unknown command group: {tag}[/red]")
console.print(f"[dim]Available: {', '.join(sorted(commands.keys()))}[/dim]")
sys.exit(1)
console.print(f"\n[bold]{tag}[/bold] commands:\n")
for cmd_name, cmd_info in sorted(commands[tag].items()):
params_str = " ".join(f"<{p}>" for p in cmd_info["path_params"])
opts_str = " ".join(f"[--{p['name']}]" for p in cmd_info["query_params"])
full_cmd = f"{cmd_name}"
if params_str:
full_cmd += f" {params_str}"
if opts_str:
full_cmd += f" {opts_str}"
console.print(f" [cyan]{full_cmd:<40}[/cyan] {cmd_info['summary']}")
console.print(f"\n[dim]Usage: ush {tag} <command> [args...][/dim]")
# =============================================================================
# Interactive Shell Mode
# =============================================================================
def guess_name_field(item: dict, group: str) -> str | None:
"""
Guess which field contains the resource name/identifier.
Args:
item: A single item from the list response
group: The command group name (e.g., "services")
Returns:
The field name that likely contains the identifier, or None
TODO: Implement your preferred field detection logic here.
Consider: What fields should take priority? How to handle edge cases?
"""
# Common patterns to try, in priority order
candidates = [
f"{group.rstrip('s')}_name", # service_name, provider_name
f"{group.rstrip('s')}_id", # service_id, provider_id
"name",
"id",
"key",
"slug",
]
for field in candidates:
if field in item and item[field]:
return field
# Fallback: first string field that looks like an identifier
for key, value in item.items():
if isinstance(value, str) and value and not key.startswith("_"):
return key
return None
def get_resource_endpoints(spec: dict) -> dict[str, tuple[str, str]]:
"""
Auto-detect resource list endpoints from OpenAPI spec.
Looks for GET /api/{group}/ endpoints and guesses the name field.
Falls back to manual overrides for known edge cases.
Returns dict of: group -> (list_endpoint, name_field)
"""
# Manual overrides for edge cases where auto-detection fails
overrides = {
"services": ("/api/services/", "service_name"),
"docker": ("/api/docker/containers", "name"),
"kubernetes": ("/api/kubernetes/namespaces", "name"),
}
endpoints = dict(overrides)
# Auto-detect from OpenAPI spec
for path, methods in spec.get("paths", {}).items():
if "get" not in methods:
continue
# Match /api/{group}/ pattern (list endpoints)
match = re.match(r"^/api/([^/]+)/?$", path)
if not match:
continue
group = match.group(1)
# Skip if we have a manual override
if group in overrides:
continue
# Check if response is an array (list endpoint)
responses = methods["get"].get("responses", {})
success = responses.get("200", {})
content = success.get("content", {}).get("application/json", {})
schema = content.get("schema", {})
if schema.get("type") == "array" or "items" in schema:
# This is a list endpoint - we'll guess the name field at runtime
endpoints[group] = (path, "__auto__")
return endpoints
class UshCompleter(Completer):
"""
Nested completer for ush shell with resource-first completion.
Tab 1: Complete command group (services, providers, etc.)
Tab 2: Complete resource name OR command (fetched from API)
Tab 3: Complete command for that resource, or parameters
Example flow:
services <Tab> → shows: mem0, chronicle, ... AND list, catalog, ...
services mem0 <Tab> → shows: start, stop, logs, status, ...
"""
def __init__(self, commands: dict, client: "UshadowClient", spec: dict):
self.commands = commands
self.client = client
self.spec = spec
self.special_commands = {"help", "exit", "quit", "health", "whoami"}
# Cache for resource lists: {"services": ["mem0", "chronicle", ...]}
self._resource_cache: dict[str, list[str]] = {}
# Map: group -> (list_endpoint, name_field)
# Auto-detected from OpenAPI spec with manual overrides
self.resource_endpoints = get_resource_endpoints(spec)
def _get_resources(self, group: str) -> list[str]:
"""Fetch and cache resource names for a group."""
if group in self._resource_cache:
return self._resource_cache[group]
if group not in self.resource_endpoints:
return []
endpoint, name_field = self.resource_endpoints[group]
try:
result = self.client.api("GET", endpoint, auth=True)
if isinstance(result, list) and result:
# Auto-detect name field if marked as __auto__
if name_field == "__auto__":
name_field = guess_name_field(result[0], group)
if not name_field:
return []
names = [item.get(name_field, "") for item in result if item.get(name_field)]
self._resource_cache[group] = names
return names
except Exception:
pass # Silently fail - just won't have completions
return []
def _get_commands_for_resource(self, group: str) -> list[str]:
"""Get commands that operate on a specific resource (have path params)."""
if group not in self.commands:
return []
return [
cmd for cmd, info in self.commands[group].items()
if info.get("path_params") # Commands that take a resource name
]
def _get_standalone_commands(self, group: str) -> list[str]:
"""Get commands that don't need a resource (list, catalog, etc.)."""
if group not in self.commands:
return []
return [
cmd for cmd, info in self.commands[group].items()
if not info.get("path_params") # Commands without path params
]
def get_completions(self, document, complete_event):
text = document.text_before_cursor
words = text.split()
word_count = len(words)
# Handle partial word at cursor
word_before_cursor = document.get_word_before_cursor()
# Key fix: if text ends with space, we're completing a NEW word
at_new_word = text.endswith(" ") or text == ""
if not at_new_word and words:
word_count -= 1
if word_count == 0:
# === Position 1: Command groups + special commands ===
for cmd in sorted(self.special_commands):
if cmd.startswith(word_before_cursor):
yield Completion(cmd, start_position=-len(word_before_cursor),
display_meta="built-in")
for group in sorted(self.commands.keys()):
if group.startswith(word_before_cursor):
cmd_count = len(self.commands[group])
yield Completion(group, start_position=-len(word_before_cursor),
display_meta=f"{cmd_count} commands")
elif word_count == 1:
# === Position 2: Resources AND standalone commands ===
# e.g., "services <Tab>" shows: mem0, chronicle, ... AND list, catalog
group = words[0]
if group not in self.commands:
return
# First: standalone commands (list, catalog, etc.)
for cmd in sorted(self._get_standalone_commands(group)):
if cmd.startswith(word_before_cursor):
cmd_info = self.commands[group][cmd]
yield Completion(cmd, start_position=-len(word_before_cursor),
display_meta=cmd_info.get("summary", "")[:40])
# Then: resource names from API
for name in sorted(self._get_resources(group)):
if name.startswith(word_before_cursor):
yield Completion(name, start_position=-len(word_before_cursor),
display_meta="resource")
elif word_count == 2:
# === Position 3: Depends on what position 2 was ===
group = words[0]
second = words[1]
if group not in self.commands:
return
resources = self._get_resources(group)
if second in resources:
# User selected a resource → show commands for it
for cmd in sorted(self._get_commands_for_resource(group)):
if cmd.startswith(word_before_cursor):
cmd_info = self.commands[group][cmd]
yield Completion(cmd, start_position=-len(word_before_cursor),
display_meta=cmd_info.get("summary", "")[:40])
elif second in self.commands[group]:
# User selected a command → show path params or resources
cmd_info = self.commands[group][second]
path_params = cmd_info.get("path_params", [])
if path_params:
# Show resources as completions for the first path param
for name in sorted(resources):
if name.startswith(word_before_cursor):
yield Completion(name, start_position=-len(word_before_cursor),
display_meta=f"<{path_params[0]}>")
elif word_count >= 3:
# === Position 4+: Additional params or query params ===
group = words[0]
second = words[1]
third = words[2]
if group not in self.commands:
return
resources = self._get_resources(group)
# Determine the command and resource
if second in resources and third in self.commands[group]:
# Pattern: services mem0 start [additional params]
cmd_info = self.commands[group][third]
provided_count = word_count - 3
elif second in self.commands[group]:
# Pattern: services start mem0 [additional params]
cmd_info = self.commands[group][second]
provided_count = word_count - 3
else:
return
# Query parameters
for qp in cmd_info.get("query_params", []):
opt = f"--{qp['name']}"
if opt.startswith(word_before_cursor) and opt not in words:
meta = qp.get("description", "")[:30] or ("required" if qp.get("required") else "optional")
yield Completion(opt, start_position=-len(word_before_cursor),
display_meta=meta)
def run_shell(commands: dict, client: UshadowClient, spec: dict) -> None:
"""Run interactive shell with nested completion and fish-style suggestions."""
if not SHELL_AVAILABLE:
console.print("[red]Shell mode requires prompt_toolkit. Install with:[/red]")
console.print("[dim] pip install prompt_toolkit[/dim]")
sys.exit(1)
# Shell styling - includes completion menu styling
style = Style.from_dict({
"prompt": "cyan bold",
"": "#ffffff",
# Completion menu styling
"completion-menu": "bg:#333333 #ffffff",
"completion-menu.completion": "bg:#333333 #ffffff",
"completion-menu.completion.current": "bg:#00aa00 #000000",
"completion-menu.meta.completion": "bg:#444444 #aaaaaa",
"completion-menu.meta.completion.current": "bg:#00aa00 #000000",
})
# History file
history_file = Path.home() / ".ush_history"
# Create session with completion and history
# reserve_space_for_menu pushes prompt up so menu is visible at bottom of screen
session = PromptSession(
completer=UshCompleter(commands, client, spec),
auto_suggest=AutoSuggestFromHistory(),
history=FileHistory(str(history_file)),
style=style,
complete_while_typing=False,
complete_in_thread=True,
reserve_space_for_menu=8,
)
console.print("\n[bold cyan]ushadow shell[/bold cyan] - Type commands, Tab to complete, ↑/↓ for history")
console.print("[dim]Type 'help' for commands, 'whoami' for user info, 'exit' to quit[/dim]\n")
while True:
try:
# Get input with completion
text = session.prompt("ushadow> ").strip()
if not text:
continue
# Handle special commands
if text in ("exit", "quit"):
console.print("[dim]Goodbye![/dim]")
break
if text == "help":
show_help(commands)
continue
if text == "health":
try:
result = client.health()
console.print("[green]✅ ushadow backend healthy[/green]")
except Exception as e:
console.print(f"[red]❌ Backend unreachable: {e}[/red]")
continue
if text == "whoami":
try:
# Get current user info from /api/auth/me
result = client.api("GET", "/api/auth/me", auth=True)
console.print("\n[bold]Current User:[/bold]")
console.print(f" Email: {result.get('email', 'N/A')}")
console.print(f" Name: {result.get('display_name', 'N/A')}")
console.print(f" Superuser: {result.get('is_superuser', False)}")
console.print(f" Active: {result.get('is_active', False)}")
console.print(f" Verified: {result.get('is_verified', False)}\n")
except Exception as e:
console.print(f"[red]❌ Failed to get user info: {e}[/red]")
continue
# Parse and execute command
args = text.split()
if len(args) < 1:
continue
tag = args[0]
if tag not in commands:
console.print(f"[red]Unknown: {tag}[/red] - try 'help'")
continue
if len(args) == 1:
show_help(commands, tag)
continue
# Support both orderings:
# services start mem0 (command-first, original)
# services mem0 start (resource-first, new)
second = args[1]
third = args[2] if len(args) > 2 else None
# Get cached resources for this group
completer = session.completer
resources = completer._get_resources(tag) if hasattr(completer, '_get_resources') else []
# Determine command and resource based on what was typed
if second in commands[tag]:
# Command-first: services start mem0
cmd_name = second
cmd_info = commands[tag][cmd_name]
remaining = args[2:]
elif second in resources and third and third in commands[tag]:
# Resource-first: services mem0 start
cmd_name = third
cmd_info = commands[tag][cmd_name]
# Pre-fill the resource as the first path param
remaining = [second] + args[3:]
elif second in resources:
# Just resource, no command yet: services mem0
console.print(f"[yellow]Select a command for {second}:[/yellow]")
resource_cmds = [c for c, i in commands[tag].items() if i.get("path_params")]
console.print(f"[dim]{', '.join(sorted(resource_cmds))}[/dim]")
continue
else:
console.print(f"[red]Unknown: {tag} {second}[/red]")
console.print(f"[dim]Available commands: {', '.join(sorted(commands[tag].keys()))}[/dim]")
continue
# Parse path parameters
path_args = {}
for param in cmd_info["path_params"]:
if not remaining:
console.print(f"[red]Missing: <{param}>[/red]")
continue
path_args[param] = remaining.pop(0)
# Parse query parameters
query_args = {}
body_data = None
i = 0
while i < len(remaining):
arg = remaining[i]
if arg.startswith("--"):
param_name = arg[2:]
if i + 1 < len(remaining) and not remaining[i + 1].startswith("-"):
query_args[param_name] = remaining[i + 1]
i += 2
else:
query_args[param_name] = True
i += 1
elif arg in ("--data", "-d") and i + 1 < len(remaining):
try:
body_data = json.loads(remaining[i + 1])
except json.JSONDecodeError as e:
console.print(f"[red]Invalid JSON: {e}[/red]")
i += 2
else:
i += 1
# Execute
try:
result = execute_command(client, cmd_info, path_args, query_args, body_data, tag, cmd_name)
print_result(result, tag, cmd_name)
except Exception as e:
console.print(f"[red]Error: {e}[/red]")
except KeyboardInterrupt:
console.print("\n[dim]Ctrl+C - type 'exit' to quit[/dim]")
except EOFError:
console.print("\n[dim]Goodbye![/dim]")
break
def main():
"""Main CLI entry point."""
# Load and parse OpenAPI spec
spec = load_openapi_spec()
commands = parse_endpoints(spec)
# Parse arguments
args = sys.argv[1:]
# No arguments - show help
if not args:
show_help(commands)
return
# Handle special commands
if args[0] in ("--help", "-h", "help"):
show_help(commands)
return
if args[0] == "health":
try:
client = UshadowClient.from_env()
result = client.health()
console.print("[green]✅ ushadow backend healthy[/green]")
if "--verbose" in args or "-v" in args:
console.print(json.dumps(result, indent=2))
except Exception as e:
console.print(f"[red]❌ Backend unreachable: {e}[/red]")
sys.exit(1)
return
if args[0] == "whoami":
try:
verbose = "--verbose" in args or "-v" in args
client = UshadowClient.from_env(verbose=verbose)
result = client.api("GET", "/api/auth/me", auth=True)
console.print("\n[bold]Current User:[/bold]")
console.print(f" Email: {result.get('email', 'N/A')}")
console.print(f" Name: {result.get('display_name', 'N/A')}")
console.print(f" Superuser: {result.get('is_superuser', False)}")
console.print(f" Active: {result.get('is_active', False)}")
console.print(f" Verified: {result.get('is_verified', False)}")
if verbose:
console.print(f"\n[dim]Full response:[/dim]")
console.print(json.dumps(result, indent=2))
except Exception as e:
console.print(f"[red]❌ Failed to get user info: {e}[/red]")
sys.exit(1)
return
if args[0] == "shell":
try:
client = UshadowClient.from_env()
run_shell(commands, client, spec)
except Exception as e:
console.print(f"[red]❌ Cannot start shell: {e}[/red]")
sys.exit(1)
return
# Get command group
tag = args[0]
if tag not in commands:
console.print(f"[red]Unknown command group: {tag}[/red]")
console.print(f"[dim]Available: {', '.join(sorted(commands.keys()))}[/dim]")
sys.exit(1)
# Help for command group
if len(args) == 1 or args[1] in ("--help", "-h", "help"):
show_help(commands, tag)
return
# Get command
cmd_name = args[1]
if cmd_name not in commands[tag]:
console.print(f"[red]Unknown command: {tag} {cmd_name}[/red]")
console.print(f"[dim]Available: {', '.join(sorted(commands[tag].keys()))}[/dim]")
sys.exit(1)
cmd_info = commands[tag][cmd_name]
remaining_args = args[2:]
# Parse path parameters (positional)
path_args = {}
for param in cmd_info["path_params"]:
if not remaining_args:
console.print(f"[red]Missing required argument: <{param}>[/red]")
console.print(f"[dim]Usage: ush {tag} {cmd_name} <{param}>[/dim]")
sys.exit(1)
path_args[param] = remaining_args.pop(0)
# Parse query parameters and options
query_args = {}
body_data = None
verbose = False
i = 0
while i < len(remaining_args):
arg = remaining_args[i]
if arg in ("--verbose", "-v"):
verbose = True
i += 1
elif arg in ("--data", "-d") and i + 1 < len(remaining_args):
try:
body_data = json.loads(remaining_args[i + 1])
except json.JSONDecodeError as e:
console.print(f"[red]Invalid JSON: {e}[/red]")
sys.exit(1)
i += 2
elif arg.startswith("--"):
# Query parameter
param_name = arg[2:]
if i + 1 < len(remaining_args) and not remaining_args[i + 1].startswith("-"):
query_args[param_name] = remaining_args[i + 1]
i += 2
else:
query_args[param_name] = True
i += 1
else:
console.print(f"[yellow]Warning: Unexpected argument: {arg}[/yellow]")
i += 1
# Execute command
try:
client = UshadowClient.from_env(verbose=verbose)
if verbose:
console.print(f"[dim]🔗 {cmd_info['method']} {cmd_info['path']}[/dim]")
result = execute_command(
client, cmd_info, path_args, query_args, body_data, tag, cmd_name
)
print_result(result, tag, cmd_name)
except Exception as e:
console.print(f"[red]❌ Error: {e}[/red]")
sys.exit(1)
if __name__ == "__main__":
main()