In pre-merge-commit
, I need the hash of the merge head to verify a few things about the commits that are about to be merged to the current branch.
However, it seems that neither the reference MERGE_HEAD
nor the file .git/MERGE_HEAD
exist at the time when the hook is running.
How can I get the merge head revision in my hook?
Internally Git has a function write_merge_heads
that finds the correct object and writes it to the file .git/MERGE_HEAD
.
Unfortunately, this function is called after the pre-merge-hook
was already executed. (It's called regardless if the hook succeeds or fails.)
If you're willing to have a tiny bit of extra typing each merge, there is a really simple fix.
Just exit
from the pre-merge-commit
hook with non-0 code if the MERGE_HEAD
is not present.
After the merge is resumed, MERGE_HEAD
will be there.
Here is a template for such pre-merge-commit
hook:
#!/bin/sh
if [ ! -f .git/MERGE_HEAD ]
then
printf 'Cannot find the MERGE_HEAD!\n' 1>&2
printf 'Git tends to not pass this information for the first call of the `pre-merge-commit` hook.\n' 1>&2
printf 'Please, run `git merge --continue` or just `git commit` and it should work this time.\n' 1>&2
exit 1
fi
# The actual hook's body...