name: Measure Diff Across Multiple Repos
on:
  workflow_dispatch:
    inputs:
      prId:
        description: "PR #"
        required: true
        type: number
      type:
        description: "Diff computation type"
        required: true
        default: "diffAfterMainFormat"
        type: choice
        options:
          - diffAfterMainFormat # format using main branch first, then apply PR changes ontop of that
          - diffMainVsChangeFormat # format using main branch, store. Reset to original then format using PR branch. Compute differences

jobs:
  build-latest:
    name: Build Pull Request (#${{ github.event.inputs.prId }})
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Checkout Pull Request
        run: hub pr checkout ${{ github.event.inputs.prId }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Build (All features)
        run: cargo build --verbose --locked --release --all-features

      - name: Upload artifacts
        uses: actions/upload-artifact@v3
        with:
          name: stylua-latest
          path: target/release/stylua

  build-main:
    name: Build Main
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: "main"

      - name: Build (All features)
        run: cargo build --verbose --locked --release --all-features

      - name: Upload artifacts
        uses: actions/upload-artifact@v3
        with:
          name: stylua-main
          path: target/release/stylua

  run-comparison:
    runs-on: ubuntu-latest
    needs: ["build-main", "build-latest"]
    steps:
      - uses: actions/checkout@v4

      - name: Download artifacts
        uses: actions/download-artifact@v3
        with:
          path: artifacts

      - name: Set up artifacts
        run: |
          mv ./artifacts/stylua-main/stylua ./stylua-main
          mv ./artifacts/stylua-latest/stylua ./stylua-latest

      - name: Run comparison tool
        id: run_comparison
        run: |
          body="$(python ./.github/run_comparisons.py ${{ github.event.inputs.type }})"
          body="${body//'%'/'%25'}"
          body="${body//$'\n'/'%0A'}"
          body="${body//$'\r'/'%0D'}"
          echo "::set-output name=body::$body"

      - name: Create comment
        uses: peter-evans/create-or-update-comment@v3
        with:
          issue-number: ${{ github.event.inputs.prId }}
          body: ${{ steps.run_comparison.outputs.body }}
