Last active
December 5, 2019 17:46
-
-
Save Mikhus/7db3256b901478352e22bfee8e8ad9a5 to your computer and use it in GitHub Desktop.
Semantic commit message hook for git in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# ISC License | |
# | |
# Copyright (c) 2019-present, Mykhailo Stadnyk <mikhus@gmail.com> | |
# | |
# Permission to use, copy, modify, and/or distribute this software for any | |
# purpose with or without fee is hereby granted, provided that the above | |
# copyright notice and this permission notice appear in all copies. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES | |
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF | |
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR | |
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES | |
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN | |
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF | |
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | |
input_file=$1 | |
first_line=`head -n1 ${input_file}` | |
allowed="feat|fix|docs|style|refactor|perf|test|chore" | |
pattern="^(${allowed}):( (\[[-A-Za-z0-9]+\]))? (.+)$" | |
red='\033[1;31m' | |
gre='\033[1;32m' | |
yel='\033[1;33m' | |
cya='\033[1;36m' | |
def='\033[0m' | |
trim() { | |
local s="$*" | |
s="${s#"${s%%[![:space:]]*}"}" | |
s="${s%"${s##*[![:space:]]}"}" | |
echo -n "$s" | |
} | |
usage () { | |
echo -e "${red}Bad commit message!${def}" | |
echo -e "Correct format is: ${cya}tag: [BUG_ID] Message${def}" | |
echo -e "Allowed tags:" | |
IFS="|" read -ra items <<< ${allowed} | |
for item in "${items[@]}"; do | |
echo -e " - ${gre}${item}${def}" | |
done | |
echo -e "[JIRA_ID] is optional, but recommended." | |
echo -e "Message can not be empty!" | |
} | |
if ! [[ ${first_line} =~ ${pattern} ]]; then | |
# bad commit message format overall, so | |
usage ; exit 1 | |
fi | |
msg=$(trim "${BASH_REMATCH[4]}") | |
bug_id=$(trim "${BASH_REMATCH[3]}") | |
if [[ ${msg} = "" ]]; then | |
# empty commit message when trimmed | |
usage ; exit 1 | |
fi | |
if [[ ${bug_id} = "" ]]; then | |
# jira id not found - accept, but warn | |
echo -e "${red}Warning:${yel} bug-tracking identifier is missing...${def}" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will allow to commit only if commit message provided satisfies to so called "semantic release"
So it will expect the following message format:
Where tag should be one of
feat|fix|docs|style|refactor|perf|test|chore
[BUG_ID] is optional and will generate warning message if missing
Commit message itself is checked to be non-empty message