name: Lint commits

on:
  push:
    branches: [main, next, 'v*']
  pull_request:

permissions:
  contents: read

concurrency:
  group: "${{ github.workflow }}-${{ github.event.pull_request.head.label || github.head_ref || github.ref }}"
  cancel-in-progress: true

jobs:
  commitlint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v6
        with:
          node-version: lts/*
          package-manager-cache: false
      - run: npm ci || npm install
      - name: Select commitlint config
        id: config
        run: |
          if [ "${{ github.event.pull_request.user.login }}" = "dependabot[bot]" ]; then
            echo "path=./commitlint.config.dependabot.mjs" >> "$GITHUB_OUTPUT"
          else
            echo "path=./commitlint.config.mjs" >> "$GITHUB_OUTPUT"
          fi
      - name: Lint last commit (push)
        if: github.event_name == 'push'
        run: npx commitlint --last --verbose
      - name: Lint PR commits (pull_request)
        if: github.event_name == 'pull_request'
        run: npx commitlint --config "${{ steps.config.outputs.path }}" --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose

  pr-title:
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request'
    permissions:
      pull-requests: read
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v6
        with:
          node-version: lts/*
          package-manager-cache: false
      - run: npm ci || npm install
      - uses: wagoid/commitlint-github-action@v6
        with:
          configFile: ${{ github.event.pull_request.user.login == 'dependabot[bot]' && 'commitlint.config.dependabot.mjs' || 'commitlint.config.mjs' }}
        env:
          NODE_PATH: ${{ github.workspace }}/node_modules
