'How do I rerun the editor after the git commit-msg hook?

I have a git commit-msg hook that looks like this:

#!/bin/bash

COMMIT_MESSAGE_FILE="$1"
COMMIT_MESSAGE=$(cat "$COMMIT_MESSAGE_FILE")

if echo $COMMIT_MESSAGE | grep -q "PROJ-XXXX"
then
    echo "ERROR: Please either delete the PROJ-XXXX, or enter a proper JIRA ticket number"
    exit 1
fi

This works, but if I write a commit message during a commit, and forget to update the ticket number, it will close the editor, show the error, and discard my message completely.

Is there a way to have the hook either rerun the editor so I can edit my message, or at least remember what my commit message was next time I run git commit -v so I don't need to retype the commit message?

git


Solution 1:[1]

I thought there might be a simple, built-in way to do it, but I guess not. I just wrote this - it seems to work pretty good:

#!/bin/bash

# JIRA tag format
JIRA_TAG="PROJ-XXXX"

# Allows us to read user input below, assigns stdin to keyboard
exec < /dev/tty

# Colors
SWITCH="\033["
NORMAL="${SWITCH}0m"
RED="${SWITCH}1;31m"
YELLOW="${SWITCH}1;33m"

# Commit file
COMMIT_MESSAGE_FILE="$1"

while true
do
    COMMIT_MESSAGE=$(cat "$COMMIT_MESSAGE_FILE")

    if echo $COMMIT_MESSAGE | grep -q "${JIRA_TAG}"
    then
        # Print the problem
        echo -e "${RED}ERROR${NORMAL}: Please either delete the ${YELLOW}${JIRA_TAG}${NORMAL}, or enter a proper JIRA ticket number"
        read -p "Press Enter to Try Again"

        # Rerun in editor
        # Exit if editor exits with an error
        # This lets someone break out of loop with :cq in vim
        # Nano doesn't appear to have a similar way to exit with an error
        # code
        $EDITOR "$COMMIT_MESSAGE_FILE" || exit 1
    else
        exit 0
    fi
done

This git hook, saved in .git/hooks/commit-msg, along with a ~/.gitmessage of something like this:


Jira Tickets: PROJ-XXXX

Ensures that you never forget to include a JIRA tag in your commit.

Note: ~/.gitmessage needs to be enabled with something like:

git config --global commit.template ~/.gitmessage

and the commit-msg hook needs to be executable (chmod +x .git/hooks/commit-msg)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John