name: Cargo Build & Test
permissions:
  contents: read

on:
  pull_request:
    types:
      - opened
      - reopened
      - synchronize
      - ready_for_review

jobs:
  pre_ci:
    name: Pre-CI tests # run some tests like rust version control and style check
    runs-on: ubuntu-latest
    if: ${{ !github.event.pull_request.draft }}
    steps:
      - uses: actions/checkout@v6
      - uses: taiki-e/install-action@cargo-hack
      - run: rustup update stable && rustup update nightly
      - run: cargo hack check --rust-version --workspace --all-targets --ignore-private
        # ^ fail if code cannot be run with rust version specified in Cargo.toml
      - run: cargo clippy -- -D warnings
        # ^ fail on warnings by clippy
      - run: RUSTDOCFLAGS="-D warnings" cargo doc
        # ^ fail on documentation warnings
      - run: rustup component add rustfmt --toolchain nightly
      - run: cargo +nightly fmt --all -- --check
        # ^ fail when fmt was not run

  build_and_test:
    name: Rust project - latest
    runs-on: ubuntu-latest
    if: ${{ !github.event.pull_request.draft }}
    strategy:
      matrix:
        toolchain:
          - stable
          - beta
          - nightly
    steps:
      - uses: actions/checkout@v6
      - run: rustup update ${{ matrix.toolchain }} && rustup default ${{ matrix.toolchain }}
      - run: cargo build --verbose
      - run: cargo test --verbose
