Coverage for src/rhiza_task/uv.py: 100%

62 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-11-30 09:28 +0000

1"""The ways rhiza reaches a tool, and nothing else. 

2 

3Every recipe in the retired *Python* make layer used one of exactly three forms: 

4 

5* ``uv <subcommand>`` -- uv itself (``venv``, ``sync``, ``lock --check``). 

6* ``uvx <tool>`` -- an isolated one-shot tool run: prek, bandit, semgrep, zensical, 

7 genbadge. 

8* ``uv run --with a --with b <tool>`` -- a tool run *against the project environment*, 

9 because it imports the project's own code: pytest, interrogate, hypothesis, ty, mypy. 

10 

11deptry is the one tool that moved between them. The make layer ran it via ``uvx``, but it 

12reads the project's *installed* metadata to map a distribution to its import name 

13(``pyyaml`` to ``yaml``), so it now runs in the third form (#222). 

14 

15The second and third are a real distinction that the make layer already gets right, so it 

16is preserved here rather than unified. 

17 

18rust.mk and go.mk add a fourth: ``$(CARGO) nextest run``, ``$(GO) test`` -- a toolchain 

19binary that is already on PATH, because uv does not provision cargo or go and nothing here 

20pretends otherwise. :func:`tool` is that form. It shares this module's environment handling 

21and echoing rather than being a bare ``subprocess.call`` in each language module, so 

22``$ cargo clippy`` is printed the same way ``$ uvx bandit`` is. 

23 

24go.mk contributes one more, and it is the one that gets missed when these are counted: 

25:func:`capture`, which returns *stdout* rather than an exit status, for the recipe that 

26needs a value back rather than a verdict -- the licence gate, which has to interpolate 

27``go list -m`` into its own arguments. It is easy to overlook precisely because it is the 

28only form whose caller reads the result instead of just its status, and #131 is what that 

29cost: every prose total for this module disagreed with the code, and with the others. So no 

30sentence here gives one -- the public functions below are the authority, and a total in 

31prose goes stale the moment a form is added. 

32 

33Two things disappear: 

34 

35``install-uv`` as a *task*. bootstrap.mk curls ``https://astral.sh/uv/install.sh`` into 

36``./bin`` because make cannot assume uv exists. A process launched by ``uvx rhiza-task`` 

37runs *because* uv exists, so nothing in this package can be the thing that provisions uv -- 

38it would already be too late. The problem does not disappear with it, though: the make 

39layer's contract was that ``make <anything>`` works on a bare runner, so the bootstrap 

40lives on in the Makefile shim as three lines and one file target. What is gone is the 30 

41lines of probe-and-branch shell, and the ``bin/uv`` nobody ran directly. 

42 

43The shell. Commands are argument vectors, never shell strings. rhiza.mk carries a 40-line 

44probe to detect make falling back to ``cmd.exe`` on Windows, because its recipes are 

45POSIX shell; with no shell there is nothing to detect. 

46""" 

47 

48from __future__ import annotations 

49 

50import os 

51import shutil 

52 

53# Every call in this module is a fixed argument vector, and `shell=True` appears nowhere -- which 

54# is what bandit's B404 asks about. The reason sits here rather than on the suppression comment 

55# itself: bandit reads everything after that marker as a comma-separated list of test IDs, so a 

56# trailing explanation becomes one `Test in comment:` warning per word. 

57import subprocess # nosec B404 

58import sys 

59from collections.abc import Mapping, Sequence 

60from pathlib import Path 

61 

62from .spec import Failed 

63 

64BLUE = "\033[36m" 

65RESET = "\033[0m" 

66 

67 

68def _bin(name: str, env_var: str) -> str: 

69 """Resolve a uv executable, honouring an override. 

70 

71 Args: 

72 name: ``uv`` or ``uvx``. 

73 env_var: The override variable, e.g. ``RHIZA_UV_BIN``. 

74 

75 Returns: 

76 An absolute path when one is found, else the bare name so the OS reports the 

77 failure with its own message. 

78 """ 

79 return os.environ.get(env_var) or shutil.which(name) or name 

80 

81 

82def _run( 

83 argv: Sequence[str], 

84 cwd: Path, 

85 env: Mapping[str, str] | None = None, 

86 unset: Sequence[str] = (), 

87) -> int: 

88 """Run a command, streaming its output, and return the exit status. 

89 

90 Args: 

91 argv: The full argument vector. 

92 cwd: Working directory. 

93 env: Extra environment variables, merged over the current environment. 

94 unset: Variables to remove from the inherited environment, applied after ``env``. 

95 

96 Returns: 

97 The process exit status. 

98 """ 

