#!/usr/bin/env bash

# Validate conventional commit messages in git history
# Usage: gc-check [number_of_commits]

set -o errexit
set -o nounset

# Full conventional commit regex:
# type(optional-scope)optional-!: description
COMMIT_REGEX='^(feat|fix|docs|style|refactor|test|chore|perf|ci|build)(\([^)]+\))?!?: .+'

count=${1:-10}
errors=0

echo "Checking last $count commits..."
echo ""

while IFS= read -r line; do
    hash=$(echo "$line" | cut -d' ' -f1)
    msg=$(echo "$line" | cut -d' ' -f2-)

    if echo "$msg" | grep -qE "$COMMIT_REGEX"; then
        if echo "$msg" | grep -qE '^[^:]+!:'; then
            echo "✓ $hash $msg (BREAKING)"
        else
            echo "✓ $hash $msg"
        fi
    else
        echo "✗ $hash $msg"
        errors=$((errors + 1))
    fi
done < <(git log --oneline -n "$count")

echo ""
if [ $errors -gt 0 ]; then
    echo "$errors invalid commit(s) found"
    exit 1
else
    echo "All commits valid"
fi
