Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring merge commits for prepare-commit-msg git hook

Tags:

git

githooks

I came up with the following prepare-commit-msg git hook:

#!/bin/sh

BRANCH=`git branch | grep '^*' | sed -e 's/^\* //'`
MESSAGE=`cat "$1"`
JIRA_ID=$(echo "$BRANCH" | grep -Eo "[A-Z0-9]{1,10}-?[A-Z0-9]+-\d+")

if [ -z "$JIRA_ID" ]; then
    echo "$MESSAGE" > "$1"
else
    echo "[$JIRA_ID] $MESSAGE" > "$1"
fi

It does its job by adding branch name (which is in a form of BRANCH-123) to every commit message. However, I don't want this to work with merge commits which have auto-generate commit messages s.a. Merge branch 'master' into BRANCH-123. Which with my hook converts into BRANCH-123 Merge branch 'master' into BRANCH-123

I need to edit the script to somehow ignore (not apply the hook) commits starting with Merge branch.

like image 532
Sergei Emelianov Avatar asked May 09 '26 07:05

Sergei Emelianov


1 Answers

As the document of prepare-commit-msg says,

It takes one to three parameters. The first is the name of the file that contains the commit log message. The second is the source of the commit message, and can be: message (if a -m or -F option was given); template (if a -t option was given or the configuration option commit.template is set); merge (if the commit is a merge or a .git/MERGE_MSG file exists); squash (if a .git/SQUASH_MSG file exists); or commit, followed by a commit SHA-1 (if a -c, -C or --amend option was given).

We can test the 2nd parameter and exit with 0 if it's merge:

#!/bin/bash

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3

if [ "${COMMIT_SOURCE}" = merge ];then
    exit 0
fi
like image 74
ElpieKay Avatar answered May 12 '26 09:05

ElpieKay