99 # Built as an explicitly typed dict rather than a `{**a, **b}` literal: subprocess's 

100 # `env` parameter is narrowly typed, and the inferred type of the literal is not 

101 # assignable to it. 

102 merged: dict[str, str] = dict(os.environ) 

103 merged.update(env or {}) 

104 # Removal is its own parameter rather than an empty value in `env`, because an empty 

105 # string is not the same as absent to every reader: `dist-check` strips version 

106 # overrides such as SETUPTOOLS_SCM_PRETEND_VERSION, and a backend that tests for the 

107 # variable's presence would read "" as a version. 

108 for name in unset: 

109 merged.pop(name, None) 

110 # uv warns when VIRTUAL_ENV points somewhere other than the project venv. rhiza.mk 

111 # handles this with `unexport VIRTUAL_ENV`; this is the same fix. 

112 merged.pop("VIRTUAL_ENV", None) 

113 merged.setdefault("UV_NO_MODIFY_PATH", "1") 

114 print(f"{BLUE}$ {' '.join(argv)}{RESET}", file=sys.stderr, flush=True) 

115 # `list(argv)` on its own line, not inlined into the call below. Inlined, the line held 

116 # two call nodes, and bandit runs every test against each: B603 fired on the subprocess 

117 # call and was suppressed, then returned None for `list(...)` and -- seeing B603 named in 

118 # the line's suppression comment -- warned `encountered (B603), but no failed test` on 

119 # every clean run. The suppression is live: B603 is a real finding here, low severity and 

120 # so below `bandit -ll`'s threshold. Hence one call per line rather than a deletion. 

121 command = list(argv) 

122 return subprocess.call(command, cwd=cwd, env=merged) # noqa: S603 # nosec B603 

123 

124 

125def uv( 

126 *args: str, 

127 cwd: Path, 

128 check: bool = True, 

129 env: Mapping[str, str] | None = None, 

130 unset: Sequence[str] = (), 

131) -> int: 

132 """Run uv itself. 

133 

134 Args: 

135 *args: uv subcommand and arguments, e.g. ``("sync", "--frozen")``. 

136 cwd: Working directory. 

137 check: Raise on non-zero rather than returning the status. 

138 env: Extra environment variables. 

139 unset: Inherited variables to remove. ``dist-check`` is the one caller: it rebuilds 

140 a wheel from the sdist with any version override taken away. 

141 

142 Returns: 

143 The exit status. 

144 

145 Raises: 

146 Failed: When ``check`` and uv exited non-zero. 

147 """ 

148 code = _run([_bin("uv", "RHIZA_UV_BIN"), *args], cwd, env, unset) 

149 if check and code: 

150 raise Failed(code, f"uv {args[0] if args else ''} failed") 

151 return code 

152 

153 

154def uvx( 

155 tool: str, 

156 *args: str, 

157 cwd: Path, 

158 withs: Sequence[str] = (), 

159 python: str | None = None, 

160 check: bool = True, 

161 env: Mapping[str, str] | None = None, 

162) -> int: 

163 """Run an isolated tool via ``uvx``. 

164 

165 Args: 

166 tool: The tool spec, e.g. ``bandit`` or ``'zensical>=0.0.36'``. 

167 *args: Arguments for the tool. 

168 cwd: Working directory. 

169 withs: Extra packages injected into the tool's environment. book.mk's 

170 ``MKDOCS_EXTRA_PACKAGES`` is the only current user. 

171 python: Interpreter for the tool itself. Usually omitted -- prek and the other 

172 language-neutral tools provision their own toolchains, which is why 

173 quality.mk was able to drop its ``-p ${PYTHON_VERSION}``. 

174 check: Raise on non-zero rather than returning the status. 

175 env: Extra environment variables. 

176 

177 Returns: 

178 The exit status. 

179 

180 Raises: 

181 Failed: When ``check`` and the tool exited non-zero. 

182 """ 

183 argv = [_bin("uvx", "RHIZA_UVX_BIN")] 

184 if python: 

185 argv += ["-p", python] 

186 for w in withs: 

187 argv += ["--with", w] 

188 argv += [tool, *args] 

189 code = _run(argv, cwd, env) 

190 if check and code: 

191 raise Failed(code, f"{tool} failed") 

192 return code 

193 

194 

