diff --git a/.github/workflows/verify-pr-prefix.yml b/.github/workflows/verify-pr-prefix.yml new file mode 100644 index 0000000000..9a338ae898 --- /dev/null +++ b/.github/workflows/verify-pr-prefix.yml @@ -0,0 +1,38 @@ +name: Check if commit message contains role prefix + +on: + pull_request: + types: [opened, synchronize, edited, reopened] + +jobs: + verify-prefix: + runs-on: ubuntu-latest + continue-on-error: true + + permissions: + contents: write + pull-requests: write + repository-projects: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Run commit message check + id: prefixcheck + run: | + set +e + ./scripts/check-role-prefix.sh > result.log 2>&1 + EXIT_CODE=$? + echo "exit_code=$EXIT_CODE" >> $GITHUB_OUTPUT + cat result.log + + - name: Comment on PR if prefix check failed + if: steps.prefixcheck.outputs.exit_code != '0' + uses: peter-evans/create-or-update-comment@v5 + with: + issue-number: ${{ github.event.pull_request.number }} + body-path: ./result.log + reactions: confused diff --git a/scripts/check-role-prefix.sh b/scripts/check-role-prefix.sh new file mode 100755 index 0000000000..14c97c19e8 --- /dev/null +++ b/scripts/check-role-prefix.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +# Get the latest commit message file +TMP_MSG_FILE=$(mktemp) +git log -1 --pretty=format:"%s%n%n%b" >"$TMP_MSG_FILE" + +echo "Checking latest commit message:" +cat "$TMP_MSG_FILE" + +if [ -n "$GITHUB_BASE_REF" ]; then + CHANGED_ROLES=$(git diff "origin/${GITHUB_BASE_REF}" --name-only || true) +else + CHANGED_ROLES=$(git diff --cached --name-only || true) +fi + +CHANGED_ROLES=$(echo "$CHANGED_ROLES" | grep '^roles/' | cut -d'/' -f2 | sort -u | xargs | sed 's/ /|/g') +if [ -z "$CHANGED_ROLES" ]; then + echo "No roles modified - skipping check..." + exit 0 +fi + +echo -e "\n\nDetected changes in roles: **$CHANGED_ROLES**" +MSG=$(head -n 1 "$TMP_MSG_FILE") +ROLE_COUNT=$(echo "$CHANGED_ROLES" | tr '|' '\n' | wc -l) + +if [ "$ROLE_COUNT" -eq 1 ]; then + # shellcheck disable=SC1087 + PATTERN="^[\[(]$CHANGED_ROLES[\])]" +else + PATTERN="^[\[(](multiple)[\])]" +fi + +if ! grep -qE "$PATTERN" <<<"$MSG"; then + echo -e "\n**ERROR: Commit message must start with:**\n" + if [ "$ROLE_COUNT" -eq 1 ]; then echo -e "\t[$CHANGED_ROLES]\n"; fi + if [ "$ROLE_COUNT" -gt 1 ]; then echo -e "\t(multiple)\n\n"; fi + echo -e "Example commit header:\n" + echo -e "\t-[reproducer] fix task something\n" + echo -e "\t-(cifmw_helpers) improve code\n" + echo -e "\t-[multiple] updated default value" + exit 1 +fi + +echo "Commit message prefix is valid."