Coverage for src/rhiza_task/tasks/quality.py: 100%

136 statements  

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

1"""The language-neutral gates: quality.mk and bootstrap.mk's ``clean``. 

2 

3Nothing here needs to know how the project declares its dependencies, which is why the 

4template made ``core`` rather than a language layer own them. 

5 

6The interesting one is ``rhiza-test``. quality.mk runs ``pytest .rhiza/tests`` -- a folder 

7synced from the template -- and prints a WARN and exits 0 when the folder is absent. Since 

8that folder was replaced by the ``pytest-rhiza`` distribution, consumers who excluded it 

9got a green gate measuring nothing, and jointview carries a 60-line Makefile override to 

10fix that for itself. Here the plugin *is* the implementation, so the override is not 

11needed and the silent-pass branch does not exist. 

12 

13``docs-examples`` is registered here and implemented in :mod:`rhiza_task.tasks.fences`. 

14The split is worth knowing rather than discovering: the checker had grown to two thirds of 

15this module and pulled its maintainability index from 62 to 36, at which point the docstring 

16above described half a file. The task keeps the argument for *why* the gate exists, which is 

17what a reader looking for a gate wants; that module holds the argument for how it checks. 

18""" 

19 

20from __future__ import annotations 

21 

22import re 

23import shutil 

24 

25# The hook-path probe below is a fixed argument vector, with no shell -- which is what bandit's 

26# B404 asks about. The reason sits here rather than on the suppression comment itself: bandit 

27# reads everything after that marker as a comma-separated list of test IDs, so a trailing 

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

29import subprocess # nosec B404 

30import tomllib 

31from pathlib import Path 

32 

33from ..config import Config 

34from ..spec import Guard, Skip, task 

35from ..uv import uv_run, uvx 

36from . import fences 

37 

38TODO_PATTERN = re.compile(r"\b(TODO|FIXME|HACK):") 

39TODO_SUFFIXES = frozenset({".py", ".mk", ".sh", ".md", ".yml", ".yaml", ".toml", ".rs", ".go"}) 

40TODO_SKIP_DIRS = frozenset( 

41 { 

42 ".git", 

43 ".venv", 

44 "node_modules", 

45 ".tox", 

46 "build", 

47 "dist", 

48 "_book", 

49 "_tests", 

50 ".mypy_cache", 

51 ".pytest_cache", 

52 ".ruff_cache", 

53 "__pycache__", 

54 } 

55) 

56 

57TAG_VERSION_CHECK = "test_latest_tag_matches_pyproject_version" 

58"""pytest-rhiza's assertion that the newest tag equals the declared version. 

59 

60Correct about a released tree and **false by construction during a release**, which is the 

61window :func:`_release_pending` exists to detect. A repository cannot satisfy it between the 

62version bump and the tag: the bump is what the release PR contains, and the tag is cut from 

63that PR's merge commit, so for the length of the PR the declared version is ahead of every 

64tag that exists. 

65 

66What that costs is a red ``rhiza-task all`` on the releaser's own machine for the length of the 

67release, which is where it was hit while cutting v1.1.0. 

68 

69**It costs nothing in CI, and the note this replaces claimed otherwise.** ci.yml's checkout sets 

70no ``fetch-depth`` and no ``fetch-tags``, so no CI job has any tags at all and this check already 

71skips there -- ``No version tags found in repository``. The required ``gates`` job was therefore 

72never blocked by it, and the assertion that v1.0.0's release PR had been merged red was inferred 

73from a local run rather than read off a CI one. Both claims were wrong, and they were wrong in 

74the direction that made this change look more necessary than it is. Recorded rather than quietly 

75deleted, because the overstatement shipped. See #115. 

76""" 

77 

78CLEAN_ARTIFACTS = ("dist", "build", ".coverage", ".pytest_cache", ".benchmarks", "_tests", "_book") 

79 

80 

81@task("fmt", "run the pre-commit hooks over all files", section="Quality") 

82def fmt(cfg: Config) -> None: 

83 """Run every configured hook via prek. 

84 

85 ``--config`` is not decoration. By default prek treats every directory below the root 

86 holding a ``.pre-commit-config.yaml`` as a separate project and runs each one's hooks 

87 -- useful in a monorepo, wrong in rhiza's own repo where three bundles ship one as 

88 template content. Naming the config disables that discovery, so ``fmt`` means "this 

89 repo's config, once". A consumer wanting the monorepo behaviour drops the flag here and 

90 in the hook install. 

91 

92 prek rather than pre-commit: a Rust reimplementation reading the same config file, 

93 which provisions each hook's toolchain itself. That is what removed the 

94 ``-p ${PYTHON_VERSION}`` this recipe used to need, and with it the coupling that made 

95 the language-neutral half of the template depend on a Python version being resolvable. 

96 

97 Args: 

98 cfg: The resolved config. 

99 

100 Raises: 

101 Skip: When the project has no pre-commit config. 

102 """ 

