cover-go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/bin/bash
  2. # cover-go - Generate test coverage statistics for all Go packages.
  3. workdir=.cover
  4. mkdir -p $workdir
  5. profile="$workdir/cover.out"
  6. mode=count
  7. args=$*
  8. # Used for saving results when specifying --save-html
  9. if [[ $args == *--save-html* ]]; then
  10. for lastarg; do true; done
  11. outfile=$lastarg
  12. echo "Outfile: $outfile"
  13. fi
  14. generate_cover_data() {
  15. rm -rf "$workdir"
  16. mkdir "$workdir"
  17. for pkg in "$@"; do
  18. f="$workdir/$(echo $pkg | tr / -).cover"
  19. go test -covermode="$mode" -coverprofile="$f" "$pkg"
  20. ret=$?
  21. if [ $ret -ne 0 ]; then
  22. if [[ $args == *--save-html* ]]; then
  23. echo '<svg width="88" height="20" xmlns="http://www.w3.org/2000/svg"><g shape-rendering="crispEdges"><path fill="#555" d="M0 0h41v20H0z"/><path fill="#fc1" d="M41 0h40v20H41z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"><text x="20.5" y="14">tests</text><text x="60" y="14">fail</text></g></svg>' > $outfile.svg
  24. fi
  25. exit $ret
  26. fi
  27. done
  28. echo "mode: $mode" >"$profile"
  29. grep -h -v "^mode:" "$workdir"/*.cover >>"$profile"
  30. }
  31. show_cover_report() {
  32. go tool cover -${1}="$profile" -o $profile.${1}
  33. go tool cover -${1}="$profile"
  34. }
  35. save_cover_report() {
  36. coverage=`go tool cover -func=.cover/cover.out | tee $outfile.txt | grep -En "^total:" | grep -o '[0-9]*.[0-9]*%$'`
  37. echo $?
  38. go tool cover -${1}="$profile" -o $outfile.html
  39. if [ "$coverage" == "100.0%" ]; then
  40. echo '<svg width="110" height="20" xmlns="http://www.w3.org/2000/svg"><g shape-rendering="crispEdges"><path fill="#555" d="M0 0h61v20H0z"/><path fill="#4c1" d="M61 0h50v20H61z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"><text x="30.5" y="14">coverage</text><text x="85" y="14">'$coverage'</text></g></svg>' > $outfile.svg
  41. else
  42. echo '<svg width="110" height="20" xmlns="http://www.w3.org/2000/svg"><g shape-rendering="crispEdges"><path fill="#555" d="M0 0h61v20H0z"/><path fill="#fc1" d="M61 0h50v20H61z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"><text x="30.5" y="14">coverage</text><text x="85" y="14">'$coverage'</text></g></svg>' > $outfile.svg
  43. fi
  44. }
  45. generate_cover_data $(go list ./...)
  46. show_cover_report func
  47. case "$1" in
  48. "")
  49. ;;
  50. --html)
  51. show_cover_report html ;;
  52. --save-html)
  53. save_cover_report html ;;
  54. *)
  55. echo >&2 "error: invalid option: $1"; exit 1 ;;
  56. esac