name: Build

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

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Run tests
        run: cargo test --all-targets

      - name: Run clippy
        run: cargo clippy --all-targets -- -D warnings

      - name: Check formatting
        run: cargo fmt -- --check

  build:
    name: Build (${{ matrix.name }})
    needs: test
    runs-on: ${{ matrix.runner }}
    strategy:
      matrix:
        include:
          - name: linux-x86_64
            runner: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - name: linux-aarch64
            runner: ubuntu-24.04-arm
            target: aarch64-unknown-linux-gnu
          - name: macos-aarch64
            runner: macos-latest
            target: aarch64-apple-darwin
          - name: windows-x86_64
            runner: windows-latest
            target: x86_64-pc-windows-msvc
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - name: Build
        run: cargo build --release --target ${{ matrix.target }}

      - name: Rename binary (unix)
        if: runner.os != 'Windows'
        run: mv target/${{ matrix.target }}/release/towl towl-${{ matrix.target }}

      - name: Rename binary (windows)
        if: runner.os == 'Windows'
        run: mv target/${{ matrix.target }}/release/towl.exe towl-${{ matrix.target }}.exe

      - name: Upload artifact (unix)
        if: runner.os != 'Windows'
        uses: actions/upload-artifact@v4
        with:
          name: towl-${{ matrix.target }}
          path: towl-${{ matrix.target }}

      - name: Upload artifact (windows)
        if: runner.os == 'Windows'
        uses: actions/upload-artifact@v4
        with:
          name: towl-${{ matrix.target }}
          path: towl-${{ matrix.target }}.exe
