name: CI/CD

on: [ push, pull_request ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Cargo Cache
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            target/
          key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: ${{ runner.os }}-cargo-
      - name: Build project
        run: cargo build --workspace --release

  test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Install Rust
        run: rustup component add rustfmt clippy
      - name: Cargo Cache
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            target/
          key: ${{ runner.os }}-cargo-test-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: ${{ runner.os }}-cargo-
      - name: Run tests
        run: cargo test --workspace

  deploy_release:
    needs: [ build, test ]
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    if: startsWith(github.ref, 'refs/tags/')
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Install crates.io auth token
        uses: rust-lang/crates-io-auth-action@v1
        id: auth
      - name: Publish release
        run: cargo publish --workspace
        env:
          CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
