name: CI

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

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: short

jobs:
  ci:
    name: ${{ matrix.os }} / stable
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest]

    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain (stable)
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - name: Cache cargo registry & target
        uses: Swatinem/rust-cache@v2

      - name: cargo fmt --check
        run: cargo fmt --all -- --check

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

      - name: cargo test
        run: cargo test --all-targets --all-features

      - name: cargo build (release)
        run: cargo build --release --locked

      # tests/e2e/ scaffold は M6 で初めて land する。
      # それまでは下記 3 ステップは hashFiles ガードでスキップされる。
      - name: Check for e2e scaffold
        id: e2e_scaffold
        shell: bash
        run: |
          if [ -f tests/e2e/package.json ]; then
            echo "present=true" >> "$GITHUB_OUTPUT"
          else
            echo "present=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Setup bun
        if: steps.e2e_scaffold.outputs.present == 'true'
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

      - name: Install tuistory e2e deps
        if: steps.e2e_scaffold.outputs.present == 'true'
        working-directory: tests/e2e
        run: bun install --frozen-lockfile

      - name: Run tuistory e2e tests
        if: steps.e2e_scaffold.outputs.present == 'true'
        working-directory: tests/e2e
        run: bun test
        env:
          KIZU_BIN: ${{ github.workspace }}/target/release/kizu
