name: CI

on: [push, pull_request]

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always
  CARGO_INCREMENTAL: 0

  RUSTFLAGS: -Dwarnings

  # setup sccache for Rust; see https://github.com/Mozilla-Actions/sccache-action
  SCCACHE_GHA_ENABLED: "true"
  RUSTC_WRAPPER: "sccache"

  # https://crates.io/crates/insta
  CI: true

jobs:

  check_project_files:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Restore lychee cache
        uses: actions/cache@v4
        with:
          path: .lycheecache
          key: cache-lychee-${{ github.sha }}
          restore-keys: cache-lychee-

      - uses: lycheeverse/lychee-action@v2
        with:
          args: "--cache --max-cache-age 1d . -v *.md"
          failIfEmpty: false

  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: mozilla-actions/sccache-action@v0.0.7
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - run: cargo verify-project
      - run: cargo fmt --check --all
      - run: cargo clippy -- -D warnings
      - run: cargo check --future-incompat-report
      - run: cargo doc --no-deps --document-private-items

  build_and_test:
    runs-on: ubuntu-latest
    needs: check
    steps:
      - uses: actions/checkout@v4

      - uses: mozilla-actions/sccache-action@v0.0.7
      - name: Cache Cargo dependencies
        uses: Swatinem/rust-cache@v2

      - uses: dtolnay/rust-toolchain@stable
        with:
          components: llvm-tools-preview

      - name: Install grcov
        uses: taiki-e/install-action@v2
        with:
          tool: grcov

      - name: Build
        env:
          RUSTFLAGS: -Cinstrument-coverage
        run: cargo build --verbose

      - name: Test
        env:
          LLVM_PROFILE_FILE: toml-rgb2ansi256-%p-%m.profraw
          RUSTFLAGS: -Cinstrument-coverage
        run: cargo test --verbose

      - name: Generate coverage
        run: |
          mkdir -p ./target/debug/coverage/
          grcov $(find . -name "toml-rgb2ansi256-*.profraw" -print) \
            --branch \
            --ignore-not-existing \
            --binary-path ./target/debug/ \
            -s . \
            -t lcov \
            --ignore "/*" \
            -o ./target/debug/coverage/

      - name: Upload coverage reports to Codecov
        uses: codecov/codecov-action@v5
        env:
          CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
        with:
          files: ./target/debug/coverage/lcov
