gitbutler icon indicating copy to clipboard operation
gitbutler copied to clipboard

`but setup` displaces hooks owned by hook managers (prek, pre-commit, husky) without detecting them, and provides no escape hatch

Open ichoosetoaccept opened this issue 8 months ago • 24 comments

Version

0.19.5

Operating System

macOS

Distribution Method

dmg (Mac OS - Apple Silicon)

Describe the issue

Summary

but setup unconditionally overwrites pre-commit and post-checkout hooks without checking whether a hook manager (prek, pre-commit, husky, lefthook, etc.) already owns them. It renames existing hooks with a -user suffix and installs GITBUTLER_MANAGED_HOOK_V1 wrappers in their place. While but setup does print a note that it is "Installing Git hooks", it does not name the affected files, does not warn that existing hooks will be displaced, and does not detect pre-existing hook managers.

The resulting state is fragile in several distinct ways.

Failure modes

1. Insufficient warning on but setup

but setup does print a note:

Installing Git hooks to help manage commits on the workspace branch

However it does not:

  • Name which hook files will be affected (pre-commit, post-checkout)
  • Mention that existing hooks will be renamed to a -user suffix
  • Detect whether a hook manager (prek, pre-commit, husky) is already installed and owns those files
  • Offer a way to skip hook installation (--no-hooks) for projects that manage hooks independently

A developer running but setup in a project where prek already owns pre-commit gets no indication that their hook runner has just been demoted to pre-commit-user and wrapped by a GitButler shim.

2. Inconsistent coverage — pre-push is left untouched

GitButler wraps pre-commit and post-checkout, but ignores pre-push entirely. This means pre-push hooks continue running through the hook manager's full pipeline (including stash-before-hooks). When combined with a stale gitbutler/workspace HEAD commit, this causes linters to run against stale file content — see the stale-workspace-HEAD issue filed separately (#12750).

3. prek install after but setup silently breaks workspace guard

