Coverage for src/meshadmin/cli/commands/context.py: 100%

49 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-04-22 07:26 +0200

1from typing import Annotated 

2 

3import structlog 

4import typer 

5import yaml 

6 

7from meshadmin.cli.config import get_config 

8 

9context_app = typer.Typer() 

10logger = structlog.get_logger(__name__) 

11 

12 

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) 

21 

22 contexts = {} 

23 if config.contexts_file.exists(): 

24 with open(config.contexts_file) as f: 

25 contexts = yaml.safe_load(f) or {} 

26 

27 # If this is the first context, make it active 

28 is_first = len(contexts) == 0 

29 

30 contexts[name] = { 

31 "endpoint": endpoint, 

32 "interface": interface, 

33 "active": is_first, 

34 } 

35 

36 with open(config.contexts_file, "w") as f: 

37 yaml.dump(contexts, f) 

38 

39 print(f"Created context '{name}'") 

40 if is_first: 

41 print(f"Set '{name}' as active context") 

42 

43 

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) 

50 

51 with open(config.contexts_file) as f: 

52 contexts = yaml.safe_load(f) or {} 

53 

54 if name not in contexts: 

55 print(f"Context '{name}' not found") 

56 raise typer.Exit(1) 

57 

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 

62 

63 with open(config.contexts_file, "w") as f: 

64 yaml.dump(contexts, f) 

65 

66 print(f"Switched to context '{name}'") 

67 

68 

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 

75 

76 with open(config.contexts_file) as f: 

77 contexts = yaml.safe_load(f) 

78 

79 for name, data in contexts.items(): 

80 print( 

81 f"{'* ' if data.get('active') else ' '}{name} ({data['endpoint']}) ({data['interface']})" 

82 )