103 if not (cfg.root / ".pre-commit-config.yaml").is_file(): 

104 raise Skip("no .pre-commit-config.yaml") 

105 uvx("prek", "run", "--all-files", "--config", ".pre-commit-config.yaml", cwd=cfg.root) 

106 

107 

108@task("semgrep", "run the semgrep static analysis rules", section="Quality", guards=(Guard("source_folder"),)) 

109def semgrep(cfg: Config) -> None: 

110 """Run semgrep against the source folder with rhiza's rule set. 

111 

112 Args: 

113 cfg: The resolved config. 

114 

115 Raises: 

116 Skip: When the rule file is absent. 

117 """ 

118 rules = cfg.root / ".rhiza" / "semgrep.yml" 

119 if not rules.is_file(): 

120 raise Skip("no .rhiza/semgrep.yml") 

121 # `--error` is what makes this a gate: without it semgrep prints its findings and exits 

122 # 0, so the task reported ok on any tree (#231). bundle-layer plants a finding and 

123 # asserts the non-zero exit, which is the half a unit test of the vector cannot see. 

124 uvx("semgrep", "--error", "--config", str(rules), cfg.source_folder, cwd=cfg.root) 

125 

126 

127@task("rhiza-test", "run the rhiza repository checks", section="Quality", needs=("install",)) 

128def rhiza_test(cfg: Config) -> None: 

129 """Run the ``pytest-rhiza`` checks against this repository. 

130 

131 The check modules are enumerated rather than globbed: pytest-rhiza ships the Rust and 

132 Go modules in the same distribution, so ``--pyargs pytest_rhiza.checks`` would collect 

133 checks that cannot pass on a Python project. See 

134 :data:`~rhiza_task.config.DEFAULT_RHIZA_CHECKS`. 

135 

136 ``install`` is a prerequisite because the docstring check imports the project's own 

137 packages to run their doctests, which needs the dependencies present. 

138 

139 ``RHIZA_DOCTEST_FOLDERS`` is what tells ``test_docstrings`` where to look, and it has 

140 to be passed: the check falls back to ``SOURCE_FOLDER`` in ``.rhiza/.env`` and then to 

141 a literal ``src``, so a repo whose Python lives anywhere else got 

142 ``SKIPPED No doctest folder found (looked for: src)`` and a **green** gate -- the 

143 doctests went unchecked with nothing failing to say so. ``.rhiza/.env`` cannot cover 

144 for it either: since rhiza stopped shipping ``.rhiza/.gitignore``, whose only content 

145 was the ``!.env`` negation, that file is gitignored and a CI checkout never has one. 

146 ``quality.mk`` exported the variable from ``DOCSTRING_FOLDERS``; this is that export. 

147 

148 One check is dropped while a release is in flight. :data:`TAG_VERSION_CHECK` asserts that 

149 the newest tag equals the declared version, which a repository cannot satisfy between its 

150 version bump and its tag -- so ``rhiza-task all``, which a developer runs before pushing, 

151 went red for the length of a release. :func:`_release_pending` detects the window from the 

152 repository's own state, so nothing has to be passed in and the check returns by itself once 

153 the tag exists. It is a *local* improvement only: CI has no tags, so this check skips there 

154 regardless -- see that constant's own note. 

155 

156 The pin the checks are provisioned from is :func:`_provider`'s answer rather than the 

157 setting itself, so a repository can spell "resolve them from my own environment". 

158 

159 Args: 

160 cfg: The resolved config. 

161 """ 

162 # `-k`, not `--deselect`: a deselect needs the collected node id, and under `--pyargs` that 

163 # is the *installed* package's file path inside the uv cache -- a string this task would 

164 # have to reconstruct and that changes with the pin. Matching on the test's name needs 

165 # neither. 

166 # 

167 # Announced on stdout rather than passed over silently. A relaxed gate that says nothing is 

168 # how a real mismatch would hide behind this, and the whole argument for relaxing it is 

169 # that a permanently-red required check is worse than a visibly narrower one. 

