Skip to content

Instantly share code, notes, and snippets.

@mathiasschopmans
Last active October 7, 2024 09:15
Show Gist options
  • Save mathiasschopmans/70e8d466c620d950f2ca2cea08c4e279 to your computer and use it in GitHub Desktop.
Save mathiasschopmans/70e8d466c620d950f2ca2cea08c4e279 to your computer and use it in GitHub Desktop.
Git commit hook using bash to validate the commit message against conventional commits
#!/bin/bash
# Get the commit message
commit_msg=$(cat $1)
# Define a regex pattern to match the conventional commit message format
pattern='^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z]+\))?!?: .+$'
# 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