name: Changelog

on:
  push:
    branches:
      - main
    paths-ignore:
      - 'CHANGELOG.md'
      - '.github/workflows/changelog.yml'

  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: false

permissions: {}

env:
  RUMDL_VERSION: "0.1.42"

jobs:
  changelog:
    name: Update Changelog
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd  # v6
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Install git-cliff
        uses: taiki-e/install-action@b651345a718c8f44efa2460560b3dbf29cbd7ee1  # v2
        with:
          tool: git-cliff@2.12.0

      - name: Cache rumdl
        uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae  # v5
        with:
          path: ~/.cargo/bin/rumdl
          key: rumdl-${{ env.RUMDL_VERSION }}
      - name: Install rumdl
        run: command -v rumdl || cargo install rumdl@${{ env.RUMDL_VERSION }}

      - name: Generate changelog
        run: git cliff -o CHANGELOG.md

      - name: Format changelog
        run: rumdl fmt CHANGELOG.md

      - name: Commit updated changelog
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          git diff --quiet CHANGELOG.md && exit 0
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"
          git add CHANGELOG.md
          git commit -m "chore: update changelog [skip ci]"
          git pull --rebase
          git push
