1

I have written a git pre-commit hook which does the following:

  1. Stash any changes that are not staged for commit
  2. Run tests
  3. Unstash changes

The purpose is to prevent false-positives or false-negatives on passing tests/compiling when staged changes depend on unstaged changes. Generally, the hook works very well and has caught many mistakes on my part.

However, as implemented it does not interact well with git add -p:

  1. Stage changes with git add -p and then git commit
  2. Script runs: git stash push -m "pre-commit-${DATE} on ${BRANCH}" -k -u -q
  3. tests pass/fail
  4. git stash pop -q is run and results in a conflict, ruining my day and aborting the commit

My workaround has essentially been to either use git commit --no-verify or stash things myself if I ever use git add -p. However I am updating my git hooks and I'd like to update or replace the stash functionality to allow me to run tests on only staged changes while no longer conflicting with git add -p. Is there a way to:

  • pre-determine if a stash will conflict and defer it to after the commit is generated
  • use a mechanism other than stash that works well in a pre-commit script
  • "abort" the pop if a merge conflict happens
Gwen
  • 191
  • 1
  • 3
  • for what it's worth [pre-commit.com](https://pre-commit.com/#pre-commit-during-commits) solves this using `diff` / `apply` + a conflict-rollback strategy -- you may find it useful (or as a battle-tested replacement for homegrown scripts) -- disclaimer: I'm the author – anthony sottile Mar 16 '20 at 18:52
  • See https://stackoverflow.com/q/20479794/1256452 - you'll need a `git reset --hard` – torek Mar 16 '20 at 20:16

0 Answers0