Skip to content

Instantly share code, notes, and snippets.

@voiski
Last active July 2, 2018 19:13
Show Gist options
  • Save voiski/7f7bde735d106ea8ed7864d95f04dec4 to your computer and use it in GitHub Desktop.
Save voiski/7f7bde735d106ea8ed7864d95f04dec4 to your computer and use it in GitHub Desktop.
Pre commit template to append the branch name in the commit message
#!/bin/ssh
# Script to configure a prepare commit msg hook to concatenate your branch name into at begin of your commit message.
# This is usefull if you work with jira or other track tool.
# To run it, simple run the bellow line:
# curl -Ssf https://gist.githubusercontent.com/voiski/7f7bde735d106ea8ed7864d95f04dec4/raw/install_commit_template_hook.sh|bash
# Creating file on your home folder
mkdir -p ~/.git-templates/hooks
cat << 'EOF' > ~/.git-templates/hooks/prepare-commit-msg
#!/bin/bash
# Comment this line if you want to always concatenate the branch name when it is missing.
# This line will avoid the rebase message changes that is a little annoying.
if [ -n "$COMMIT_MSG_FILE" ];then return; fi
COMMIT_MSG_FILE=$1
BRANCH_NAME=$(git symbolic-ref --short HEAD | sed 's/\(.*-[0-9][0-9]*\).*/\1/')
BRANCH_NAME="${BRANCH_NAME##*/}"
if [ -n "$BRANCH_NAME" ] &&
[ $(head -1 ${COMMIT_MSG_FILE}|grep -c "${BRANCH_NAME}" ) = 0 ]
then
sed -i.bak -e "1s/^/${BRANCH_NAME} /" ${COMMIT_MSG_FILE}
fi
EOF
chmod +x ~/.git-templates/hooks/prepare-commit-msg
# Use this line to config as default for all new git clones/init
git config --global init.templatedir '~/.git-templates'
# Use this line to create a alias to install this hook on existing local git repos
# git install-commit-template
git config --global alias.install-commit-template '!ln -s ~/.git-templates/hooks/prepare-commit-msg .git/hooks/prepare-commit-msg'
@voiski
Copy link
Author

voiski commented Jul 2, 2018

To run it in your local, do:

curl -Ssf https://gist.githubusercontent.com/voiski/7f7bde735d106ea8ed7864d95f04dec4/raw/install_commit_template_hook.sh|bash

To remove it, just:

git.config --global --unset alias.install-commit-template
git.config --global --unset init.templatedir
rm -Rf ~/.git-templates # check if you need this folder
# This will not remove the hook from the existing local repositories, you can go into each one
rm .git/hooks/prepare-commit-msg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment