Coverage for packages/workshop/src/livery/workshop/_shell.py: 85%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop, packages/extensions/ty, packages/extensions/ruff, packages/extensions/python, packages/extensions/pytest, packages/extensions/pyrefly, packages/extensions/nanobind, packages/extensions/mypy, packages/extensions/mkdocstrings, packages/extensions/lfs, packages/extensions/docs, packages/extensions/cpp, packages/extensions/coverage, packages/extensions/conan, packages/extensions/cmake, packages/extensions/claude, packages/extensions/clang-tidy, packages/extensions/clang-format, packages/extensions/changelog, packages/extensions/basedpyright ran.

1"""The entered-shell entry: a fully configured interactive shell.
2
3``fm shell [kind]`` makes the target shell itself evaluate
4``fm -C=<root> --quiet env.emit <dialect>`` at its own startup,
5injected through a dialect-specific rc mechanism. The completion
6hook is a shell function that never survives an exec, so evaluating
7the emission in a wrapper and exec'ing the target would lose it;
8evaluated inside the target, environment and completion both land in
9the final interactive shell. A cold checkout fails loudly inside the
10opened shell: the emission's refusal prints to stderr, never a shell
11that merely looks entered.
12
13The launch decisions are data (``shell_launch_plan`` answers
14argv, environment, and rc files) so every branch tests as a plain
15call; the task body only writes and execs them.
16"""
17
18from __future__ import annotations(empty)
19
20import os(empty)
21import shlex(empty)
22import shutil(empty)
23import subprocess(empty)
24import sys(empty)
25from dataclasses import dataclass, field(empty)
26from pathlib import Path(empty)
27
28import livery.footman as footman(empty)
29from livery.footman import Arg, Stdout, group(empty)
30
31_KINDS = ("bash", "zsh", "pwsh")(empty)
32
33# Evaluated INSIDE the launched shell: environment, PATH, and the
34# interactive completion hook, all from the one emission. --quiet
35# drops the receipt rows; stderr stays live so a cold refusal
36# teaches. {root} arrives already quoted for the dialect: a checkout
37# path may hold a quote or a space, and spliced raw it ends the
38# string early and breaks the whole eval.
39_POSIX_ENTER = 'eval "$({prog} -C={root} --quiet env.emit posix)"'(empty)
40_PWSH_ENTER = '({prog} -C={root} --quiet env.emit pwsh) -join "`n" | Invoke-Expression'(empty)
41
42
43def _posix_root(root: Path) -> str:(empty)
44 """*root* as one POSIX shell word."""
45 return shlex.quote(str(root))
46
47
48def _pwsh_root(root: Path) -> str:(empty)
49 """*root* as one PowerShell single-quoted string.
50
51 PowerShell escapes a single quote by doubling it; there is no
52 backslash escape inside single quotes.
53 """
54 return "'" + str(root).replace("'", "''") + "'"
55
56
57@dataclass(empty)
58class ShellLaunch:(empty)
59 """Everything needed to open the entered shell, as pure data."""
60
61 argv: list[str](empty)
62 env: dict[str, str] = field(default_factory=dict)(empty)
63 files: dict[Path, str] = field(default_factory=dict)(empty)
64
65
66def default_kind() -> str:(empty)
67 """The platform's interactive shell: ``$SHELL``'s basename, else pwsh/bash."""
68 if sys.platform == "win32":
69 return "pwsh"
70 name = Path(os.environ.get("SHELL", "")).name
71 return name if name in _KINDS else "bash"
72
73
74def _git_bash() -> str | None:(empty)
75 r"""The Git-Bash executable on Windows, or None.
76
77 A vendored install exports ``CLAUDE_CODE_GIT_BASH_PATH``; a
78 system Git for Windows puts ``<root>/cmd/git.exe`` on PATH but
79 not ``<root>/bin/bash.exe``, so one derives from the other.
80 Never a bare ``bash`` fallback: that finds WSL's
81 ``System32\bash.exe``.
82 """
83 vendored = os.environ.get("CLAUDE_CODE_GIT_BASH_PATH", "")
84 if vendored and os.path.isfile(vendored):84 ↛ 85line 84 didn't jump to line 85 because the condition on line 84 was never true
85 return vendored
86 git = shutil.which("git")
87 if git:87 ↛ 93line 87 didn't jump to line 93 because the condition on line 87 was always true
88 candidate = os.path.join(
89 os.path.dirname(os.path.dirname(git)), "bin", "bash.exe"
90 )
91 if os.path.isfile(candidate):91 ↛ 93line 91 didn't jump to line 93 because the condition on line 91 was always true
92 return candidate
93 return None
94
95
96def _resolve_binary(kind: str) -> str:(empty)
97 """The concrete shell executable for *kind*, or a taught refusal."""
98 if sys.platform == "win32":
99 if kind == "bash":
100 found = _git_bash()
101 elif kind == "pwsh":
102 found = shutil.which("pwsh") or shutil.which("powershell")
103 else:
104 found = shutil.which(kind)
105 else:
106 found = shutil.which(kind)
107 if not found:107 ↛ 108line 107 didn't jump to line 108 because the condition on line 107 was never true
108 raise SystemExit(f"no {kind} shell available on this machine")
109 return found
110
111
112def shell_launch_plan(kind: str, *, root: Path, tmp_dir: Path) -> ShellLaunch:(empty)
113 """The launch plan for an entered *kind* shell rooted at *root*.
114
115 bash takes the injection through ``--rcfile`` (which replaces
116 ``~/.bashrc``, so the rc sources it first; ``/etc`` rc files
117 load regardless); zsh through a throwaway ``ZDOTDIR`` whose
118 ``.zshenv`` and ``.zshrc`` chain to the user's own (``ZDOTDIR``
119 resets to the home inside, so nested shells behave); pwsh
120 through ``-NoExit -Command`` with the user profile still
121 loading. cmd is refused: it has no startup file to inject, so a
122 launched cmd only inherits a cold caller and looks entered
123 without being entered; pwsh delivers the full contract on
124 Windows.
125 """
126 if kind == "cmd":
127 raise SystemExit(
128 "cmd has no startup file to evaluate the emission, so it"
129 " cannot be entered reliably; use pwsh on Windows."
130 )
131 if kind not in _KINDS:
132 raise SystemExit(f"unknown shell kind '{kind}' - one of: {', '.join(_KINDS)}")
133 binary = _resolve_binary(kind)
134
135 enter = _POSIX_ENTER.format(prog=footman.prog(), root=_posix_root(root))
136 if kind == "bash":
137 rc = tmp_dir / "livery-shell-bashrc"
138 content = f'[ -f "$HOME/.bashrc" ] && . "$HOME/.bashrc"\n{enter}\n'
139 return ShellLaunch(
140 argv=[binary, "--rcfile", str(rc), "-i"], files={rc: content}
141 )
142 if kind == "zsh":
143 zdot = tmp_dir / "livery-shell-zdot"
144 zshenv = '[ -f "$HOME/.zshenv" ] && . "$HOME/.zshenv"\n'
145 zshrc = (
146 'ZDOTDIR="$HOME"\n'
147 + '[ -f "$HOME/.zshrc" ] && . "$HOME/.zshrc"\n'
148 + enter
149 + "\n"
150 )
151 return ShellLaunch(
152 argv=[binary, "-i"],
153 env={"ZDOTDIR": str(zdot)},
154 files={zdot / ".zshenv": zshenv, zdot / ".zshrc": zshrc},
155 )
156 return ShellLaunch(
157 argv=[
158 binary,
159 "-NoLogo",
160 "-NoExit",
161 "-Command",
162 _PWSH_ENTER.format(prog=footman.prog(), root=_pwsh_root(root)),
163 ]
164 )
165
166
167def _realise(kind: str) -> ShellLaunch:(empty)
168 """The plan for *kind*, with its rc files written to disk."""
169 import livery.footman as footman
170
171 resolved = kind or default_kind()
172 tmp_dir = footman.scratch_dir("shell")
173 plan = shell_launch_plan(resolved, root=footman.cwd(), tmp_dir=tmp_dir)
174 for path, content in plan.files.items():
175 path.parent.mkdir(parents=True, exist_ok=True)
176 path.write_text(content, encoding="utf-8")
177 return plan
178
179
180def launch_shell(kind: str = "") -> None:(empty)
181 """Open the entered shell; never returns on POSIX, waits on Windows.
182
183 POSIX execs, nothing left behind. Windows has no real exec, so
184 the launcher waits and forwards the exit code: the console needs
185 an owner.
186 """
187 plan = _realise(kind)
188 env = {**os.environ, **plan.env}
189 if sys.platform == "win32":
190 result = subprocess.run(plan.argv, env=env, cwd=os.getcwd(), check=False)
191 raise SystemExit(result.returncode)
192 os.execvpe(plan.argv[0], plan.argv, env)
193
194
195shell = group("shell", help="Open a fully entered interactive shell")(empty)
196
197
198@shell.default(interactive=True, shared=False)(empty)
199def shell_default((empty)
200 kind: Arg[str] = "",
201) -> None:
202 """Open an entered shell of *kind* (bash, zsh, or pwsh).
203
204 The launched shell evaluates ``fm env.emit`` at its own startup,
205 so environment, PATH, and completion land inside it. Bare picks
206 ``$SHELL``'s kind, pwsh on Windows.
207 """
208 launch_shell(kind)
209
210
211@shell.task(name="prepare", hidden=True)(empty)
212def shell_prepare((empty)
213 kind: Arg[str] = "",
214) -> Stdout[list[str]]:
215 """Prepare an entered launch: write its rc files, answer its argv.
216
217 The handoff for a launcher that must not keep a resident Python:
218 the caller launches the argv itself. Writing the rc files here
219 is the job, not a side errand; an argv naming a missing rc opens
220 a shell that looks entered and is not. A plan that needs
221 environment variables (zsh's throwaway ``ZDOTDIR``) is refused
222 rather than returned half-working.
223 """
224 plan = _realise(kind)
225 if plan.env:225 ↛ 231line 225 didn't jump to line 231 because the condition on line 225 was always true
226 names = ", ".join(sorted(plan.env))
227 raise SystemExit(
228 f"{kind or default_kind()} cannot be handed off as an argv:"
229 f" it needs {names} set in the environment"
230 )
231 return plan.argv