|
| 1 | +name: Conventional Commits |
| 2 | + |
| 3 | +on: |
| 4 | + pull_request: |
| 5 | + # Just some events that could involve commit messages |
| 6 | + types: [opened, synchronize, reopened] |
| 7 | + |
| 8 | +jobs: |
| 9 | + validate-commit-names: |
| 10 | + name: Check Commit Names |
| 11 | + runs-on: ubuntu-latest |
| 12 | + |
| 13 | + steps: |
| 14 | + # Checkout the repository |
| 15 | + - name: Checkout repository |
| 16 | + uses: actions/checkout@v5 |
| 17 | + with: |
| 18 | + # Fetch full history so we can access all commits in the PR |
| 19 | + fetch-depth: 0 |
| 20 | + |
| 21 | + # Validate commit messages |
| 22 | + - name: Validate all commit messages |
| 23 | + run: | |
| 24 | + echo "Validating all commit names in PR #${{ github.event.pull_request.number }}" |
| 25 | +
|
| 26 | + # Get the base branch and the PR branch |
| 27 | + BASE_BRANCH="${{ github.event.pull_request.base.ref }}" |
| 28 | + HEAD_BRANCH="${{ github.event.pull_request.head.ref }}" |
| 29 | +
|
| 30 | + # Fetch the base branch so we can compare commits |
| 31 | + git fetch origin $BASE_BRANCH |
| 32 | +
|
| 33 | + # Get all commits in the PR (not the base branch ones) |
| 34 | + # --pretty=format:"%s" gets only the commit message |
| 35 | + commits=$(git log origin/$BASE_BRANCH..$HEAD_BRANCH --pretty=format:"%s") |
| 36 | +
|
| 37 | + #List of commit messages to validate |
| 38 | + echo "$commits" |
| 39 | +
|
| 40 | + # Regex pattern for valid Conventional Commit prefixes with a mandatory space |
| 41 | + regex='^(docs: |fix: |feat: |chore: |refactor: |test: |style: |build: |ci: ).+' |
| 42 | +
|
| 43 | + # Variable to count errors |
| 44 | + fail=0 |
| 45 | +
|
| 46 | + # 'IFS=' disables splitting of the line into words |
| 47 | + # '-r' disables interpreting backslashes as escape characters (keeps \ literally) |
| 48 | + while IFS= read -r commitmsg; do |
| 49 | + # Skip merge and tx commits |
| 50 | + if [[ "$commitmsg" =~ ^Merge\ pull\ request || "$commitmsg" =~ ^\[tx\] ]]; then |
| 51 | + echo "Ignoring merge commit: $commitmsg" |
| 52 | + continue |
| 53 | + fi |
| 54 | +
|
| 55 | + # Check if the commit message matches the regex |
| 56 | + if ! [[ "$commitmsg" =~ $regex ]]; then |
| 57 | + echo "Invalid commit: $commitmsg" |
| 58 | + fail=$((fail+1)) |
| 59 | + fi |
| 60 | + done <<< "$commits" |
| 61 | +
|
| 62 | + # Fail the job if there are any invalid commits |
| 63 | + if [[ $fail -gt 0 ]]; then |
| 64 | + echo "$fail commit(s) do not follow the Conventional Commits convention" |
| 65 | + exit 1 |
| 66 | + else |
| 67 | + echo "✅ All commits follow the Conventional Commits convention" |
0 commit comments