170 selection: tuple[str, ...] = () 

171 if _release_pending(cfg): 

172 print(f"[INFO] release in flight: the declared version leads every tag, so {TAG_VERSION_CHECK} is deselected") 

173 selection = ("-k", f"not {TAG_VERSION_CHECK}") 

174 

175 uv_run( 

176 "pytest", 

177 "--pyargs", 

178 *cfg.rhiza_checks, 

179 *selection, 

180 cwd=cfg.root, 

181 withs=_provider(cfg), 

182 env={"RHIZA_DOCTEST_FOLDERS": cfg.source_folder}, 

183 ) 

184 

185 

186@task( 

187 "test-pyproject", 

188 "run the pyproject.toml structure checks, verbosely", 

189 section="Quality", 

190 layer="python", 

191 needs=("install",), 

192) 

193def test_pyproject(cfg: Config) -> None: 

194 """Run just the pyproject check, with full reporting. 

195 

196 A narrower, louder view of one module that ``rhiza-test`` also runs -- kept because it 

197 is what you want when that check is the thing you are fixing. The reporting flags are 

198 python.mk's verbatim, and the provider is :func:`_provider`'s, so the two gates agree on 

199 where the checks come from. 

200 

201 Args: 

202 cfg: The resolved config. 

203 """ 

204 uv_run( 

205 "pytest", 

206 "--pyargs", 

207 "pytest_rhiza.checks.test_pyproject", 

208 "-v", 

209 "--tb=long", 

210 "--showlocals", 

211 "-rA", 

212 "--durations=0", 

213 "--no-header", 

214 cwd=cfg.root, 

215 withs=_provider(cfg), 

216 ) 

217 

218 

219@task("todos", "list every TODO, FIXME and HACK comment", section="Quality") 

220def todos(cfg: Config) -> None: 

221 """Report TODO/FIXME/HACK comments with file and line. 

222 

223 quality.mk implements this as ``find -print0 | xargs -0 grep -nHE | grep -v | awk``, 

224 with a ``grep -v "make todos"`` filter to stop the recipe matching itself. Reading the 

225 files directly needs no such filter and no shell. 

226 

227 Args: 

228 cfg: The resolved config. 

229 """ 

230 hits = 0 

231 for path in sorted(_walk(cfg.root)): 

232 try: 

233 lines = path.read_text(errors="replace").splitlines() 

234 except OSError: 

235 # Skip, not fail: a file the gate cannot open is not a TODO, and one unreadable 

236 # path in a tree must not cost the report every hit after it. `errors="replace"` 

237 # already absorbs undecodable *bytes*, so what reaches here is the file that 

238 # could not be opened at all -- a permission bit, a dangling symlink, a name the 

239 # OS accepted and cannot serve. 

240 continue 

241 for number, line in enumerate(lines, start=1): 

242 if TODO_PATTERN.search(line): 

243 # as_posix, not str: this is report output a reader copies into a grep or an 

244 # editor's go-to-file, so the separator must not depend on the OS that ran 

245 # the gate. The paths are repo-relative and never touch the filesystem again. 

246 rel = path.relative_to(cfg.root).as_posix() 

247 print(f"{rel}:{number}: {line.strip()}") 

248 hits += 1 

249 print(f"\n[INFO] {hits} item(s) found.") 

250 

251 

252@task( 

253 "docs-examples", 

254 "check the fenced examples in the docs tree", 

255 section="Quality", 

256 needs=("install",), 

257 guards=(Guard("docs_folder"),), 

258) 

259def docs_examples(cfg: Config) -> None: 

260 """Parse every checkable fence under the docs folder, and diff the executed ones. 

261 

262 The gap this closes: ``docs-coverage`` asks whether a docstring *exists* and 

263 markdownlint asks whether the markdown is *well-formed*. Neither asks whether what the 

264 documentation **claims** is still true, and a stale command keeps rendering perfectly -- 

265 so the reader who finds out is a newcomer, at the worst moment. ``README.md`` was already 

266 covered, by pytest-rhiza's ``test_readme_validation`` under :func:`rhiza_test`; the docs 

267 tree had nothing, and it is the larger half. 

268 

269 Not a second check of ``README.md``, deliberately: that file is pytest-rhiza's subject, 

270 and counting one verdict twice would make two gates report one fact. 

271 

272 Which languages are checked, how, and why two of them can go unavailable on a working 

273 machine all live in :mod:`rhiza_task.tasks.fences`, which holds the checker. This is the 

274 registration and the argument for the gate; that module is the implementation. 

275 

276 ``install`` is a prerequisite because the executed half imports the project's own 

277 packages, exactly as :func:`rhiza_test`'s docstring check does. 

278 

279 Args: 

280 cfg: The resolved config. 

281 

282 Raises: 

283 Skip: When the tree holds no checkable fence, so nothing was measured. A docs tree 

284 documenting nothing runnable would otherwise score a silent pass, which is the 

285 failure this gate exists to make visible. 

286 Failed: When at least one example is broken or stale. 

287 """ 

