From 27896fd2cd0a4c51aa164eca9d615ebd94e55860 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:21:23 -0800 Subject: [PATCH] fix(dev): hooks find hoisted lefthook installs and set up the environment only for a matched job scripts/run-lefthook now searches the hoisted node_modules layouts the generated hook searches (npm, pnpm --node-linker=hoisted), in this tree and the clone's main checkout, and only execs lefthook. The jobs call `{just}` (scripts/hook-just), which falls back to scripts/run-in-hermes-env only once lefthook has matched staged files to the job, so a commit no job matches never runs, or fails on, environment setup. Tests: hoisted lookup, main-checkout lookup from a linked worktree, the no-`just` job path, and a real docs-only commit without `just` that never reaches setup. --- lefthook.yml | 21 +++--- scripts/hook-just | 9 +++ scripts/run-lefthook | 34 ++++++---- tests/scripts/test_run_lefthook.py | 100 ++++++++++++++++++++++++++--- 4 files changed, 135 insertions(+), 29 deletions(-) create mode 100755 scripts/hook-just diff --git a/lefthook.yml b/lefthook.yml index 10d82ee4fc..a64c5000c8 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -4,42 +4,47 @@ # `test -n "..."`. A commit that predates the script skips the hooks instead of failing. lefthook: "sh -c 'if test -f scripts/run-lefthook; then exec sh scripts/run-lefthook $0 $*; fi; echo git hooks skipped: this checkout has no scripts/run-lefthook >&2'" +# `just` for the jobs, resolved only for a job whose glob matched (scripts/hook-just), so a +# commit no job matches never sets up an environment. Absolute: `root:` jobs run in a subdir. +templates: + just: sh "$(git rev-parse --show-toplevel)/scripts/hook-just" + pre-commit: jobs: - name: lint python glob: "*.py" # glob filter - run: just ruff {staged_files} + run: "{just} ruff {staged_files}" - name: move shims glob: "*.py" - run: just check --only shims + run: "{just} check --only shims" - name: lint web root: web/ glob: "web/**/*.{js,ts,tsx}" - run: just eslint {staged_files} + run: "{just} eslint {staged_files}" - name: lint bootstrap installer root: apps/bootstrap-installer/ glob: "*.{js,ts,tsx}" - run: just eslint {staged_files} + run: "{just} eslint {staged_files}" - name: lint desktop app root: apps/desktop/ glob: "*.{js,ts,tsx}" - run: just eslint {staged_files} + run: "{just} eslint {staged_files}" - name: lint tui root: ui-tui/ glob: "*.{js,ts,tsx}" - run: just eslint {staged_files} + run: "{just} eslint {staged_files}" - name: lint shared root: apps/shared/ glob: "*.{js,ts,tsx}" - run: just eslint {staged_files} + run: "{just} eslint {staged_files}" - name: lint tests root: tests-js/ glob: "*.{js,ts,tsx}" - run: just eslint {staged_files} + run: "{just} eslint {staged_files}" diff --git a/scripts/hook-just b/scripts/hook-just new file mode 100755 index 0000000000..c1e690199e --- /dev/null +++ b/scripts/hook-just @@ -0,0 +1,9 @@ +#!/bin/sh +# `just` for a git-hook job (`{just}` in lefthook.yml), resolved only once lefthook has +# matched staged files to the job: a commit no job matches never sets up an environment. +# An unactivated shell has no `just`, a PM tool: it comes from this checkout's own +# environment (scripts/run-in-hermes-env), never from a venv on PATH or `uv run`. +if command -v just >/dev/null 2>&1; then + exec just "$@" +fi +exec "$(dirname "$0")/run-in-hermes-env" just "$@" diff --git a/scripts/run-lefthook b/scripts/run-lefthook index 7a917dbfad..87d309642a 100755 --- a/scripts/run-lefthook +++ b/scripts/run-lefthook @@ -6,19 +6,36 @@ # checkout's `.venv` and editable-installs the checkout into it, so a `.venv` linked to # another checkout's venv re-pointed that checkout at this tree's code on every commit. # Hooks are shared by every worktree of a clone, so the clone's main checkout is searched too. +# +# Only lefthook starts here, with no environment setup: lefthook filters the staged files +# first, and a job that matches resolves its own environment (scripts/hook-just). top="$(git rev-parse --show-toplevel)" || exit 1 common="$(cd "$(git rev-parse --git-common-dir)/.." && pwd)" || exit 1 os="$(uname | tr '[:upper:]' '[:lower:]')" arch="$(uname -m | sed 's/aarch64/arm64/;s/x86_64/x64/')" exe= case "$os" in mingw*|msys*|cygwin*) os=windows exe=.exe ;; esac +pkg="lefthook-$os-$arch" found= -# pnpm's native binary, not the node_modules/.bin shim: that one needs node on PATH, -# which a commit from an unactivated shell does not have. +pick() { + if [ -z "$found" ] && [ -x "$1" ]; then + found="$1" + fi +} for root in "$top" "$common"; do - for candidate in "$root"/node_modules/.pnpm/lefthook-"$os"-"$arch"@*/node_modules/lefthook-"$os"-"$arch"/bin/lefthook"$exe"; do - if [ -z "$found" ] && [ -x "$candidate" ]; then - found="$candidate" + # pnpm's isolated layout. The native binary, not the node_modules/.bin shim: that one + # needs node on PATH, which a commit from an unactivated shell does not have. + for candidate in "$root"/node_modules/.pnpm/"$pkg"@*/node_modules/"$pkg"/bin/lefthook"$exe"; do + pick "$candidate" + done + # The hoisted layouts (npm, `pnpm --node-linker=hoisted`): the generated hook's own list, + # minus its package-manager and `uv run` fallbacks. + for dir in "" /web /apps/bootstrap-installer /apps/desktop /ui-tui /apps/shared /tests-js; do + pick "$root$dir/node_modules/$pkg/bin/lefthook$exe" + pick "$root$dir/node_modules/@evilmartians/lefthook/bin/$pkg/lefthook$exe" + pick "$root$dir/node_modules/@evilmartians/lefthook-installer/bin/lefthook$exe" + if command -v node >/dev/null 2>&1; then + pick "$root$dir/node_modules/lefthook/bin/index.js" fi done done @@ -29,9 +46,4 @@ if [ -z "$found" ]; then echo "git hooks skipped: lefthook is not installed (run pnpm install at the repo root)" >&2 exit 0 fi -# The jobs call `just`, a PM tool: an unactivated shell gets it from this checkout's own -# environment (scripts/run-in-hermes-env), never from a venv on PATH. -if command -v just >/dev/null 2>&1; then - exec "$found" "$@" -fi -exec "$top/scripts/run-in-hermes-env" "$found" "$@" +exec "$found" "$@" diff --git a/tests/scripts/test_run_lefthook.py b/tests/scripts/test_run_lefthook.py index 78cfe13540..03479b28f4 100644 --- a/tests/scripts/test_run_lefthook.py +++ b/tests/scripts/test_run_lefthook.py @@ -38,7 +38,8 @@ def checkout(tmp_path: Path) -> Path: root = tmp_path / "checkout" (root / "scripts").mkdir(parents=True) shutil.copy2(REPO_ROOT / "lefthook.yml", root / "lefthook.yml") - shutil.copy2(REPO_ROOT / "scripts" / "run-lefthook", root / "scripts" / "run-lefthook") + for script in ("run-lefthook", "hook-just"): + shutil.copy2(REPO_ROOT / "scripts" / script, root / "scripts" / script) subprocess.run(["git", "init", "-q", str(root)], check=True, timeout=60) other_venv = tmp_path / "other" / ".venv" other_venv.mkdir(parents=True) @@ -63,13 +64,20 @@ def _run_hook(root: Path) -> subprocess.CompletedProcess: cwd=root, env=env, capture_output=True, text=True, timeout=60, check=False) -def _native_lefthook(root: Path) -> Path: +def _package() -> str: os_name = platform.system().lower() arch = {"aarch64": "arm64", "x86_64": "x64"}.get(platform.machine(), platform.machine()) - package = f"lefthook-{os_name}-{arch}" + return f"lefthook-{os_name}-{arch}" + + +def _native_lefthook(root: Path) -> Path: + package = _package() return root / "node_modules" / ".pnpm" / f"{package}@2.2.1" / "node_modules" / package / "bin" / "lefthook" +GIT = ["git", "-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false"] + + def test_hook_runs_the_checkouts_lefthook_and_never_uv(checkout: Path): received = checkout.parent / "received" _shim(_native_lefthook(checkout), f'echo "$@" > "{posix(received)}"') @@ -90,6 +98,50 @@ def test_hook_without_lefthook_skips_instead_of_reaching_uv(checkout: Path): assert list((checkout / ".venv").iterdir()) == [] +def test_hook_finds_lefthook_in_the_hoisted_layout(checkout: Path): + """npm and `pnpm --node-linker=hoisted` put the native package straight under node_modules.""" + received = checkout.parent / "received" + _shim(checkout / "node_modules" / _package() / "bin" / "lefthook", f'echo "$@" > "{posix(received)}"') + + run = _run_hook(checkout) + + assert run.returncode == 0, run.stderr + assert received.read_text(encoding="utf-8").split() == ["run", "pre-commit"] + + +def test_linked_worktree_runs_the_main_checkouts_lefthook(checkout: Path): + """Hooks are shared by every worktree; one without its own node_modules uses the main checkout's.""" + received = checkout.parent / "received" + _shim(_native_lefthook(checkout), f'echo "$@" > "{posix(received)}"') + subprocess.run([*GIT, "add", "lefthook.yml", "scripts"], cwd=checkout, check=True, timeout=60) + subprocess.run([*GIT, "commit", "-q", "--no-verify", "-m", "init"], cwd=checkout, check=True, timeout=60) + linked = checkout.parent / "linked" + subprocess.run([*GIT, "worktree", "add", "-q", "--detach", str(linked)], cwd=checkout, check=True, timeout=60) + + run = _run_hook(linked) + + assert run.returncode == 0, run.stderr + assert received.read_text(encoding="utf-8").split() == ["run", "pre-commit"] + assert not (checkout.parent / "calls").exists() + + +def test_job_without_just_runs_it_in_the_checkouts_own_env(checkout: Path): + """An unactivated shell has no `just`: a job gets it from scripts/run-in-hermes-env, never uv.""" + if shutil.which("just", path="/usr/bin:/bin"): + pytest.skip("a system `just` would take the activated-shell branch") + (checkout.parent / "bin" / "just").unlink() + runner = checkout.parent / "runner" + _shim(checkout / "scripts" / "run-in-hermes-env", f'echo "$@" > "{posix(runner)}"') + + run = subprocess.run(["sh", str(checkout / "scripts" / "hook-just"), "ruff", "a.py"], cwd=checkout, + env={**os.environ, "PATH": f"{posix(checkout.parent / 'bin')}:/usr/bin:/bin"}, + capture_output=True, text=True, timeout=60, check=False) + + assert run.returncode == 0, run.stderr + assert runner.read_text(encoding="utf-8").split() == ["just", "ruff", "a.py"] + assert not (checkout.parent / "calls").exists() + + def _pinned_lefthook() -> Path | None: """The pnpm-installed lefthook of this checkout or its clone's main checkout.""" common = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], cwd=REPO_ROOT, @@ -103,9 +155,9 @@ def _pinned_lefthook() -> Path | None: return None -def test_generated_hook_with_its_binary_gone_never_reaches_uv(checkout: Path, tmp_path: Path): - """Through the hook `lefthook install` writes, once the binary it baked in is deleted: - the state of a clone whose hooks were installed from a since-removed worktree.""" +def _install_hooks(checkout: Path, tmp_path: Path) -> tuple[Path, dict[str, str]]: + """Write the hooks with the pnpm-pinned lefthook from a copy that is then deleted: the + state of a clone whose hooks were installed from a since-removed worktree.""" pinned = _pinned_lefthook() if pinned is None: pytest.skip("no pnpm-installed lefthook to generate a hook with (pnpm install)") @@ -120,13 +172,41 @@ def test_generated_hook_with_its_binary_gone_never_reaches_uv(checkout: Path, tm subprocess.run([str(baked), "install", "-f"], cwd=checkout, env=env, check=True, capture_output=True, timeout=60) shutil.rmtree(baked.parent) - (checkout / "change.py").write_text("x = 1\n", encoding="utf-8") - subprocess.run(["git", "add", "change.py"], cwd=checkout, env=env, check=True, timeout=60) + return pinned, env - commit = subprocess.run(["git", "commit", "-q", "-m", "change"], cwd=checkout, env=env, - capture_output=True, text=True, timeout=120, check=False) + +def _commit(checkout: Path, env: dict[str, str], name: str) -> subprocess.CompletedProcess: + (checkout / name).write_text("x = 1\n", encoding="utf-8") + subprocess.run(["git", "add", name], cwd=checkout, env=env, check=True, timeout=60) + return subprocess.run(["git", "commit", "-q", "-m", "change"], cwd=checkout, env=env, + capture_output=True, text=True, timeout=120, check=False) + + +def test_generated_hook_with_its_binary_gone_never_reaches_uv(checkout: Path, tmp_path: Path): + """Through the hook `lefthook install` writes, once the binary it baked in is deleted.""" + _, env = _install_hooks(checkout, tmp_path) + + commit = _commit(checkout, env, "change.py") assert commit.returncode == 0, commit.stderr assert not (checkout.parent / "calls").exists() assert list((checkout / ".venv").iterdir()) == [] assert "git hooks skipped" in commit.stderr + + +def test_commit_no_job_matches_sets_up_no_environment(checkout: Path, tmp_path: Path): + """Without `just`, a docs-only commit still never runs the environment setup: lefthook + filters the staged files first, and only a matched job resolves `just`.""" + pinned, env = _install_hooks(checkout, tmp_path) + native = _native_lefthook(checkout) + native.parent.mkdir(parents=True) + shutil.copy2(pinned, native) + (tmp_path / "bin" / "just").unlink() + runner = tmp_path / "runner" + _shim(checkout / "scripts" / "run-in-hermes-env", f'echo "$@" >> "{posix(runner)}"; exit 1') + + commit = _commit(checkout, env, "README.md") + + assert commit.returncode == 0, commit.stderr + assert not runner.exists() + assert not (tmp_path / "calls").exists()