When a pre-commit
hook runs, the repository might not be clean. So if you naively run your tests, they will not be against what you're committing, but whatever happens to be in your working tree.
The obvious thing to do is to git stash --keep-index --include-untracked
at the start of the pre-commit
and git pop
at the end. That way you are testing against the (pure) index, which is what we want.
Unfortunately, this generates merge conflict markers if you use git add --patch
(especially if you edit hunks), since the contents of stash@{0}
might not match up against the work tree after commit.
Another common solution is to clone the repository and run the tests in a new temporary one. There are two issues with that:
- we haven't committed yet, so we can't easily get a copy of the repository in the state we're about to commit; and
- my tests might be sensitive to the location of the current working directory, for example because of local environment configuration.
How can I restore my work-tree to whatever state it was in before the git stash --keep-index --include-untracked
, without introducing merge conflict markers, and without modifying the post-commit HEAD
?
pre-commit
. If you believe it is, please explain why, and what a sensible alternative might be. – Windboundgit diff --cached
onto that file descriptor. – Cockpitgit add -p
just before committing. Since my builds are so fast, I'd like to make sure that these tweaks don't break the build. – Windbound