Skip to content

Instantly share code, notes, and snippets.

@migalmeida
Created January 12, 2021 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save migalmeida/6c6fe9e15aaaeb0690d15beb2bce2411 to your computer and use it in GitHub Desktop.
Save migalmeida/6c6fe9e15aaaeb0690d15beb2bce2411 to your computer and use it in GitHub Desktop.
#!/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