288 fences.check(cfg) 

289 

290 

291@task("clean", "remove build artifacts and stale local branches", section="Dev") 

292def clean(cfg: Config) -> None: 

293 """Remove ignored files, build artifacts, and local branches whose remote is gone. 

294 

295 ``.env`` files are preserved: they hold local configuration that is expensive to 

296 reconstruct and is not an artifact. 

297 

298 Args: 

299 cfg: The resolved config. 

300 """ 

301 git = shutil.which("git") or "git" 

302 _git(git, ["clean", "-d", "-X", "-f", "-e", "!.env", "-e", "!.env.*"], cfg.root) 

303 

304 for name in CLEAN_ARTIFACTS: 

305 target = cfg.root / name 

306 if target.is_dir(): 

307 shutil.rmtree(target, ignore_errors=True) 

308 elif target.exists(): 

309 target.unlink(missing_ok=True) 

310 for egg in cfg.root.glob("*.egg-info"): 

311 shutil.rmtree(egg, ignore_errors=True) 

312 

313 print("[INFO] removing local branches with no remote counterpart") 

314 _git(git, ["fetch", "--prune"], cfg.root) 

315 listing = _git(git, ["branch", "-vv"], cfg.root, capture=True) 

316 for line in listing.splitlines(): 

317 # A leading * or + marks the current or a worktree-checked-out branch; neither can 

318 # be deleted, and attempting it is how the make recipe's xargs used to fail. 

319 if ": gone]" in line and not line.startswith(("*", "+")): 

320 branch = line.strip().split()[0] 

321 _git(git, ["branch", "-D", branch], cfg.root) 

322 

323 

324def _provider(cfg: Config) -> tuple[str, ...]: 

325 """Return the ``--with`` arguments that provide pytest-rhiza, or nothing at all. 

326 

327 :attr:`~rhiza_task.config.Config.pytest_rhiza` is pinned by default, which is right for 

328 a consumer: a gate should run the assertions of a known release rather than whatever the 

329 checks repository's HEAD says today. **Empty means the opposite** -- omit ``--with`` 

330 entirely and let ``uv run`` resolve pytest-rhiza from the project environment, which is 

331 how a repository tries an unreleased check against a real subject without publishing 

332 something first. It is a real choice rather than an absent one, so it is honoured rather 

333 than defaulted over. 

334 

335 Spelling it needs TOML, for the reason :func:`~rhiza_task.config._from_env_file` gives 

336 about ``mkdocs-extra-packages``: only there does an empty value differ from an absent 

337 key. ``pytest-rhiza = ""`` in ``[tool.rhiza-task]`` says it; ``RHIZA_PYTEST_RHIZA=`` 

338 cannot, and reads as unset. 

339 

340 ``pytest-rhiza = "."`` is the trap to avoid rather than the shorthand to reach for: uv 

341 resolves it to a *cached built copy* which is not rebuilt on edit, so the checks pass 

342 against a stale tree while looking like they ran against the working one. Empty leaves 

343 the project environment to answer, which an editable install actually tracks. 

344 

345 Args: 

346 cfg: The resolved config. 

347 

348 Returns: 

349 The one-element pin, or an empty tuple when the setting is empty. 

350 """ 

351 return (cfg.pytest_rhiza,) if cfg.pytest_rhiza.strip() else () 

352 

353 

354def _walk(root: Path) -> list[Path]: 

355 """Return the files worth scanning for TODO comments. 

356 

357 Args: 

358 root: Repository root. 

359 

360 Returns: 

361 Matching files, with skipped directories pruned. 

362 """ 

363 found: list[Path] = [] 

364 stack = [root] 

365 while stack: 

366 current = stack.pop() 

367 for entry in current.iterdir(): 

368 if entry.is_dir(): 

369 if entry.name not in TODO_SKIP_DIRS: 

370 stack.append(entry) 

371 elif entry.suffix in TODO_SUFFIXES: 

