Skip to content

Instantly share code, notes, and snippets.

@KennFatt
Created November 24, 2023 12:45
Show Gist options
  • Save KennFatt/753e33a9c55e8d64b83642484c914e79 to your computer and use it in GitHub Desktop.
Save KennFatt/753e33a9c55e8d64b83642484c914e79 to your computer and use it in GitHub Desktop.
A bash function to run golang test coverage for specific module in your project and open the report in your web browser.
function go-gen-cover() {
# Check dependencies
if ! type xargs &>/dev/null; then
echo "error: 'xargs' command is missing"
return 1
fi
if ! type go &>/dev/null; then
echo "error: 'go' command is missing"
return 1
fi
module_name=$1
if [ -z "$module_name" ]; then
echo "usage: $0 <module_name_pattern>"
return 1
fi
# temporary output
tDir="/tmp/go-gen-cover"
rm -rf $tDir
mkdir -p $tDir
t="$tDir/go-cover.$$.tmp"
# run the test and generate the coverage > $t.html
go list ./... | grep $module_name | xargs go test -coverprofile=$t && go tool cover -html=$t -o $t.html
# remove the out file
unlink $t
# open in respective application (e.g. web browser)
if type open &>/dev/null; then
open $t.html
elif type xdg-open &>/dev/null; then
xdg-open $t.html
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment