Skip to content

Instantly share code, notes, and snippets.

@amussey amussey/README.md
Last active Dec 26, 2015

Embed
What would you like to do?
Automatically insert the ticket number from the branch name at the front of your commit message.

git: Prepend Ticket Information

To eliminate the need to constantly type out the ticket information at the beginning of a commit message, this script uses the built in git hook system to prepend commits with the ticket information from the branch name. For example, if your branch is named:

b-51392/fixed-minor-visual-bug

the hook will grab the ticket information at the beginning of the branch name and prepend it to your comments:

$ git commit -m "Test commit message"
[b-51392/fixed-minor-visual-bug 74cfe0e] B-51392: Test commit message.
 1 file changed, 1 insertion(+)

$ git log
commit 74cfe0eddf3fa9f2056a95aa06085cc4e2e57520
Author: Andrew Mussey
Date:   Tue Oct 29 10:25:27 2013 -0400

    B-51392: Test commit message.

Requirements

In order for this to work as expected, the ticket must be in the format of:

[Ticket info]/[Title]

On top of this, the expected format of the ticket name is one of the following:

[Single Letter]-[Series of numbers] (such as b-51231 or d-42132)
hackday

Any other ticket name is currently discarded.

Usage

Copy this file to your local git repo, and save it in the .git/hooks directory as prepare-commit-msg. Then, run:

chmod +x prepare-commit-msg

It's as easy as that!

Note: You will have to do this for each repo.

#!/bin/bash
# Save this file in your local git repo at:
# .git/hooks/prepare-commit-msg
#
# (no *.sh file extension)
# Then, run:
# chmod +x prepare-commit-msg
BRANCH_NAME=$(git branch 2>/dev/null | grep -e ^* | tr -d ' *')
BRANCH_HEADER=($(echo $BRANCH_NAME | tr '[:lower:]' '[:upper:]' | tr "//" "\n"))
COMMIT_MESSAGE=`cat $1`
CURRENT_COMMIT_HEAD=$(echo ${COMMIT_MESSAGE:0:${#BRANCH_HEADER[0]}} | tr '[:lower:]' '[:upper:]')
if [ "$BRANCH_NAME" != "master" ]
then
if [ "${BRANCH_HEADER[0]}" != "$CURRENT_COMMIT_HEAD" ]
then
if [[ "${BRANCH_HEADER[0]}" =~ [A-Z]-[0-9]+ ]]
then
echo "${BRANCH_HEADER[0]}: $COMMIT_MESSAGE" > $1
elif [[ "${BRANCH_HEADER[0]}" == "HACKDAY" ]]
then
echo "Hackday: $COMMIT_MESSAGE" > $1
fi
fi
fi
@apretto

This comment has been minimized.

Copy link

apretto commented Nov 14, 2013

If you have the git bash prompt plugin installed:

if [[ $(type -t __git_ps1) == "function" ]]
then
    BRANCH_NAME=$(__git_ps1 '%s')
else
    BRANCH_NAME=$(git branch 2>/dev/null | grep -e ^* | tr -d ' *')
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.