Skip to content

Instantly share code, notes, and snippets.

@kurtke1990
Last active January 5, 2024 02:19
Show Gist options
  • Save kurtke1990/7b817cbd969bedd4e8f57a2fe7d731f4 to your computer and use it in GitHub Desktop.
Save kurtke1990/7b817cbd969bedd4e8f57a2fe7d731f4 to your computer and use it in GitHub Desktop.
semantic commit message hook
#!/bin/bash
current_branch=$(git rev-parse --abbrev-ref HEAD)
base_branch=$(git show-branch -a | grep '\*' | grep -v "$(git rev-parse --abbrev-ref HEAD)" | head -n1 | sed 's/[\^~].*/\]/' | sed 's/.*\[\(.*\)\].*/\1/')
msg_regex="(^(feat|fix|chore|docs|style|refactor|perf|test|build|ci)(\(([^)]*)\))?: (.+))|(^Merge (branch|pull request) .+)|(^Revert .+)"
commit_messages=$(git log --pretty="%s" "$base_branch..$current_branch")
IFS=$'\n'
for commit_msg in $commit_messages; do
if ! [[ $commit_msg =~ $msg_regex ]]; then
echo ""
echo "Invalid commit message: $commit_msg"
echo "Please revise all the commit messages with the semantic pattern in the branch: '$current_branch'"
echo ""
echo "The valid messages will be like:"
echo "--------------------------------"
echo "feat: add a new super feature"
echo "docs: update README.md"
echo "fix: [CS1234-5678] fix an error"
echo "refactor(helper): refactor the helper component"
echo ""
exit 1
fi
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment