Coverage for src/workstack/cli/commands/prepare_cwd_recovery.py: 96%

26 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-19 09:31 -0400

1"""Hidden command that pre-generates recovery scripts for passthrough flows.""" 

2 

3from pathlib import Path 

4 

5import click 

6 

7from workstack.cli.core import discover_repo_context 

8from workstack.cli.shell_utils import render_cd_script, write_script_to_temp 

9from workstack.core.context import WorkstackContext 

10 

11 

12def generate_recovery_script(ctx: WorkstackContext) -> Path | None: 

13 """Create a recovery script that returns to the repo root if cwd vanishes. 

14 

15 This helper intentionally guards against runtime cwd races: 

16 - Path.cwd() may raise FileNotFoundError if the directory vanished between invocations. 

17 - discover_repo_context() performs the authoritative repo lookup; probing earlier provides 

18 no additional safety and merely repeats the work. 

19 - Returning None signals that graceful degradation is preferred to exploding at the boundary. 

20 """ 

21 try: 

22 current_dir = Path.cwd() 

23 except FileNotFoundError: 

24 return None 

25 

26 if not current_dir.exists(): 

27 return None 

28 

29 try: 

30 repo = discover_repo_context(ctx, current_dir) 

31 except (FileNotFoundError, ValueError): 

32 return None 

33 

34 script_content = render_cd_script( 

35 repo.root, 

36 comment="workstack passthrough recovery script", 

37 success_message="✓ Workstack detected a removed directory and returned to repo root.", 

38 ) 

39 

40 script_path = write_script_to_temp( 

41 script_content, 

42 command_name="prepare", 

43 comment="pre-generated by __prepare_cwd_recovery", 

44 ) 

45 

46 return script_path 

47 

48 

49@click.command( 

50 "__prepare_cwd_recovery", 

51 hidden=True, 

52 add_help_option=False, 

53) 

54@click.pass_obj 

55def prepare_cwd_recovery_cmd(ctx: WorkstackContext) -> None: 

56 """Emit a recovery script if we are inside a managed repository.""" 

57 script_path = generate_recovery_script(ctx) 

58 if script_path is None: 

59 return 

60 

61 click.echo(str(script_path), nl=False)