195def uv_run( 

196 tool: str, 

197 *args: str, 

198 cwd: Path, 

199 withs: Sequence[str] = (), 

200 no_project: bool = False, 

201 python: str | None = None, 

202 uv_args: Sequence[str] = (), 

203 check: bool = True, 

204 env: Mapping[str, str] | None = None, 

205) -> int: 

206 """Run a tool against the project environment via ``uv run --with``. 

207 

208 Args: 

209 tool: The executable, e.g. ``pytest``. 

210 *args: Arguments for the tool. 

211 cwd: Working directory. 

212 withs: Packages to inject, e.g. ``("pytest", "pytest-cov")``. 

213 no_project: Pass ``--no-project``, for a tool that must not see the project 

214 environment. marimo.mk's ``marimo`` target is the one case. 

215 python: Interpreter to run under, as ``uvx``'s parameter of the same name already 

216 does. Usually omitted -- a tool run against the project environment takes that 

217 environment's interpreter, which is the point of this form. ``update`` is the 

218 exception: the scripts it drives are a *different* project's, pinned by that 

219 project to one version, so the interpreter is theirs to name rather than the 

220 target repository's. 

221 uv_args: Flags for ``uv run`` itself, placed before the tool. ``test-lowest`` is the 

222 only caller, and what it passes is why this is one parameter rather than three: 

223 ``--isolated``, ``--resolution lowest-direct`` and the repository's 

224 ``uv_sync_args`` are a resolver mode plus the environment it is asked about, and 

225 none of them means anything without the others. ``no_project`` and ``python`` 

226 stay named because each is a single decision with a single spelling -- a caller 

227 wanting one of those should keep using them rather than spelling the flag here. 

228 check: Raise on non-zero rather than returning the status. 

229 env: Extra environment variables. 

230 

231 Returns: 

232 The exit status. 

233 

234 Raises: 

235 Failed: When ``check`` and the tool exited non-zero. 

236 """ 

237 argv = [_bin("uv", "RHIZA_UV_BIN"), "run", *uv_args] 

238 if python: 

239 argv += ["--python", python] 

240 if no_project: 

241 argv.append("--no-project") 

242 for w in withs: 

243 argv += ["--with", w] 

244 argv += [tool, *args] 

245 code = _run(argv, cwd, env) 

246 if check and code: 

247 raise Failed(code, f"{tool} failed") 

248 return code 

249 

250 

251def tool( 

252 name: str, 

253 *args: str, 

254 cwd: Path, 

255 check: bool = True, 

256 env: Mapping[str, str] | None = None, 

257) -> int: 

258 """Run a toolchain binary that is expected to be on PATH. 

259 

260 The Rust and Go layers' engines, which uv neither provisions nor knows about: cargo, 

261 rustup, go, and the binaries ``cargo-tools`` and ``go-tools`` install. Nothing is 

262 injected and nothing is isolated -- that is what makes it different from :func:`uvx`, 

263 not an oversight. 

264 

265 Args: 

266 name: The executable, or an absolute path to one. 

267 *args: Its arguments. 

268 cwd: Working directory. 

269 check: Raise on non-zero rather than returning the status. 

270 env: Extra environment variables, e.g. ``RUSTDOCFLAGS``. 

271 

272 Returns: 

273 The exit status. 

274 

275 Raises: 

276 Failed: When ``check`` and the tool exited non-zero. 

277 """ 

278 code = _run([shutil.which(name) or name, *args], cwd, env) 

279 if check and code: 

280 raise Failed(code, f"{Path(name).name} {args[0] if args else ''} failed".strip()) 

281 return code 

282 

283 

284def capture(name: str, *args: str, cwd: Path) -> str: 

285 """Run a tool and return its stdout, for the one recipe that needs a value back. 

286 

287 go.mk's licence gate is that recipe: ``go-licenses check ./... --ignore "$(go list -m)"`` 

288 -- without the module's own path, go-licenses walks the project's own packages and fails 

289 a freshly synced project for having no LICENSE of its own. Found by rhiza's e2e suite 

290 rather than by a dry run, which is why it is carried over rather than rediscovered. 

291 

292 Args: 

293 name: The executable. 

294 *args: Its arguments. 

295 cwd: Working directory. 

296 

297 Returns: 

298 Stripped stdout, or an empty string when the tool failed or is absent. 

299 """ 

300 try: 

301 result = subprocess.run( # noqa: S603 # nosec B603 

302 [shutil.which(name) or name, *args], 

303 cwd=cwd, 

304 capture_output=True, 

305 text=True, 

306 check=False, 

307 ) 

308 except OSError: 

309 return "" 

310 return result.stdout.strip() if result.returncode == 0 else ""