Skip to content

fix(git): support git worktrees; make test suites hermetic - #185

Merged
mrz1836 merged 6 commits into
masterfrom
fix/worktree-hook-support
Oct 3, 2026
Merged

mrz1836 merged 6 commits into
masterfrom
fix/worktree-hook-support

Conversation

@mrz1836

@mrz1836 mrz1836 commented Oct 2, 2026 •

Copy link
Copy Markdown
Owner

What Changed

1. Worktree support (closes #184)

  • Hook script (internal/git/installer.go): REPO_ROOT is resolved when the hook runs (git rev-parse --show-toplevel, falling back to pwd, since git starts hooks at the top of the working tree). It is no longer the absolute path of the checkout install ran in, and the script is identical for every checkout.
  • Hooks directory resolution (new internal/git/hooks_dir.go): install, uninstall, status, IsHookInstalled and pre-install validation ask git (git rev-parse --show-toplevel --git-path hooks), which handles a worktree .git file and core.hooksPath.
    • The answer from git is only trusted when its toplevel matches the repo root (symlinks resolved), so a stray .git can never make us write into an enclosing repository.
    • Falls back to the filesystem (.git directory, or gitdir: file plus commondir), which covers worktrees and submodules.
    • The git call is an injectable gitRunner, so the resolution logic is covered with mocks.
  • Outdated hook detection: status warns when an installed hook differs from what this version generates. Re-running go-pre-commit install updates it in place, without --force.

2. Safe when the hooks directory is shared

Following core.hooksPath means a hook can land in a directory shared by several repositories (a global core.hooksPath). Before running checks, the hook now looks for go-pre-commit configuration (.github/env/*.env or .github/.env.base) in the repo root and its parents, the same search config.Load uses. If there is none, it exits 0 with a one-line notice (silent in CI), so it never blocks commits in a repository it was not set up for. install --verbose now prints the resolved hooks directory.

3. Test suites made hermetic and order-independent

Several packages only passed on the first -count iteration, in source order, with a particular inherited environment, or when a network install happened to fail. They all reproduce on unmodified master:

  • internal/tools: the suite swapped in a registry without gitleaks and never restored it, so a later test restored a nil entry and LoadVersionsFromEnv panicked. The install cache leaked real binaries found on PATH, and GO_PRE_COMMIT_*_VERSION* values exported by magex changed the versions the tests saw (v0.12.0). Fix: newToolRegistry() plus a per-test resetToolState (fresh registry and cache), and the last real-runner test now uses the fake runner.
  • config / envfile / integration / validation: config.Load writes every value it reads into the process environment, and legacy mode never overrides values that are already set. So tests saw earlier tests settings, or the values magex exports. Fix: new internal/testutil with IsolateEnv (exact full-environment restore) and ClearConfigEnv (drop inherited go-pre-commit configuration in each package TestMain).
  • checks/gotools: six "tool not available" tests (fumpt, lint, gitleaks) only ran where the tool was absent, and then relied on the automatic install failing. That depends on network access and on the inherited version pin: on CI the default version installed successfully, so the tests failed. A new makeToolsUnavailable helper leaves only git on PATH and clears the install cache, so neither the tool nor its installers (go, sh, curl) can be found. These tests now run on every machine (they used to be skipped wherever the tools are installed) and never reach the network. TestRepositoryRootFailures also accepts the gofumpt install-failure error used since 47ed999.
  • cmd/go-pre-commit: running the root command in-process changes directory to the repository root (initConfig, intended CLI behaviour that is left unchanged), so later builds of . failed with no Go files. Tests that run commands in-process now restore the working directory (t.Chdir(".")). The test binary is built in a temp dir, with build output included in failures.
  • cmd/production-validation: one test registered flags on the real flag.CommandLine, so the next run panicked with flag redefined.
  • Fixed a test that only passed thanks to leaked state: its fixture sets a 300s timeout, but it expected 720. Nil checks before dereferencing results are now fatal. The misnamed func TestMain(t *testing.T) is renamed TestMainBinary, so the package can have a real TestMain.

Why It Was Necessary

  • [Bug] The pre-commit hook and install don't work in git worktrees #184: committing from a linked worktree ran checks against the main checkout and failed on new files (lstat /path/to/main/new.go: no such file or directory). install from a worktree failed with mkdir <wt>/.git: not a directory.
  • The test fixes make CI and local runs reliable regardless of order, repetition, network, installed tools, or what the shell or magex exports.

Testing Performed

  • New internal/git/hooks_dir_test.go, covering:
    • mocked git: worktree, core.hooksPath, CRLF, symlinks, malformed output, enclosing repo;
    • filesystem fallback: worktree, submodule and broken .git layouts;
    • real-git integration for installing from a worktree and with core.hooksPath;
    • end-to-end hook runs: the [Bug] The pre-commit hook and install don't work in git worktrees #184 reproduction, an unconfigured repo sharing the hooks dir (skips, commit succeeds), and modular config in a parent directory;
    • a bash -n syntax check of the generated script.
  • Mutation checks: with the hook pointed back at the main checkout, the end-to-end test fails with the exact error from [Bug] The pre-commit hook and install don't work in git worktrees #184. With the config guard disabled, the shared-hooks test fails.
  • Manual runs with the built binary: the worktree commit passes, install from a worktree works, and with a shared core.hooksPath the unrelated repo commit is skipped while the configured repo runs all checks.
  • Whole repo: go test ./... -race -shuffle=on -count=3 passes, including with all 50 GO_PRE_COMMIT_* variables from .github/env exported. CI=true GITHUB_ACTIONS=true with -count=2 -shuffle=on passes. All 592 top-level tests also pass when each is run alone.
  • checks/gotools passes offline with a CI-like PATH (only go and system tools), with and without the repo env exported. The six missing-tool tests run, and pass, on machines with all tools installed too.
  • magex lint: 0 issues. magex test passes. Hook script verified on bash 3.2 (the macOS system bash) and bash 5.

Impact / Risk

  • Normal checkouts without core.hooksPath: the hook still lands in .git/hooks and runs from the same root.
  • Repo-local core.hooksPath (.githooks, husky): the hook is now installed where git actually runs hooks. Previously it went to .git/hooks, where git ignored it. Existing hooks there are still protected: install warns and needs --force, which backs them up.
  • A repository with no go-pre-commit configuration (in its root or any parent directory) is now skipped with a notice. Before, the hook failed with "failed to load configuration". Every configured repository behaves exactly as before.
  • Hooks installed by earlier releases keep working as before, but keep the hard-coded path until users re-run go-pre-commit install. status points this out.
  • Production code changes are limited to the installer and hook script, newToolRegistry() (pure refactor), and verbose output in install. Everything else is test-only.

Notifications

The installed hook embedded the absolute path of the checkout it was
installed from. Hooks live in the git directory shared by every
worktree, so a commit from a linked worktree ran its checks against the
main checkout and failed on any file the worktree added. The hook now
resolves REPO_ROOT with git rev-parse --show-toplevel when it runs.

The installer built the hooks path as <root>/.git/hooks, which fails in
a worktree where .git is a file. It now asks git for the hooks directory
(git rev-parse --git-path hooks), which also honors core.hooksPath, and
falls back to reading the .git directory or gitdir/commondir files. The
git call is injectable so the resolution is covered with mocks as well
as real-git integration tests.

status now reports hooks written by an older release as outdated so
users know to re-run go-pre-commit install.

Closes #184
@github-actions github-actions Bot added the bug-P3 Lowest rated bug, affects nearly none or low-impact label Oct 2, 2026
@github-actions github-actions Bot added the size/XL Very large change (>500 lines) label Oct 2, 2026
@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Code Coverage Analysis

🟢 Overall Coverage: 91.8%
📊 Initial coverage report - no baseline available for comparison

Coverage Metrics

Metric Value Grade Trend
Percentage 91.8% 🏆 A 📊
Statements 3.3K/3.6K 🏆 A First report
Quality Score 91.8/100 🏆 A 📈

Coverage Breakdown

█████████████░░ 91.8%

Resources


Generated via go-coverage • 2026-10-03 00:15:05 UTC

github-actions Bot added a commit that referenced this pull request Oct 2, 2026
🏷️ Generated with GoFortress
Hooks can now land in a hooks directory shared by several repositories
(every worktree, or a global core.hooksPath). Before running checks the
hook looks for go-pre-commit configuration (.github/env/*.env or
.github/.env.base) in the repository root and its parents, the same
search config.Load uses, and exits 0 with a notice when there is none,
so it never blocks commits in a repository it was not set up for.

install --verbose now prints the resolved hooks directory. Adds end to
end tests for a shared hooks directory, modular config in a parent
directory, and a bash syntax check of the generated script.
The tools tests shared package state and failed with -count>1 or
shuffled order: the suite replaced the registry with one missing
gitleaks and never restored it, so a later test restored a nil entry
and LoadVersionsFromEnv panicked; tools cached as installed (including
real binaries on PATH) leaked between tests; and GO_PRE_COMMIT_*
version variables exported by magex from .github/env changed the
versions the tests observed.

Extract newToolRegistry so tests can reset to the real defaults, give
every stateful test a fresh registry and install cache via
resetToolState, clear inherited configuration in TestMain, and fake the
install runner in the last test that could reach the real one.

Adds internal/testutil with ClearConfigEnv (drop inherited
go-pre-commit configuration) and IsolateEnv (restore the full process
environment after a test), shared by the test packages.
Several packages only passed on the first -count iteration, in source
order, or with a particular inherited environment:

- config.Load writes every configuration value it reads into the
  process environment and legacy mode never overrides set values, so
  tests in config, envfile, integration and validation saw earlier
  tests' settings, or the values magex exports from .github/env.
  Tests that load configuration now call testutil.IsolateEnv, and each
  package's TestMain drops inherited configuration.
- Running the root command in-process changes directory to the
  repository root (initConfig); tests that do so now restore the
  working directory, which broke building the binary on later runs.
- production-validation registered its flags on the real
  flag.CommandLine, panicking with "flag redefined" on the next run.

Also fixes a test that only passed thanks to leaked state (its fixture
sets a 300s timeout, it expected 720), makes nil checks fatal before
dereferencing results, builds the test binary in a temp dir with its
build output in failures, and renames the misnamed TestMain(t) to
TestMainBinary so the package can have a real TestMain.
@mrz1836 mrz1836 changed the title fix(git): support git worktrees in hook and installer fix(git): support git worktrees; make test suites hermetic Oct 2, 2026
TestLintCheckBuildErrorScenarios runs only where golangci-lint is not on
PATH and expected the check's install attempt to fail. On CI it only did
because the inherited GO_PRE_COMMIT_GOLANGCI_LINT_VERSION could not be
installed; with inherited configuration now cleared, the default version
installed over the network and the test failed. Run the check with only
git on PATH (no golangci-lint, go, sh or curl) and a clean install cache,
so the missing tool is reported deterministically without network access.

TestRepositoryRootFailures still expected "gofumpt not found" when
gofumpt is unavailable, but a failed install has been reported as
"command 'gofumpt' failed" with the cause since 47ed999, so the test
failed wherever gofumpt could not be installed. Accept either error.
Six tests cover the 'tool not available' paths of the fumpt, lint and
gitleaks checks. They only ran where the tool was absent and then relied
on the automatic install failing, which depends on the runner's network
and on which version is pinned in the inherited environment; on CI the
default version installed successfully and the lint tests failed.

makeToolsUnavailable leaves only git on PATH and clears the install
cache, so neither the tool nor its installers (go, sh, curl) can be
found. The tests now run on every machine, including those with the
tools installed where they were previously skipped, and never reach the
network.
github-actions Bot added a commit that referenced this pull request Oct 3, 2026
🏷️ Generated with GoFortress
@mrz1836
mrz1836 merged commit 42f6034 into master Oct 3, 2026
23 checks passed
@github-actions
github-actions Bot deleted the fix/worktree-hook-support branch October 3, 2026 00:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug-P3 Lowest rated bug, affects nearly none or low-impact size/XL Very large change (>500 lines)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] The pre-commit hook and install don't work in git worktrees

1 participant