Skip to content

Commit

Permalink
feat: add conventional-pre-commit hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Atiqur Rahman committed Apr 11, 2022
1 parent e3a2150 commit 8f0c719
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
12 changes: 12 additions & 0 deletions detekt.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,15 @@ task createDetektPreCommitHook() {
"""
"chmod +x .git/hooks/pre-commit".execute()
}

task createConventionalMessagePreCommitHook() {
def gitHooksDirectory = new File("$project.rootDir/.git/hooks/")
if (!gitHooksDirectory.exists()) gitHooksDirectory.mkdirs()
new File("$project.rootDir/.git/hooks", "commit-msg").text = """
#!/bin/bash
echo "Running Conventional Commit check"
commit_message="\$1"
./scripts/conventional-pre-commit.sh "\$commit_message"
"""
"chmod +x .git/hooks/commit-msg".execute()
}
48 changes: 48 additions & 0 deletions scripts/conventional-pre-commit.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/usr/bin/env bash

# list of Conventional Commits types
cc_types=("feat" "fix")
default_types=("build" "chore" "ci" "docs" "${cc_types[@]}" "perf" "refactor" "revert" "style" "test")
types=( "${cc_types[@]}" )

if [ $# -eq 1 ]; then
types=( "${default_types[@]}" )
else
# assume all args but the last are types
while [ $# -gt 1 ]; do
types+=( "$1" )
shift
done
fi

# the commit message file is the last remaining arg
msg_file="$1"

commit_msg_type_regex='feat|fix|refactor|style|test|docs|build'
commit_msg_scope_regex='.{1,20}'
commit_msg_subject_regex='.{1,100}'
commit_msg_regex="^(${commit_msg_type_regex})(\(${commit_msg_scope_regex}\))?: (${commit_msg_subject_regex})\$"
merge_msg_regex="^Merge branch '.+'\$"

commit_msg_header=$(git show -s --format=%s $msg_file)

# Check if commit is conventional commit
if ! [[ "$commit_msg_header" =~ (${commit_msg_regex})|(${merge_msg_regex}) ]]; then
exit 0
fi

echo "[Commit message] $( cat "$msg_file" )"
echo "
Your commit message does not follow Conventional Commits formatting
https://www.conventionalcommits.org/
Conventional Commits start with one of the below types, followed by a colon,
followed by the commit message:
$(IFS=' '; echo "${types[*]}")
Example commit message adding a feature:
feat: implement new API
Example commit message fixing an issue:
fix: remove infinite loop
Optionally, include a scope in parentheses after the type for more context:
fix(account): remove infinite loop
"
exit 1
2 changes: 1 addition & 1 deletion scripts/pre-commit.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/bin/bash
echo "Running detekt check"
./gradlew detekt
./gradlew detekt

0 comments on commit 8f0c719

Please sign in to comment.