name: Lint Workspace

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

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
  cancel-in-progress: true

jobs:
  lint:
    name: Lint
    runs-on:
      - runs-on=${{ github.run_id }}
      - runner=8cpu-linux-x64
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
        with:
          cache-on-failure: true

      - name: Generate docs
        run: |
          cargo doc --workspace  --exclude "openvm-benchmarks" --exclude "*-tests" --exclude "*-test"

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

      - name: Run clippy
        run: |
          # list of features generated using:
          # echo -e "\033[1;32mAll unique features across workspace:\033[0m" && cargo metadata --format-version=1 --no-deps | jq -r '.packages[].features | to_entries[] | .key' | sort -u | sed 's/^/• /'
          cargo clippy --all-targets --all --tests --features "aggregation bench-metrics bls12_381 bn254 default entrypoint export-getrandom export-libm function-span getrandom halo2-compiler halo2curves heap-embedded-alloc k256 mimalloc nightly-features panic-handler parallel rust-runtime static-verifier std test-utils unstable" -- -D warnings
          cargo clippy --all-targets --all --tests --no-default-features --features "jemalloc jemalloc-prof" -- -D warnings

      - name: Run fmt, clippy for guest
        run: |
          # Find all directories named "programs" and include additional static paths
          for crate_path in $(find . -type d -name "programs" -exec find {} -mindepth 0 -maxdepth 0 -type d \;) examples/*; do
            # Check if Cargo.toml exists in the directory
            if [ -f "$crate_path/Cargo.toml" ]; then
              echo "Running cargo fmt, clippy for $crate_path"
              cargo fmt --manifest-path "$crate_path/Cargo.toml" --all -- --check
              if [[ "$crate_path" == *"extensions/ecc/tests/programs"* ]]; then
                echo "Running cargo clippy with k256 feature for $crate_path"
                cargo clippy --manifest-path "$crate_path/Cargo.toml" --all-targets --features "std k256" -- -D warnings
              elif [[ "$crate_path" == *"extensions/pairing/tests/programs"* ]]; then
                echo "Running cargo clippy with openvm_pairing_guest::bn254 feature for $crate_path"
                cargo clippy --manifest-path "$crate_path/Cargo.toml" --all-targets --features "std bn254" -- -D warnings
              else
                echo "Running cargo clippy for $crate_path"
                cargo clippy --manifest-path "$crate_path/Cargo.toml" --all-targets --features std -- -D warnings
              fi
            else
              echo "Skipping $crate_path as it does not contain a Cargo.toml"
            fi
          done