Skip to content

Instantly share code, notes, and snippets.

@JanDeDobbeleer
Last active March 7, 2017 09:40
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 JanDeDobbeleer/08d0b587511bf2e2bdc004d3de7fad0d to your computer and use it in GitHub Desktop.
Save JanDeDobbeleer/08d0b587511bf2e2bdc004d3de7fad0d to your computer and use it in GitHub Desktop.
A commit-msg hook Enrico Campidoglio demonstrated at Techorama 2016. I found the code on his blog and as I don't trust myself, I tweaked the script to rerun the check until I get it right.
#!/bin/sh
#
# A hook script that checks the length of the commit message.
#
# Called by "git commit" with one argument, the name of the file
# that has the commit message. The hook should exit with non-zero
# status after issuing an appropriate message if it wants to stop the
# commit. The hook is allowed to edit the commit message file.
DEFAULT="\033[0m"
YELLOW="\033[1;33m"
function printWarning {
message=$1
printf >&2 "${YELLOW}$message${DEFAULT}\n"
}
function printNewline {
printf "\n"
}
function captureUserInput {
# Assigns stdin to the keyboard
exec < /dev/tty
}
function confirm {
question=$1
read -p "$question [y/n]"$'\n' -n 1 -r
}
function verify {
messageFilePath=$1
message=$(cat $messageFilePath)
firstLine=$(printf "$message" | sed -n 1p)
firstLineLength=$(printf ${#firstLine})
test $firstLineLength -lt 73 || {
printWarning "Tip: the first line of the commit message shouldn't be longer than 72 characters and yours was $firstLineLength."
printWarning "Message: $firstLine"
captureUserInput
confirm "Do you want to modify the message in code?"
if [[ $REPLY =~ ^[Yy]$ ]];
then
code $messageFilePath --wait
printNewline
verify $messageFilePath
else
printNewline
printWarning "I'm afraid I can't allow you to do that Dave."
printNewline
exit 1
fi
}
}
verify $1
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment