name: Coverage

on:
  push:
    branches: [ master, main ]
  pull_request:
    branches: [ master, main ]

jobs:
  coverage:
    name: Generate Coverage Badge
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Install cargo-tarpaulin
        run: |
          cargo install cargo-tarpaulin --version 0.27.3 || cargo install cargo-tarpaulin

      - name: Generate coverage
        run: |
          cargo tarpaulin --verbose --all-features --workspace --timeout 120 --out xml --output-dir .

      - name: Extract coverage percentage
        id: coverage
        run: |
          # Extract coverage from cobertura.xml using Python
          COVERAGE=$(python3 -c "import xml.etree.ElementTree as ET; tree = ET.parse('cobertura.xml'); print(f\"{float(tree.getroot().attrib.get('line-rate', 0)) * 100:.2f}\")")
          echo "percentage=$COVERAGE" >> $GITHUB_OUTPUT
          echo "Coverage: $COVERAGE%"

      - name: Install coverage-badge CLI
        run: cargo install coverage-badge

      - name: Generate coverage badge
        run: |
          mkdir -p assets
          coverage-badge -c ${{ steps.coverage.outputs.percentage }} -o assets/coverage.svg

      - name: Commit badge
        run: |
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git add assets/coverage.svg
          git diff --quiet && git diff --staged --quiet || git commit -m "Update coverage badge"
          git push || echo "No changes to push"

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v4
        with:
          files: ./cobertura.xml
          fail_ci_if_error: false
        continue-on-error: true