372 found.append(entry) 

373 return found 

374 

375 

376def _semver(text: str) -> tuple[int, int, int] | None: 

377 """Parse a ``vX.Y.Z`` or ``X.Y.Z`` string into a comparable tuple. 

378 

379 Tuples of ints rather than a real version type, because comparing releases is all this 

380 needs and ``packaging`` is not a dependency of this package -- three runtime dependencies 

381 is a deliberate ceiling, each one paid for by every consumer on every ``uvx`` invocation. 

382 A pre-release or build suffix returns None rather than sorting oddly: this is used to 

383 decide whether to relax a gate, so anything it cannot read confidently must leave the gate 

384 alone. 

385 

386 Args: 

387 text: A tag or version string, with or without the leading ``v``. 

388 

389 Returns: 

390 ``(major, minor, patch)``, or None when the string is not exactly that shape. 

391 """ 

392 match = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)", text.strip()) 

393 if match is None: 

394 return None 

395 major, minor, patch = (int(part) for part in match.groups()) 

396 return major, minor, patch 

397 

398 

399def _release_pending(cfg: Config) -> bool: 

400 """Report whether the declared version is ahead of every tag in the repository. 

401 

402 That state is a release in flight: the version bump has been made and the tag has not been 

403 cut yet, which is exactly what a release PR contains and what :data:`TAG_VERSION_CHECK` 

404 cannot be satisfied during. 

405 

406 Every uncertain answer is False -- no manifest, an unreadable one, a version or tag shape 

407 this cannot parse, no git, no tags at all. The gate is relaxed only on positive evidence 

408 that a release is underway, because the failure modes are asymmetric: relaxing it wrongly 

409 hides a real mismatch, while leaving it on wrongly costs one red job on a release PR, which 

410 is the situation being fixed and is at least visible. 

411 

412 It also does not distinguish a release in flight from a bump nobody ever tagged. Nothing 

413 local can: the two states are identical on disk. So the trade is stated rather than hidden 

414 -- the *behind* direction stays gated, which is the one that shipped a wrong version before 

415 (v1.0.0's release commit left uv.lock at the previous version), and the *ahead* direction 

416 is announced on stdout by the caller rather than passed over. 

417 

418 Args: 

419 cfg: The resolved config. 

420 

421 Returns: 

422 True when a release looks to be in flight. 

423 """ 

424 manifest = cfg.root / "pyproject.toml" 

425 if not manifest.is_file(): 

426 return False 

427 try: 

428 parsed = tomllib.loads(manifest.read_text(errors="replace")) 

429 except tomllib.TOMLDecodeError: 

430 return False 

431 declared = _semver(str(parsed.get("project", {}).get("version", ""))) 

432 git = shutil.which("git") 

433 if declared is None or git is None: 

434 return False 

435 listing = _git(git, ["tag", "--list", "v*"], cfg.root, capture=True) 

436 tags = [parsed_tag for parsed_tag in (_semver(line) for line in listing.split()) if parsed_tag] 

437 return bool(tags) and declared > max(tags) 

438 

439 

440def _git(git: str, args: list[str], cwd: Path, capture: bool = False) -> str: 

441 """Run a git command, tolerating failure. 

442 

443 Args: 

444 git: The git executable. 

445 args: Arguments. 

446 cwd: Working directory. 

447 capture: Return stdout instead of streaming it. 

448 

449 Returns: 

450 Captured stdout, or an empty string. 

451 """ 

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

453 [git, *args], 

454 cwd=cwd, 

455 check=False, 

456 text=True, 

457 capture_output=capture, 

458 ) 

459 return result.stdout or "" if capture else "" 

460 

461 

462PRE_COMMIT_SHIM = "File generated by pre-commit" 

463"""The header classic pre-commit writes into the hook it installs. 

464 

465Read rather than merely noticing that *a* hook is there, because the three things that hook 

466could be want three different answers and only its first lines tell them apart: prek writes 

467``File generated by prek`` into its own shim, and a hand-written hook carries neither 

468marker. Verified against pre-commit 4.4.0 and prek 0.5.2 rather than assumed. 

469""" 

470 

471 

472def _generated_by_pre_commit(path: Path) -> bool: 

473 """Say whether a path holds a hook classic pre-commit generated. 

474 

475 Args: 

476 path: The hook, which need not exist. 

477 

478 Returns: 

479 True when the file is readable and carries pre-commit's own header. A missing, 

480 unreadable or binary file is not one, which is why the read is guarded rather than 

481 preceded by an ``is_file`` check. 

482 """ 

