#!/bin/bash
# cover-go - Generate test coverage statistics for all Go packages.
workdir=.cover
mkdir -p $workdir
profile="$workdir/cover.out"
mode=count
args=$*
# Used for saving results when specifying --save-html
if [[ $args == *--save-html* ]]; then
for lastarg; do true; done
outfile=$lastarg
echo "Outfile: $outfile"
fi
generate_cover_data() {
rm -rf "$workdir"
mkdir "$workdir"
for pkg in "$@"; do
f="$workdir/$(echo $pkg | tr / -).cover"
go test -covermode="$mode" -coverprofile="$f" "$pkg"
ret=$?
if [ $ret -ne 0 ]; then
if [[ $args == *--save-html* ]]; then
echo '' > $outfile.svg
fi
exit $ret
fi
done
echo "mode: $mode" >"$profile"
grep -h -v "^mode:" "$workdir"/*.cover >>"$profile"
}
show_cover_report() {
go tool cover -${1}="$profile" -o $profile.${1}
go tool cover -${1}="$profile"
}
save_cover_report() {
coverage=`go tool cover -func=.cover/cover.out | tee $outfile.txt | grep -En "^total:" | grep -o '[0-9]*.[0-9]*%$'`
echo $?
go tool cover -${1}="$profile" -o $outfile.html
if [ "$coverage" == "100.0%" ]; then
echo '' > $outfile.svg
else
echo '' > $outfile.svg
fi
}
generate_cover_data $(go list ./...)
show_cover_report func
case "$1" in
"")
;;
--html)
show_cover_report html ;;
--save-html)
save_cover_report html ;;
*)
echo >&2 "error: invalid option: $1"; exit 1 ;;
esac