Skip to content

Instantly share code, notes, and snippets.

@nicholaswmin
Last active July 21, 2024 02:31
Show Gist options
  • Save nicholaswmin/804e6178841be2d9b8cdef08a6bf890f to your computer and use it in GitHub Desktop.
Save nicholaswmin/804e6178841be2d9b8cdef08a6bf890f to your computer and use it in GitHub Desktop.
Conventional Commits message linter as a "commit-msg" Git hook
#!/bin/bash
# Conventional Commits "commit-msg" git hook #
#
# Installs a "Conventional Commit" commit-msg Git hook
# See more: https://www.conventionalcommits.org/
#
# Usage:
# - Copy this file to your repo
# - Run it once: bash install-cc-hook.sh
# - Delete this file
# create hook
# adapted from: https://github.com/joaobsjunior/sh-conventional-commits
#
# Authors: @nicholaswmin
# License: MIT "No Attribution" (MIT-0)
cat > .git/hooks/commit-msg << 'EOF'
#!/bin/bash
REGEX="^((Merge[ a-z-]* branch.*)|(Revert*)|((build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\(.*\))?!?: .*))"
FILE=`cat $1` # File containing the commit message
echo "Commit Message: ${FILE}"
if ! [[ $FILE =~ $REGEX ]]; then
printf "\n\x1B[31mCommit aborted for not following the Conventional Commit standard.​\x1B[0m\n" >&2
printf "\ncommit message must be in format: \"<type>: <message>\"\n"
printf "\n - where <type> can be any of: build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test\n"
printf " - example: git commit -am \"docs: added code examples in usage sections\"\n"
printf " - more info: https://www.conventionalcommits.org\n\n"
exit 1
else
printf "\n\x1B[34mValid commit message.​\x1B[0m\n"
fi
EOF
# ... ensure its executable
git config core.hooksPath .git/hooks
chmod ug+x .git/hooks/commit-msg
hook_file=.git/hooks/commit-msg
if [ -f "$hook_file" ]; then
printf "\n\x1B[32mHook succesfully installed\x1B[0m\n"
else
printf "\n\x1B[31mError: Cannot find installed hook​\x1B[0m\n"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment