name: Rust CI

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

env:
  CARGO_TERM_COLOR: always

jobs:
  test:
    name: Build
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        rust: [stable, beta, nightly]
    steps:
    - uses: actions/checkout@v4
    - name: Install Rust
      uses: dtolnay/rust-toolchain@master
      with:
        toolchain: ${{ matrix.rust }}
    - name: Cache cargo registry
      uses: actions/cache@v4
      with:
        path: ~/.cargo/registry
        key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
    - name: Cache cargo index
      uses: actions/cache@v4
      with:
        path: ~/.cargo/git
        key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
    - name: Cache cargo build
      uses: actions/cache@v4
      with:
        path: target
        key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }}

  fmt:
    name: Rustfmt
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - name: Install Rust
      uses: dtolnay/rust-toolchain@nightly
      with:
        components: rustfmt
    - name: Check formatting
      run: cargo fmt --all -- --check

  clippy:
    name: Clippy
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - name: Install Rust
      uses: dtolnay/rust-toolchain@stable
      with:
        components: clippy
    - name: Rust Cache
      uses: Swatinem/rust-cache@v2
    - name: Install dependencies
      run: |
        sudo apt-get update
        sudo apt-get install -y libfontconfig1-dev
    - name: Run clippy
      run: cargo clippy --all-targets -- -D warnings

  doc:
    name: Documentation
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - name: Install Rust
      uses: dtolnay/rust-toolchain@stable
    - name: Rust Cache
      uses: Swatinem/rust-cache@v2
    - name: Install dependencies
      run: |
        sudo apt-get update
        sudo apt-get install -y libfontconfig1-dev
    - name: Check documentation
      run: cargo doc --no-deps --document-private-items
      env:
        RUSTDOCFLAGS: -D warnings

  coverage:
    name: Code Coverage
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - name: Install Rust
      uses: dtolnay/rust-toolchain@nightly
      with:
        components: llvm-tools-preview
    - name: Install tarpaulin
      uses: taiki-e/install-action@cargo-tarpaulin
    - name: Install dependencies
      run: |
        sudo apt-get update
        sudo apt-get install -y libfontconfig1-dev
    - name: Generate coverage
      run: cargo tarpaulin --engine=llvm --out xml --workspace --run-types AllTargets --run-types Doctests
    - name: Upload coverage to Codecov
      uses: codecov/codecov-action@v5
      with:
        token: ${{ secrets.CODECOV_TOKEN }}
        fail_ci_if_error: false
