How would I write a pre-merge hook in Git?

The question says it all. Is there a way to perform an action before a merge? I'm guessing there's a way to make use of a pre-commit hook, but I'm not quite sure.


You can try using the prepare-commit-msg hook. The second argument will be merge "if the commit is a merge or a .git/MERGE_MSG file exists". A non-zero exit status will abort the commit.

I don't think this will work with a fast-forward merge, since there won't be a commit message.

More info on hooks: https://www.kernel.org/pub/software/scm/git/docs/githooks.html#_prepare_commit_msg


With Git 2.24 (Q4 2019), no need for script wrapper, or prepare-message hook.

A new "pre-merge-commit" hook has been introduced.

See commit bc40ce4, commit 6098817, commit a1f3dd7 (07 Aug 2019) by Michael J Gruber (mjg).
See commit f78f6c7 (07 Aug 2019) by Josh Steadmon (steadmon).
(Merged by Junio C Hamano -- gitster -- in commit f76bd8c, 18 Sep 2019)

git-merge: honor pre-merge-commit hook

git-merge does not honor the pre-commit hook when doing automatic merge commits, and for compatibility reasons this is going to stay.

Introduce a pre-merge-commit hook which is called for an automatic merge commit just like pre-commit is called for a non-automatic merge commit (or any other commit).

The documentation now includes:

pre-merge-commit

This hook is invoked by git-merge.
It takes no parameters, and is invoked after the merge has been carried out successfully and before obtaining the proposed commit log message to make a commit.
Exiting with a non-zero status from this script causes the git merge command to abort before creating a commit.

The default 'pre-merge-commit' hook, when enabled, runs the 'pre-commit' hook, if the latter is enabled.

This hook is invoked with the environment variable GIT_EDITOR=: if the command will not bring up an editor to modify the commit message.

If the merge cannot be carried out automatically, the conflicts need to be resolved and the result committed separately (see git-merge).
At that point, this hook will not be executed, but the 'pre-commit' hook will, if it is enabled.


Another nice workaround would be to add a shell script, call it like you want, then add these lines to the script:

git() {
    if [ "$1" == "merge" ]; then
        echo "seems to work like a charme"
    fi
    command git "$@"
}

git "$@"

Then make an

alias git="./my-pre-merge-script.sh"

Then you are good to go. You just added your own pre-merge hook. I know, that you do not have access to whatever arguments git would pass to a real pre-merge hook, but you can prepare files or whatever you want to prepare for merge now; I personally am very happy with this approach: I spent 2 or 3 whole days to find something for pre-merge, then I had to go with the pre-commit-msg which I did not find accurate enough for my needs. This solves all my problems. Hope this helps anybody in the future.