Skip to content

Instantly share code, notes, and snippets.

@nelsonfncosta
Created February 8, 2019 16:00
Show Gist options
  • Save nelsonfncosta/dcf89b4c6c2805ae0d9c949292adc2a3 to your computer and use it in GitHub Desktop.
Save nelsonfncosta/dcf89b4c6c2805ae0d9c949292adc2a3 to your computer and use it in GitHub Desktop.
Commit prepare message
#!/bin/sh
#
# Automatically adds issue number (optional) and ticket number based on branch name or
# description to every commit message.
#
# Copy this file to .git/hooks under your local repository directory
# PS: If you're on linux you may need to change "sed -En" to "sed -rn"
#
# Example:
#
# Branch name:
# 765-APP-10-my-branch-name
#
# Will generate the following template for all commit messages of this branch:
#
# JIRA APP-10
# Issue #765
#
#
# You may alternatively use the usual branch name (e.g. 765-my-branch-name)
# and perform:
# > git branch --edit-description
# > APP-10
#
branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)" # detached HEAD
branch_name=${branch_name##refs/heads/}
issue=$(echo $branch_name | sed -En "s/^([0-9]+)-.*/\1/p")
ticket=$(git config branch."$branch_name".description) ||
ticket=$(echo $branch_name | sed -En "s/^([0-9]+-)?([^-]+-[0-9]+).*/\2/p")
[ -z "$ticket" ] && ticket="(TICKET_NUMBER)"
firstLine=$(head -n1 $1)
# Check that this is not an amend by checking that the first line is empty
if [ -z "$firstLine" ] && [ -n "$ticket" ]; then
if [ -n "$issue" ]; then
sed -i '' '1s/^/\
\
JIRA '$ticket'\
Issue #'$issue'/' $1 # Insert issue and ticket
else
sed -i '' '1s/^/\
\
JIRA '$ticket'/' $1 # Only insert ticket
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment