Skip to content

Instantly share code, notes, and snippets.

@allartk
Forked from mathiasschopmans/commit-msg
Last active October 7, 2024 09:15
Show Gist options
  • Select an option

  • Save allartk/2361cb51716f1f135a32740d10ee0869 to your computer and use it in GitHub Desktop.

Select an option

Save allartk/2361cb51716f1f135a32740d10ee0869 to your computer and use it in GitHub Desktop.
Git commit hook using bash to validate the commit message against conventional commits
#!/usr/bin/env bash
# Credits: https://gist.github.com/mathiasschopmans/70e8d466c620d950f2ca2cea08c4e279#file-how-to-setup-git-commit-hook-for-conventional-commits-using-bash-md
# Get the commit message
commit_msg=$(cat "$1")
# Define a regex pattern to match the conventional commit message format
pattern='^((Merge|Revert) .*$|(api|break|new|feat|fix|docs|refactor|ci|chore|perf|style|test)(: |\(.{1,}\):).*)'
# Test if the commit message matches the pattern
if ! [[ $commit_msg =~ $pattern ]]; then
echo "ERROR: The commit message does not match the Conventional Commits format."
echo " Please use the format: type(scope)?: subject"
echo " Example: feat(users): add new user endpoint"
echo " See https://www.conventionalcommits.org/en/v1.0.0/#summary for more information"
exit 1
fi
# If the commit message matches the pattern, exit successfully
exit 0
  • Open your terminal and navigate to your local git repository.
  • Create a file named commit-msg in the .git/hooks/ directory.
  • Place contents of commit-msg in the file
  • Save and close the commit-msg file.
  • Make the commit-msg file executable by running the following command in the terminal:
    • chmod +x .git/hooks/commit-msg

That's it!

The git commit hook is now in place, and every time you try to make a commit, it will validate the commit message against the conventional commit format. If the commit message doesn't match the format, it will show an error message and prevent the commit. If it matches, the commit will go through successfully.

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