Search code examples
gitgithooks

git commit-msg hook trigger only on specific commit types


I created a .git/hooks/commmit-msg hook that is triggered correctly on git commit but on top of that, as other git actions such as

  • git pull
  • git merge
  • ...

are also triggering the commit-msg hook.

Is there a way to identify inside the commit-msg file what type of git action triggered it and isolate certain logic to only apply to git commit specifically?


Solution

  • commit-msg is invoked by git commit and git merge. During git merge that creates a merge commit, 3 temporary files are created under .git. They are MERGE_HEAD, MERGE_MODE and MERGE_MSG. You can test if any of the files exists. These files are removed after the merge is done.

    #!/bin/bash
    
    gitdir=$(git rev-parse --absolute-git-dir)
    mergemode=${gitdir}/MERGE_MODE
    if [[ -f "$mergemode" ]];then
        # echo git merge, exit
        exit 0
    fi
    
    # not git merge