Skip to content

Instantly share code, notes, and snippets.

@RomiC
Created March 12, 2023 07:24
Show Gist options
  • Save RomiC/179037f63392e4aea434b9e11a546218 to your computer and use it in GitHub Desktop.
Save RomiC/179037f63392e4aea434b9e11a546218 to your computer and use it in GitHub Desktop.
Bash script to calculate (jest) test coverage diff
#!/bin/bash
# Output sample
# ========================= Total coverage diff summary ==========================
# lines : +0.46% ( +33 )
# statements : +0.49% ( +36 )
# functions : +0.66% ( +17 )
# branches : +0.16% ( +4 )
# ================================================================================
usage() {
echo "
Usage: coverage-diff [-h?] BRANCH1 [BRANCH2]
Script calculate test coverage diff between two branches.
options:
-h -? Print this message and exit"
}
shortusage() {
echo "
Usage: coverage-diff [-h?] BRANCH1 [BRANCH2]
See coverage-diff -h for help"
}
error() {
if [[ -n $1 ]];
then
echo "\nERROR: $1"
if [[ -n $2 ]];
then
shortusage
fi
exit 1
fi
}
# Parsing flags
while getopts "h?l:" opt
do
case $opt in
h|\?)
usage
exit 0
;;
esac
done
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
BRANCH1=$1
if [[ -z $BRANCH1 ]]; then
error "You must specify at least one branch name!"
fi
BRANCH2=$2
if [[ -z $BRANCH2 ]]; then
BRANCH2=$CURRENT_BRANCH
fi
if [[ $BRANCH1 == $BRANCH2 ]]; then
error "Nothing to compare. Either specify BRANCH2 or switch to it first"
fi
# echo "Gathering coverage for '$BRANCH1'…";
git switch --quiet $BRANCH1
npx jest --silent --no-cache --coverage --coverageReporters=json-summary --coverageDirectory="/tmp/$BRANCH1" > /dev/null 2>&1
# echo "Gathering coverage for '$BRANCH2'…";
git switch --quiet $BRANCH2
npx jest --silent --no-cache --coverage --coverageReporters=json-summary --coverageDirectory="/tmp/$BRANCH2" > /dev/null 2>&1
diff() {
printf "%-13s: %+5.2f%% ( %+d )\n" $1 $(jq "\$b1[0].total.$1.pct-.total.$1.pct" --slurpfile b1 /tmp/$BRANCH2/coverage-summary.json /tmp/$BRANCH1/coverage-summary.json) $(jq "\$b1[0].total.$1.covered-.total.$1.covered" --slurpfile b1 /tmp/$BRANCH2/coverage-summary.json /tmp/$BRANCH1/coverage-summary.json)
}
echo "========================= Total coverage diff summary =========================="
diff "lines"
diff "statements"
diff "functions"
diff "branches"
echo "================================================================================"
# echo "Cleaning up…"
rm -rf /tmp/{$BRANCH1,$BRANCH2}
# echo "Switching back to $CURRENT_BRANCH"
git switch --quiet $CURRENT_BRANCH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment