Repository navigation
fix(git): support git worktrees; make test suites hermetic - #185
Merged
Merged
Conversation
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
Contributor
Code Coverage Analysis🟢 Overall Coverage: 91.8% Coverage Metrics
Coverage Breakdown
ResourcesGenerated via go-coverage • 2026-10-03 00:15:05 UTC |
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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What Changed
1. Worktree support (closes #184)
internal/git/installer.go):REPO_ROOTis resolved when the hook runs (git rev-parse --show-toplevel, falling back topwd, since git starts hooks at the top of the working tree). It is no longer the absolute path of the checkoutinstallran in, and the script is identical for every checkout.internal/git/hooks_dir.go):install,uninstall,status,IsHookInstalledand pre-install validation ask git (git rev-parse --show-toplevel --git-path hooks), which handles a worktree.gitfile andcore.hooksPath..gitcan never make us write into an enclosing repository..gitdirectory, orgitdir:file pluscommondir), which covers worktrees and submodules.gitRunner, so the resolution logic is covered with mocks.statuswarns when an installed hook differs from what this version generates. Re-runninggo-pre-commit installupdates it in place, without--force.2. Safe when the hooks directory is shared
Following
core.hooksPathmeans a hook can land in a directory shared by several repositories (a globalcore.hooksPath). Before running checks, the hook now looks for go-pre-commit configuration (.github/env/*.envor.github/.env.base) in the repo root and its parents, the same searchconfig.Loaduses. 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 --verbosenow prints the resolved hooks directory.3. Test suites made hermetic and order-independent
Several packages only passed on the first
-countiteration, in source order, with a particular inherited environment, or when a network install happened to fail. They all reproduce on unmodifiedmaster:internal/tools: the suite swapped in a registry withoutgitleaksand never restored it, so a later test restored anilentry andLoadVersionsFromEnvpanicked. The install cache leaked real binaries found on PATH, andGO_PRE_COMMIT_*_VERSION*values exported by magex changed the versions the tests saw (v0.12.0). Fix:newToolRegistry()plus a per-testresetToolState(fresh registry and cache), and the last real-runner test now uses the fake runner.config/envfile/integration/validation:config.Loadwrites 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: newinternal/testutilwithIsolateEnv(exact full-environment restore) andClearConfigEnv(drop inherited go-pre-commit configuration in each packageTestMain).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 newmakeToolsUnavailablehelper leaves onlygiton 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.TestRepositoryRootFailuresalso 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 withno 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 realflag.CommandLine, so the next run panicked withflag redefined.func TestMain(t *testing.T)is renamedTestMainBinary, so the package can have a realTestMain.Why It Was Necessary
lstat /path/to/main/new.go: no such file or directory).installfrom a worktree failed withmkdir <wt>/.git: not a directory.Testing Performed
internal/git/hooks_dir_test.go, covering:core.hooksPath, CRLF, symlinks, malformed output, enclosing repo;.gitlayouts;core.hooksPath;bash -nsyntax check of the generated script.installfrom a worktree works, and with a sharedcore.hooksPaththe unrelated repo commit is skipped while the configured repo runs all checks.go test ./... -race -shuffle=on -count=3passes, including with all 50GO_PRE_COMMIT_*variables from.github/envexported.CI=true GITHUB_ACTIONS=truewith-count=2 -shuffle=onpasses. All 592 top-level tests also pass when each is run alone.checks/gotoolspasses offline with a CI-like PATH (onlygoand 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 testpasses. Hook script verified on bash 3.2 (the macOS system bash) and bash 5.Impact / Risk
core.hooksPath: the hook still lands in.git/hooksand runs from the same root.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:installwarns and needs--force, which backs them up.go-pre-commit install.statuspoints this out.newToolRegistry()(pure refactor), and verbose output ininstall. Everything else is test-only.Notifications