Running prek install a second time (e.g., after git clone on a new machine following the project's README) produces:

Hook already exists at `.git/hooks/pre-commit`, moved it to `.git/hooks/pre-commit.legacy`
Migration mode: prek will also run legacy hook `.git/hooks/pre-commit.legacy`
prek installed at `.git/hooks/pre-commit`

Result:

pre-commit         → fresh prek runner
pre-commit.legacy  → GitButler wrapper  ← prek calls this in migration mode, which calls...
pre-commit-user    → old prek runner    ← ...this orphaned duplicate: prek runs TWICE
post-checkout      → fresh prek runner  ← GitButler cleanup logic GONE
post-checkout-user → prek runner (orphaned)

In prek's default migration mode, the GitButler workspace guard still runs (via .legacy), but prek is invoked twice — once directly, once via the wrapper calling pre-commit-user. Running prek install --overwrite removes .legacy entirely, at which point the workspace guard is silently gone with no error or warning.

4. No escape hatch

There is no but setup --no-hooks flag, no config option to disable hook management, and no way to tell GitButler "I already manage hooks through prek — provide your logic as a hook I can call."

Environment

  • GitButler CLI: but (latest)
  • OS: macOS 15 / macOS 26 beta
  • Hook manager tested: prek v0.3+ (pre-commit compatible)
  • Also affects: pre-commit (uses .git/hooks/), Husky (both .git/hooks/ for v4 and .husky/ for v5+ — same displacement pattern regardless of core.hooksPath)

How to reproduce (Optional)

Reproduction

With prek (hooks in .git/hooks/)

# Fresh repo with prek already managing hooks
git init /tmp/hook-test
git commit --allow-empty -m "init"
cat > /tmp/hook-test/prek.toml << 'EOF'
minimum_prek_version = "0.3.3"
default_install_hook_types = ["pre-commit", "pre-push", "post-checkout"]
[[repos]]
repo = "builtin"
hooks = [{ id = "trailing-whitespace" }]
EOF
prek install -C /tmp/hook-test

Hooks before but setup:

.git/hooks/pre-commit    → prek runner
.git/hooks/pre-push      → prek runner
.git/hooks/post-checkout → prek runner
but setup   # run in /tmp/hook-test

Hooks after but setup:

.git/hooks/pre-commit         → GITBUTLER_MANAGED_HOOK_V1 wrapper  ← replaced, no file-level warning
.git/hooks/pre-commit-user    → prek runner (demoted, non-standard filename)
.git/hooks/pre-push           → prek runner                         ← untouched (inconsistent!)
.git/hooks/post-checkout      → GITBUTLER_MANAGED_HOOK_V1 wrapper  ← replaced, no file-level warning
.git/hooks/post-checkout-user → prek runner (demoted, non-standard filename)

With Husky (hooks in .husky/, core.hooksPath = .husky)

but setup is aware of core.hooksPath — when set to .husky, it correctly installs its wrappers into .husky/ rather than .git/hooks/. However, the same displacement pattern applies:

# Fresh repo with Husky-style hooks
git init /tmp/husky-test && git commit --allow-empty -m "init"
mkdir /tmp/husky-test/.husky
echo '#!/bin/sh\necho "husky: running pre-commit"' > /tmp/husky-test/.husky/pre-commit
chmod +x /tmp/husky-test/.husky/pre-commit
git -C /tmp/husky-test config core.hooksPath .husky
but setup   # run in /tmp/husky-test

Result — .husky/ after but setup:

.husky/pre-commit      → GITBUTLER_MANAGED_HOOK_V1 wrapper  ← original displaced
.husky/pre-commit-user → original Husky hook (50 bytes)
.husky/post-checkout   → GitButler post-checkout handler    ← injected
.git/hooks/            → empty (correctly unaffected)

The GitButler GUI setting "Enable Husky hooks" is orthogonal to this — it controls whether GitButler's internal hook execution calls .husky/ scripts, not how but setup behaves.

Expected behavior (Optional)

Expected behaviour

but setup should:

  1. Detect existing hook managers before overwriting. If pre-commit, post-checkout, or pre-push are already owned by a recognised hook manager (prek, pre-commit, husky, etc.), print a warning and instructions rather than silently renaming.

  2. Provide composable hook scripts — ship the workspace guard and post-checkout cleanup as standalone scripts (e.g., installed to .git/gitbutler/hooks/) that can be called from any hook manager config.

  3. Support --no-hooks (or a config flag) to skip all hook installation for teams that manage hooks independently.

  4. Handle pre-push consistently — either wrap it the same way as pre-commit/post-checkout, or don't wrap any hooks at all and rely on the composable scripts approach.

Suggested integration pattern

The correct integration for a prek-managed project looks like this (currently requires manual setup with no official guidance):

# prek.toml
[[repos]]
repo = "local"
hooks = [
    { id = "gitbutler-workspace-guard",
      name = "GitButler Workspace Guard",
      language = "system",
      entry = "nu .git/gitbutler/hooks/workspace-guard.nu",   # hypothetical
      pass_filenames = false,
      always_run = true,
      stages = ["pre-commit"] },
]

GitButler should ship these scripts and document this pattern as the recommended integration for projects using hook managers.

Relevant log output (Optional)


ichoosetoaccept avatar Mar 10 '26 08:03 ichoosetoaccept

May I work on this issue? Hope this project is open for contribution. cc: @Byron @slarse

spider-yamet avatar Mar 10 '26 08:03 spider-yamet

May I work on this issue? Hope this project is open for contribution. cc: @Byron @slarse

I believe you're free to, thanks for offering! Be sure to check contribution guidelines 🙂.

ichoosetoaccept avatar Mar 10 '26 09:03 ichoosetoaccept

I should add that this issue is a blocker for me in regards to Gitbutler right now. I'm running but teardown in all projects where I adopted Gitbutler until this is resolved because I use prek extensively in all my projects and don't want to deal with Gitbutler messing up my carefully crafted git hook setup.

BTW, prek is my personal favorite of many git hook managers out there. I strongly assume that all of these are affected by this:

Even more info:

ichoosetoaccept avatar Mar 10 '26 09:03 ichoosetoaccept

Thanks a lot for reporting!

I think the interactions with hook managers aren't quite sane yet, particularly with prek. Also I must add that many pre-commit hooks require the new commit tree to be present in the .git/index, which is something that GitButler might not always do.

There are many unknowns for me, but I tried to clear them up real quick with Codex (see below the line). In any case, help is certainly welcome.


but commit is not delegating to git commit. In the current CLI path it manually runs pre-commit, then commit-msg, creates the commit, then runs post-commit, all gated by --no-hooks / --no-verify (crates/but/src/command/legacy/commit.rs#L361-L522). It does not run prepare-commit-msg or the rest of Git’s usual client-side hook chain.

The interaction with but setup is:

  • but setup switches to gitbutler/workspace and installs GitButler-managed pre-commit and post-checkout hook files, respecting core.hooksPath if it exists (setup.rs#L379-L394, managed_hooks.rs#L179-L300).
  • The managed pre-commit wrapper first runs the displaced user hook as pre-commit-user, then blocks direct git commit on gitbutler/workspace with GITBUTLER_ERROR (managed_hooks.rs#L18-L61).
  • but commit intentionally calls that same hook chain, but special-cases GITBUTLER_ERROR as success, so the user’s original pre-commit still runs and GitButler’s workspace guard does not block but commit (hooks.rs#L79-L115).
  • but teardown removes/restores those managed hooks before checking out a normal branch, while the managed post-checkout hook also self-cleans if the user leaves the workspace branch manually (teardown.rs#L115-L148, managed_hooks.rs#L63-L136).

Hook lookup matters too. GitButler uses git2-hooks for pre-commit / commit-msg / post-commit, and that library gives core.hooksPath absolute precedence; if it is set, fallback search paths are not consulted (hooks.rs#L47-L60, git2-hooks/src/hookspath.rs#L23-L59). So the GitButler “Enable Husky hooks” setting is orthogonal to but setup: it only affects GitButler’s internal fallback search for .husky when core.hooksPath is not set.

My estimate for prek and Husky:

  • If prek or Husky is already installed before but setup, but commit will usually still run the displaced pre-commit through GitButler’s wrapper. So this is not mainly a “hooks never run” problem.
  • The real problem is ownership. but setup renames pre-commit and post-checkout to *-user and takes over the canonical filenames. That collides with how hook managers such as prek and husky expect to own those entrypoints.
  • That makes reinstall flows fragile. The prek double-run / lost-guard scenario described in issue #12748 and the linked comment is a credible consequence of GitButler’s rename scheme plus prek’s install model.
  • Husky is affected differently but for the same structural reason: GitButler respects core.hooksPath, so if Husky owns that path, GitButler installs its wrappers there and displaces Husky’s files in-place rather than bypassing them.
  • There is also a behavioral mismatch: but commit runs pre-commit against a synthetic index built from the selected DiffSpecs, then resets that index and creates the commit from GitButler’s own selection model (repo.rs#L89-L106, hooks.rs#L79-L93, commit.rs#L431-L458). So validate-only hooks should mostly work, but auto-fix-and-restage flows may not behave like native git commit.

Net: but commit is designed to compose with GitButler’s own managed pre-commit wrapper, but but setup still takes over hook entrypoints that third-party managers consider theirs. So the main risk for prek / Husky is not total hook loss; it is fragile ownership, possible duplicate execution after reinstall, possible loss of the GitButler workspace guard, and non-native behavior for auto-fixing hooks.

Byron avatar Mar 11 '26 05:03 Byron

Hey there. Just wanted to mention that I'm working on this.

The current direction of my changes:

  • Define an explicit GitButler git hook ownership model
  • Two modes: Mode 1 — no hook manager detected, so GitButler manages its own hooks. Mode 2 — a hook manager is detected and GitButler fully supports that by exposing pre-commit, post-checkout, and pre-push actions that can be installed as hook-manager-supported hooks
  • Existing user hooks are preserved — backed up to -user and chained, so nothing gets silently overwritten
  • Both but CLI and desktop code paths taken into account
  • but setup and but teardown fully respect this new model
  • Users get explicit escape hatches (--no-hooks, --force-hooks)
  • First PR fully supports prek as the hook manager, with comprehensive e2e tests. The design is intentionally modular so adding support for other hook managers (lefthook, husky, pre-commit, etc.) should be straightforward follow-up PRs

I'm aiming to make this as clean a PR as possible, aligning with the in-progress migration from the legacy gitbutler-repo code paths to the but CLI architecture.

It's quite the chunk of work but I'm convinced this would vastly improve GitButler and how it deals with git hooks.

ichoosetoaccept avatar Mar 20 '26 09:03 ichoosetoaccept

So i created a stack of 3 PRs on my side and submitted the first PR in the stack. The idea was to split the work somewhat to make reviewing PRs easier.. of course I didn't consider that I couldn't submit a full PR stack to you "as is". Fixing CI failures now on PR 1 but as soon as that's as green as I can make it, should I target master with the other two PRs in the stack?

ichoosetoaccept avatar Mar 20 '26 19:03 ichoosetoaccept

It seems the PRs already landed and they target master. With https://github.com/gitbutlerapp/gitbutler/pull/12966 including the two ones before it, I don't think it makes sense to do such a split unless they target each other.

With that said, the third PR has 5k lines added, and I don't consider that reviewable. I might also add these are obviously generated, and as such don't carry much value as we can just generate them ourselves and be sure they are validated. Counting lines of generated tests isn't a metric for quality or trustworthiness.

The first PR already fails CI, yet two more PRs that then also fail CI have been pushed. To me, that does not work at all. As I appreciate the motivation, I think all it takes is a nudge in the right direction maybe.

[!IMPORTANT] As a key constraint, I think we cannot have PRs with more than a couple of hundred lines of code as they aren't reviewable otherwise. Also, I need to see the prompts (and follow-up prompts) as they are easier to review. From them I could already say if it goes in a direction I'd find agreeable. (There is no use in reviewing if the prompts are off). I'd review hand-written PRs any time, they are naturally in the human-reviewable range.

Byron avatar Mar 20 '26 23:03 Byron

Hey @Byron,

This is a lengthy comment but given what transpired, full transparency and sufficient detail matter imho.

Apologies for the mess. Ironically I split this into three stacked PRs to make reviewing easier, but since I can't create branches on upstream from a fork, they all ended up targeting master with cumulative diffs — which defeated the purpose entirely. Of course this worked great on my fork—the issues started when it came time to submit this to you. I was aware of the limitation and tried to mitigate it by including clear dependency notes in each PR description, but that clearly wasn't enough. I also should have ensured CI was green before pushing the follow-up PRs. Lesson learned on both counts.

I'd like to take another stab at this. Before submitting any new PRs, I'd like to align with you. Here's the direction I already went in with what I had submitted, but laid out with what I hope is a balanced level of detail. The key design goal was that everything works in both modes — users without a hook manager get GitButler's managed hooks as the default (as today), while users who already use an external hook manager get a composable integration path instead of having their hooks overwritten. This includes the various lifecycle scenarios: setting up GitButler in a repo that already has a hook manager, adding a hook manager to a repo already using GitButler, and the baseline case of no hook manager at all:

  1. Hook manager detection in but setup — when but setup detects that an external hook manager already owns the hook files, it skips overwriting them and prints integration instructions instead. Detection works by inspecting hook file contents and checking for manager config files in the workdir. I started with prek as the first implementation since that's what I use daily, but structured it so adding support for any hook manager (pre-commit, husky, lefthook) is just adding a new variant.

  2. but hook subcommands — I initially considered shipping standalone hook scripts that managers could pull in as remote hooks, but landed on integrating them as but hook pre-commit, but hook post-checkout, and but hook pre-push subcommands instead. Since but is already on the user's PATH, there are no extra files to distribute or version, and any hook manager that can call a system command can invoke them. This way GitButler's hooks become one participant in the user's hook pipeline rather than owning the hook files exclusively — the hook manager orchestrates, and but hook <name> runs alongside the user's other hooks.

  3. but hook status diagnostic — a mode-aware status command that reports hook ownership per-hook (GitButler-managed, external with manager name, user, or absent), detects misconfigurations (orphaned hooks in old directories, stale hooks, core.hooksPath mismatches), and provides context-aware recommendations. Supports human, shell (key='value'), and JSON output formats.

  4. Mode-aware but teardown — when tearing down a GitButler workspace, if hooks are externally managed, teardown leaves them untouched instead of uninstalling them. This completes the lifecycle: setup detects the mode, the hook commands respect it, and teardown cleans up only what GitButler owns.

  5. New but-hooks crate — all hook detection and management logic lives in a dedicated but-hooks crate, following the project's ongoing migration from gitbutler--prefixed crates to but--prefixed ones. Existing consumers in gitbutler-repo continue working via re-exports.

The mode is persisted via a gitbutler.installHooks config flag. Two CLI flags let users override auto-detection when needed: --no-hooks tells but setup to skip hook installation even if no external manager was detected (useful when the user's hook manager isn't supported yet), while --force-hooks does the reverse — re-enables managed hooks even if an external manager is present, backing up existing hooks before overwriting. Either way, there's a clear recovery path.

GitButler Desktop's workspace migration flow was also updated to use the same hook management logic — so the Desktop app already respects external hook managers. Any of this needs to work correctly whether someone uses but from the terminal, GitButler Desktop, or both.

As I dug into this issue, I realized it couldn't be addressed with a simple fix — properly solving hook coexistence meant building detection, composable CLI entry points, diagnostics, and handling the lifecycle transitions between modes. The scope exceeded the original issue, but each piece was necessary to make the solution actually work end-to-end.

Looking further ahead, I think this work naturally leads to deeper integration with GitButler Desktop:

  • Onboarding — hook system detection should be a step when a user first adds a repo to GitButler, since getting this right at setup time prevents confusion later.
  • Settings — a dedicated hooks section in GitButler's settings where users can control git hook integration, inspect hook status, and run diagnostics from the UI.
  • but doctor — a health check command that validates the hook setup is correct at any given time (not just during setup). Given the number of moving parts, having a single command that can diagnose misconfiguration felt necessary — and it could feed into both onboarding and settings.

All of the above was backed by extensive tests (CLI invocation tests, integration tests with prek, status diagnostic tests), which admittedly made up a significant portion of the line count.

The code was AI-assisted — I won't pretend otherwise. There's simply no way I could have made this contribution, at the level of care and quality I aspire to, by writing it by hand in the time I had. Using an LLM combined with extensive iteration was the key to making this work at all. Sharing the prompts would mean sharing a book-length amount of back and forth which I can't imagine you'd enjoy reading. This was a fairly complex piece of work that no LLM in existence today could have gotten right in a handful of shareable prompts without supervision and extensive guidance. Now that I've gone through this entire discovery process, it's possible that the result could be distilled into a few precise prompts — but that's only because the hard part was figuring out WHAT and HOW to build, not typing it in.

Given how the submission went, I hear you on keeping PRs to a couple hundred lines — how would you suggest breaking this down into reviewable chunks at that scale? I have some ideas but I'd rather hear your take first.

Apologies again for the disturbance this first attempt caused.

ichoosetoaccept avatar Mar 21 '26 09:03 ichoosetoaccept

First of all, let me apologize if I came across as dismissive before, I guess it was a defensive reaction to what felt like a code-dump without prior alignment. Suggesting to receive prompts was more of a naive thought in the light of a lot of iteration, and I think the above explanation goes a long way towards building trust that this generated code is meaningful.

With that said, I enjoyed reading your comment and think it's sound. It's also juicy enough for me to now want this work, well done :).

I realize that a key to making bigger contributions work is to get alignment first, like done above, followed by continuous participation by maintainers. Small steps along a bigger trail that are individually meaningful is one way. For the most part, we are past this here, but I think it can work nonetheless. Another major factor in me building trust is what happened in this PR: the author made clear what they did to validate the changes. Checklists help me more than bulletpoints, as it makes clearer that it was a subtask that they performed. As a matter of fact, I trusted them that they tested Windows and Linux, I didn't test it separately.

Next steps
Plumbing + but CLI

Let's have one PR with one commit (or multiple but only if this helps you) with the MVP which is the entire hook machinery, wired up only to the but CLI. If a cursory review passes I will go into the details of it and see what can be done to merge. Please start with draft until CI passes, that'a another factor for me not to review at all.

but doctor

I know we want this for the name alone ;). But besides that, I think it's very useful to have this for a complex tool like GitButler. Maybe the implementation can go into but-diagnose or something.

integration into Desktop

This needs prior alignment with @PavelLaptev - once the plumbing PR landed this conversation can be started right away.

There are probably more steps, but we can take them when we pass the plumbing milestone.

Thanks again for bearing with me here. My entire workflow changed and I beefed up my reviewing setup. The next natural step is to find new ways to review big PRs with LLM assistance that I didn't prompt into existence myself, ideally without spending as much time as it took to create them, with the goal to feel comfortable and familiar with the added code to be able to maintain it.

Byron avatar Mar 21 '26 23:03 Byron

Hey @Byron

No worries! Thank you very much for taking the time to write such a thoughtful response, I really appreciate it!

Work is underway for a new PR submission, taking into account everything you said to the best of my ability. Will have a new PR to share soon.

Regarding but doctor(I hadn't even realized at the time of suggesting this but you're right, this MUST land for the name alone! 😂), I'm happy to take a stab at that too since I already got started on it: it's useful for verifying all this new git hook management setup and ensuring Gitbutler can peacefully co-exist with git hook managers. I wouldn't include that in this PR, though. Should I submit a new issue outlining the problem and how I'd go about that there? Then we could refine and a new PR would follow, targeting that topic specifically.

Acknowledged regarding integration to Desktop. Makes perfect sense to hold off on that for now. I can also draft up an issue for that one if you like or just leave it be for now and cross that bridge when we get there 🙂.

No issue it all. Things are changing, fast, and I get your frustration. I went through trying multiple AI code review tools (coderabbit, greptile, getunblocked.com and and) and currently settled on devinreview.com which seems to work for me.

What devinreview, in particular, does well is that it helps explain what's changing in a very human-friendly way, summarizing a PR and even ordering changes in an objectively logical way, aside from flagging various things.

As you already saw, a new draft PR is up and I've been fixing issues and resubmitting frequently. It's not quite ready yet but I'm working on it.

Cheers!

ichoosetoaccept avatar Mar 23 '26 18:03 ichoosetoaccept

Regarding but doctor(I hadn't even realized at the time of suggesting this but you're right, this MUST land for the name alone! 😂), I'm happy to take a stab at that too since I already got started on it: it's useful for verifying all this new git hook management setup and ensuring Gitbutler can peacefully co-exist with git hook managers. I wouldn't include that in this PR, though. Should I submit a new issue outlining the problem and how I'd go about that there? Then we could refine and a new PR would follow, targeting that topic specifically.

Feel free to hash it out in an issue first - it depends on the 5.5k PR to land first, and there is uncertainty if I can make it work. While you are free to work on what you want optimistically, I'd be glad if all this could depend on the PR successfully merged.

What devinreview, in particular, does well is that it helps explain what's changing in a very human-friendly way, summarizing a PR and even ordering changes in an objectively logical way, aside from flagging various things.

Thanks for sharing! Personally, I am conservative with tool and prefer one stupid tool (Codex) over specialized tools for now as Codex I can wield well by now. I use it to help get an initial understanding/overview and to flag things, but it's the same thing that's running on GH already so locally that's less important. What I can never get around is to look at all these changed lines myself and that takes time.

So the biggest improvement you can make is to reduce duplication that might be contained in it so I have to look at less.

Byron avatar Mar 24 '26 01:03 Byron

I'm jumping in late, but is there a way to disable clobbering/wrapping the hooks in the GitButler GUI (i don't use the CLI, at least not directly)? I didn't se an option in either project or global settings.

It would be nice if all automated repo code changes were opt-in.

AlexanderGH avatar Apr 07 '26 16:04 AlexanderGH

That would be interesting to hear from @ichoosetoaccept. The system he is implementing actually integrates GitButler with the existing managers, instead of proxying them. In theory, it should be fine to disable even such an integration, even though I don't think is is currently what his PR implements.

In any case, it seems very fair to also think about an opt-in or at least easy opt-out of the hooks-handling that GitButler currently performs, as something that could land much faster due to reduced scope.

Byron avatar Apr 08 '26 11:04 Byron

Hello guys! Just saw the comments now and also your mentions on Discord, @Byron , as well as comments on the PR. For whatever reason Github does not send me notifications emails on these comments! I need to look into that.

@AlexanderGH to address your question I intentionally avoided anything related to Gitbutler Desktop/GUI within the scope of this issue/PR based on discussions around direction with @Byron . I absolutely intended on following this up with Gitbutler Desktop improvements, including having the git hook setup be part of the graphical onboarding flow when some someone first adds a repo to Gitbutler because I think it belongs there. The PR is large enough as it is without also including GUI changes.

What would be helpful, I suppose, @AlexanderGH : create an issue about, well, your issue, and link to this issue? I'm happy to have a look at it once this PR lands 🙂

ichoosetoaccept avatar Apr 10 '26 06:04 ichoosetoaccept

@ichoosetoaccept I appreciate and looking your contribution :) I also need a way to opt-out since i use gitbutler on a customer project, but dont want any gitbutler related code in the code base. I need to skip the latest versions, until gitbutler does not generate their hooks automatically anymore...

prclm avatar Apr 16 '26 07:04 prclm

Actually, the way I see this going is that hooks will be opt-in in future strictly to improve the user experience. This can be done once we know that GitButler is well behaved even outside of the GitButler workspace. And that's also what we are pushing forward to now, so fingers crossed. This will happen first, and then I hope I will have more time to look at @ichoosetoaccept work for much better hook handling for when it's opted in to.

Byron avatar Apr 16 '26 21:04 Byron

Git 2.54 has support for "configuration based hooks". Essentially, you can install new hooks without overwriting older ones. Wouldn't this solve the entire issue? GitButler just has to install hooks using config (if git is new enough) and there will be no conflict.

Alxandr avatar Apr 30 '26 15:04 Alxandr

Thanks so much for sharing. I will investigate this. Maybe it could be an intermediate solution that helps right now, without having to wait for not needing hooks at all. My guess is that they will be useful for a while.

Codex

Git 2.54 adds config-based hooks: instead of putting executable files in .git/hooks/<event> or using one shared core.hooksPath, you can define named hooks in Git config.

Example:

[hook "linter"]
    event = pre-commit
    command = ~/bin/linter --cpp20

[hook "no-leaks"]
    event = pre-commit
    command = ~/bin/leak-detector

Or via commands:

git config set hook.linter.command '~/bin/linter --cpp20'
git config set --append hook.linter.event pre-commit

What changes:

  • Hooks can live in normal Git config: local, global, or system config.
  • Multiple hooks can run for the same event without writing a wrapper script.
  • A single hook can run for multiple events by repeating hook.<name>.event.
  • Traditional .git/hooks/<event> hooks still work and run after config-defined hooks.
  • hook.<name>.enabled = false disables a hook without deleting its config.
  • git hook list <event> shows what will run; --show-scope shows whether each hook came from local/global/system config.

Example inspection:

git hook list pre-commit
git hook list --show-scope pre-commit

Important details:

  • Execution order is config parse order.
  • hook.<name>.command is single-valued: if repeated, last one wins.
  • hook.<name>.event is multi-valued.
  • Commands can be executable paths or shell one-liners.
  • Git 2.54 still runs multiple config hooks sequentially. Parallel hook execution is being discussed/targeted later, not part of 2.54.

Why this matters: it gives you most of what hook managers provide, but natively. For example, you can put personal hooks in ~/.gitconfig, organization hooks in system config, and repo-specific hooks in .git/config, while still allowing per-repo opt-out.

Sources: git-hook 2.54 docs, GitHub’s Git 2.54 highlights, Collabora hook overview.

Byron avatar Apr 30 '26 23:04 Byron

@Byron and important adendum: It will also run the hooks in the hook directory. So if prek (or whatever) installs itself in the hooks directory, and git-butler adds a [hook "gitbutler.precommit"] - both will run.

[Edit]
A really good showcase of the whole feature by the author(?) of pre-commit (the python githook runner): https://youtu.be/8Jwg_mM9WYc?si=4aV4ZQHhsAohtjth

Alxandr avatar May 01 '26 09:05 Alxandr

Is @ichoosetoaccept reading this? With your prior experience on the big swing to modernize hook integration, maybe this could be a more surgical edit that can be merged quickly as it goes from 5000 to maybe 200 lines? I'd love that, so please excuse this solicitation 🙏.

Byron avatar May 02 '26 07:05 Byron