# .github/workflows/publish.yml
name: Publish to crates.io

on:
  push:
    tags:
      - 'v[0-9]+.[0-9]+.[0-9]+*' # Trigger on tags like v0.1.0, v1.2.3, v1.0.0-beta.1

jobs:

  test:
    runs-on: ubuntu-latest
    steps:
      - name: Clean up runner image
        run: |
          df -h
          rm -rf /opt/hostedtoolcache
          sudo rm -rf /usr/local/lib/android
          sudo rm -rf /usr/share/dotnet
          sudo rm -rf "$AGENT_TOOLSDIRECTORY"
          df -h

      - name: Checkout code
        uses: actions/checkout@v5

      - name: Set up Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy, rustfmt
      - name: Install protoc
        uses: arduino/setup-protoc@v2
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}

      - name: Cache Cargo
        uses: Swatinem/rust-cache@v2

      - name: Install just
        uses: taiki-e/install-action@just

      - name: Run offline tests
        run: just test-offline

      - name: Run clippy linter
        run: just lint
  
  publish:
    name: Publish
    needs: test
    runs-on: ubuntu-latest
    permissions:
      contents: read

    steps:
      - name: Checkout code
        uses: actions/checkout@v5

      - name: Set up Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy, rustfmt

      - name: Install protoc
        uses: arduino/setup-protoc@v2
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}

      - name: Publish to crates.io
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
  
  create-release:
    needs: test
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: read
    steps:
      - name: Checkout code
        uses: actions/checkout@v5

      - name: Create GitHub Releases based on changelog
        uses: taiki-e/create-gh-release-action@v1.9.1
        with:
          changelog: CHANGELOG.md
          token: ${{ secrets.GITHUB_TOKEN }}