Coverage for src/meshadmin/cli/commands/context.py: 100%
49 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-06 11:34 +0200
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-06 11:34 +0200
1from typing import Annotated
3import structlog
4import typer
5import yaml
7from meshadmin.cli.config import get_config
9context_app = typer.Typer()
10logger = structlog.get_logger(__name__)
13@context_app.command(name="create")
14def create_context(
15 name: Annotated[str, typer.Argument()],
16 endpoint: Annotated[str, typer.Option()],
17 interface: Annotated[str, typer.Option()] = "nebula1",
18):
19 config = get_config()
20 config.contexts_file.parent.mkdir(parents=True, exist_ok=True)
22 contexts = {}
23 if config.contexts_file.exists():
24 with open(config.contexts_file) as f:
25 contexts = yaml.safe_load(f) or {}
27 # If this is the first context, make it active
28 is_first = len(contexts) == 0
30 contexts[name] = {
31 "endpoint": endpoint,
32 "interface": interface,
33 "active": is_first,
34 }
36 with open(config.contexts_file, "w") as f:
37 yaml.dump(contexts, f)
39 print(f"Created context '{name}'")
40 if is_first:
41 print(f"Set '{name}' as active context")
44@context_app.command(name="use")
45def use_context(name: str):
46 config = get_config()
47 if not config.contexts_file.exists():
48 print("No contexts found")
49 raise typer.Exit(1)
51 with open(config.contexts_file) as f:
52 contexts = yaml.safe_load(f) or {}
54 if name not in contexts:
55 print(f"Context '{name}' not found")
56 raise typer.Exit(1)
58 # Deactivate all contexts and activate the selected one
59 for context_name in contexts:
60 contexts[context_name]["active"] = False
61 contexts[name]["active"] = True
63 with open(config.contexts_file, "w") as f:
64 yaml.dump(contexts, f)
66 print(f"Switched to context '{name}'")
69@context_app.command(name="list")
70def list_contexts():
71 config = get_config()
72 if not config.contexts_file.exists():
73 print("No contexts found")
74 return
76 with open(config.contexts_file) as f:
77 contexts = yaml.safe_load(f)
79 for name, data in contexts.items():
80 print(
81 f"{'* ' if data.get('active') else ' '}{name} ({data['endpoint']}) ({data['interface']})"
82 )