name: Code Coverage

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  coverage:
    name: Execute tests with code coverage
    runs-on: ubuntu-latest
    env:
      CARGO_TERM_COLOR: always
    steps:
      - uses: actions/checkout@v4
      - uses: actions-rust-lang/setup-rust-toolchain@v1.4.4
        with:
          toolchain: stable
      - uses: actions/cache@v4
        id: corpus-cache
        with:
          path: |
            relannis
            data
            data_ondisk
          key: ${{ runner.os }}-codecov-${{ hashFiles('graphannis/tests/searchtest.rs','graphannis/tests/searchtest_queries.csv', 'graphannis/build.rs') }}
      - name: Download test corpora
        if: steps.corpus-cache.outputs.cache-hit != 'true'
        run: test -d relannis/GUM/ -a -d relannis/pcc2.1/ -a -d relannis/subtok.demo || "./misc/download-test-corpora.sh"
      - name: Build CLI binary
        if: steps.corpus-cache.outputs.cache-hit != 'true'
        run: cargo build --release --bin annis
      - name: Import GUM corpus (memory)
        if: steps.corpus-cache.outputs.cache-hit != 'true'
        run: ./target/release/annis data --cmd 'import relannis/GUM'
      - name: Import pcc2.1 corpus (memory)
        if: steps.corpus-cache.outputs.cache-hit != 'true'
        run: ./target/release/annis data --cmd 'import relannis/pcc2.1'
      - name: Import subtok.demo corpus (memory)
        if: steps.corpus-cache.outputs.cache-hit != 'true'
        run: ./target/release/annis data --cmd 'import relannis/subtok.demo'
      - name: Install cargo-llvm-cov
        uses: taiki-e/install-action@cargo-llvm-cov
      - name: Remove old code coverage artifacts
        run: cargo llvm-cov clean --workspace
      - name: Run tests code coverage (standard tests)
        run: cargo llvm-cov --no-report --release
        env:
          RUSTFLAGS: "-C link-dead-code"
      - name: Run tests code coverage (ignored tests)
        run: cargo llvm-cov --no-report --release --tests -- --ignored
        env:
          RUSTFLAGS: "-C link-dead-code"
      - name: Merge code coverage reports
        run: cargo llvm-cov report --ignore-filename-regex '(tests?\.rs)|(capi/.*)' --release --codecov --output-path codecov.json
      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v4
        with:
          token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos
          files: codecov.json
          fail_ci_if_error: true