483 try: 

484 return PRE_COMMIT_SHIM in path.read_text(errors="replace") 

485 except OSError: 

486 return False 

487 

488 

489def _hook_path(root: Path, git: str) -> Path: 

490 """Locate the ``pre-commit`` hook, asking git where this repository keeps its hooks. 

491 

492 ``root / ".git" / "hooks"`` is wrong wherever ``.git`` is a *file* rather than a 

493 directory: a linked worktree and a submodule both keep their hooks under the parent's 

494 git directory. A check that looked in the wrong place would report "no legacy hook" for 

495 exactly the checkouts most likely to be carrying one, and silently. 

496 

497 Args: 

498 root: Repository root. 

499 git: The git executable. 

500 

501 Returns: 

502 Where the hook would be, whether or not it exists. Falls back to the default 

503 location when git answers nothing, which is what happens outside a repository -- 

504 where nothing exists to be found and the question does not matter. 

505 """ 

506 named = _git(git, ["rev-parse", "--git-path", "hooks/pre-commit"], root, capture=True).strip() 

507 return Path(named) if Path(named).is_absolute() else root / (named or ".git/hooks/pre-commit") 

508 

509 

510def install_hooks(cfg: Config) -> None: 

511 """Install the prek git hooks unless an external manager owns ``core.hooksPath``. 

512 

513 Neutral, and here rather than in a language module, because all three ``install`` 

514 recipes carry it verbatim -- python.mk, rust.mk and go.mk each end with the same 

515 twelve lines of shell. prek provisions each hook's own toolchain, so there is nothing 

516 language-specific left in it. 

517 

518 ``-c`` must be passed here *and* in :func:`fmt`: prek bakes the flag into the generated 

519 shim, so without it the commit-time gate rediscovers nested projects and stops meaning 

520 what ``fmt`` means. 

521 

522 **``--force`` is passed when, and only when, the hook in place is pre-commit's own.** 

523 Bare ``prek install`` on a repository that already has a classic hook moves it to 

524 ``pre-commit.legacy`` and enters *migration mode*, where prek runs the legacy hook too 

525 -- and pre-commit's generated script refuses to run in that situation, so ``git commit`` 

526 fails, telling the reader to report a bug against pre-commit. It does not heal: once the 

527 ``.legacy`` file exists every later ``install`` re-enters migration mode, and ``install`` 

528 is a prerequisite of nearly every gate, so the broken commit path is reaffirmed by each 

529 gate the consumer runs. This lands on the 0.x upgrade, which is to say on everybody. See 

530 #171. 

531 

532 So the condition is the *file*, not the flag. Forcing unconditionally would be simpler 

533 and would take a hand-written ``.git/hooks/pre-commit`` with it, on the next ``test``, 

534 for one line of output -- and ``core.hooksPath`` does not cover a hook someone wrote in 

535 the default location. Migration mode is the right answer for that hook: it keeps 

536 running, prek says it moved it, and the ``.legacy`` it leaves is not a generated shim, so 

537 a later run reaches this check and still keeps hands off. What is discarded here is only 

538 ever a script the tool that wrote it says to remove. 

539 

540 Args: 

541 cfg: The resolved config. 

542 """ 

543 if not (cfg.root / ".pre-commit-config.yaml").is_file(): 

544 return 

545 git = shutil.which("git") or "git" 

546 hooks_path = _git(git, ["config", "--get", "core.hooksPath"], cfg.root, capture=True).strip() 

547 if hooks_path: 

548 print("[INFO] skipping hook install: core.hooksPath is set") 

549 return 

550 hook = _hook_path(cfg.root, git) 

551 # Both, because they are two stages of one state: the live hook before prek has moved 

552 # it, the `.legacy` sibling after. Either one being pre-commit's means the commit path 

553 # is broken or about to be. 

554 legacy = hook.parent / f"{hook.name}.legacy" 

555 stale = [path for path in (hook, legacy) if _generated_by_pre_commit(path)] 

556 if stale: 

557 print(f"[INFO] replacing pre-commit's own hook ({', '.join(path.name for path in stale)}) with prek's") 

558 # A hook-install failure warns rather than fails, as the make recipes do: it does not 

559 # invalidate the environment that was just built. 

560 force = ("-f",) if stale else () 

561 uvx("prek", "install", *force, "-c", ".pre-commit-config.yaml", cwd=cfg.root, check=False)