Skip to content

Instantly share code, notes, and snippets.

@tekul
Created April 15, 2022 17:28
Show Gist options
  • Save tekul/3a1bcda170108d0622b1c6be7f6fe014 to your computer and use it in GitHub Desktop.
Save tekul/3a1bcda170108d0622b1c6be7f6fe014 to your computer and use it in GitHub Desktop.
Rust code coverage script
#!/bin/bash
#
# Prerequisites:
# rustup component add llvm-tools-preview
# cargo install rustfilt
# jq
set -euo pipefail
TOOLS_DIR="$(rustc --print sysroot)/lib/rustlib/x86_64-unknown-linux-gnu/bin"
# Generate raw profile data (appears in individual crate directories)
RUSTFLAGS="-C instrument-coverage" LLVM_PROFILE_FILE="project-%m.profraw" cargo test --tests
# Create combined data file
PROFRAW_FILES=$(find . -name "*.profraw")
$TOOLS_DIR/llvm-profdata merge --sparse -o project.profdata $PROFRAW_FILES
rm -f $PROFRAW_FILES
PROFILED_FILES="$( \
for file in \
$( \
RUSTFLAGS="-C instrument-coverage" \
cargo test --tests --no-run --message-format=json \
| jq -r "select(.profile.test == true) | .filenames[]" \
| grep -v dSYM - \
); \
do \
printf "%s %s " --object=$file; \
done \
)"
$TOOLS_DIR/llvm-cov report \
$PROFILED_FILES \
--Xdemangler=rustfilt \
--instr-profile=project.profdata \
--ignore-filename-regex='/.cargo/registry'
$TOOLS_DIR/llvm-cov show \
$PROFILED_FILES \
--Xdemangler=rustfilt \
--instr-profile=project.profdata \
--ignore-filename-regex='/.cargo/registry' \
--show-line-counts-or-regions \
--show-instantiations \
--format=html > coverage.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment