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
« 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."""
3from pathlib import Path
5import click
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
12def generate_recovery_script(ctx: WorkstackContext) -> Path | None:
13 """Create a recovery script that returns to the repo root if cwd vanishes.
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
26 if not current_dir.exists():
27 return None
29 try:
30 repo = discover_repo_context(ctx, current_dir)
31 except (FileNotFoundError, ValueError):
32 return None
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 )
40 script_path = write_script_to_temp(
41 script_content,
42 command_name="prepare",
43 comment="pre-generated by __prepare_cwd_recovery",
44 )
46 return script_path
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
61 click.echo(str(script_path), nl=False)