1+ name : Commit Checker
2+
3+ # Run on push to any branch
4+ on : [pull_request]
5+
6+ jobs :
7+ Commit_Checker :
8+ runs-on : ubuntu-latest
9+
10+ steps :
11+ - uses : actions/checkout@v3
12+ with :
13+ fetch-depth : 0
14+ ref : ' ${{ github.event.pull_request.base.ref }}'
15+
16+ - name : Commit validation
17+ run : |
18+ # Checkout branch
19+ git checkout -q ${{ github.event.pull_request.head.ref }}
20+
21+ # Set variables
22+ BASE_BRANCH=${{ github.event.pull_request.base.ref }}
23+ msg_regex='(AAA|BBB|CCC)\-[0-9]+'
24+
25+ # Initialize invalidCommit as false, will be set to true by any invalid commits
26+ invalidCommit=false
27+ # Find current branch name
28+ CURRENT_BRANCH=$(git branch | grep ^\* | cut -d "*" -f 2 | cut -d " " -f 2)
29+ #echo "Current branch is:" $CURRENT_BRANCH
30+ # Find hash of commit most common ancestor, e.g. where branch began
31+ BRANCH_MERGE_BASE=$(git merge-base ${BASE_BRANCH} ${CURRENT_BRANCH})
32+ #echo "Branch merge base hash is:" $BRANCH_MERGE_BASE
33+ # Find all commits since common ancestor
34+ BRANCH_COMMITS=$(git rev-list ${BRANCH_MERGE_BASE}..HEAD)
35+ #echo $BRANCH_COMMITS
36+ # Check every commit message since ancestor for regex match
37+ for commit in $BRANCH_COMMITS; do
38+ if git log --max-count=1 --format=%B $commit | tr '[a-z]' '[A-Z]' | grep -iqE "$msg_regex"; then
39+ : #If commit matches regex, commit is valid, do nothing
40+ else
41+ # If commit doesn't match regex, commit isn't valid, print commit info
42+ echo "************"
43+ printf "Invalid commit message: \"%s\" and hash: %s\n" "$(git log --max-count=1 --format=%B $commit)" "$commit"
44+ echo "************"
45+
46+ # Set this variable to trigger rejection if any commit fails regex
47+ invalidCommit=true
48+ fi
49+ done
50+ # If any commit are invalid, print reject message
51+ if [ "$invalidCommit" == true ]; then
52+ echo "Your push was rejected because at least one commit message on this branch is invalid"
53+ echo "Please fix the commit message(s) and push again."
54+ echo "https://help.github.com/en/articles/changing-a-commit-message"
55+ echo "************"
56+ exit 1
57+ elif [ "$invalidCommit" == false ]; then
58+ echo "************"
59+ echo "All commits are valid"
60+ echo "************"
61+ exit 0
62+ fi
0 commit comments