Skip to content

Instantly share code, notes, and snippets.

@ITler
Last active August 7, 2019 14:31
Show Gist options
  • Save ITler/5636c9665b9aab28e31d0047855d3259 to your computer and use it in GitHub Desktop.
Save ITler/5636c9665b9aab28e31d0047855d3259 to your computer and use it in GitHub Desktop.
#! /usr/bin/env sh
CYAN='\033[0;36m'
RED='\033[0;31m'
DC='\033[0m' # default color
sanitize_msg() {
grep -E -o '^[^#].*' "$1"
}
# Do not allow empty messages after removing comments
[ -z "$(sanitize_msg "$1")" ] && {
echo >&2 "${CYAN}Empty commit message not allowed.${DC}"
exit 1
}
# Prepend to message Jira issues found in branch name but not found within message
BRANCH_ISSUE_REFS="$(git rev-parse --abbrev-ref HEAD | grep -E -io '\b[a-z]{3,}-[1-9][0-9]*\b')"
for ISSUE in ${BRANCH_ISSUE_REFS}; do
ISSUE=$(echo "${ISSUE}" | tr '[:lower:]' '[:upper:]')
sanitize_msg "$1" | grep -iE "\b${ISSUE}\b" || sed -i "" -e "1s/^/${ISSUE} /" "$1"
done
if [ -z "${BRANCH_ISSUE_REFS}" ]; then
# Allow non prefixed commit messages, when branch name not referring JIRA issue
sanitize_msg "$1" | grep -E -qi '\b[a-z]{3,}-[1-9][0-9]*\b' || {
echo >&2 "${RED}Commit message does not contain JIRA issue ID. Consider amending message before pushing.${DC}"
}
fi
#! /usr/bin/env sh
ORANGE='\033[0;33m'
DC='\033[0m' # default color
[ -x .git/hooks/commit-msg ] || echo -e "${ORANGE}Consider setting up git hooks for this repo using https://gist.github.com/ITler/5636c9665b9aab28e31d0047855d3259${DC}"
#! /usr/bin/env bash
COMMIT_MSG_FILE=$1
branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}
branch_name=$(echo ${branch_name} | tr '[:lower:]' '[:upper:]')
firstLine=$(head -n1 "${COMMIT_MSG_FILE}")
if [ -z "${firstLine}" ] ;then #Check that this is not an amend by checking that the first line is empty
sed -i "" "1s/^/${branch_name} /" "${COMMIT_MSG_FILE}" #Insert branch name at the start of the commit message file
fi
@ITler
Copy link
Author

ITler commented Aug 5, 2019

Git hook and optional check to integrate on shell-level with i.e. direnv.

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