Skip to content

Instantly share code, notes, and snippets.

@BorisKozo
Last active June 21, 2017 09:39
Show Gist options
  • Save BorisKozo/0a72fc2d18f5c6f6c8ef706509526fef to your computer and use it in GitHub Desktop.
Save BorisKozo/0a72fc2d18f5c6f6c8ef706509526fef to your computer and use it in GitHub Desktop.
A utility script that runs Go (Golang) coverage report on all the packages within a directory excluding vendor. Note that each package will only show coverage of itself when run (no cross package coverage)
package main
import (
"fmt"
"path/filepath"
"os"
"log"
"strings"
"os/exec"
"bufio"
)
func main() {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
mode := "atomic"
srcpath := filepath.ToSlash(os.Getenv("GOPATH") + "/src/")
vendorPath := filepath.ToSlash(dir + `\vendor`)
tempCoverFile := filepath.ToSlash(dir + `\cover_tmp.out`)
finalCoverFile := filepath.ToSlash(dir + `\cover.out`)
fmt.Println(tempCoverFile)
packages := make(map[string]bool)
visitFile := func(path string, info os.FileInfo, err error) error {
slashPath := filepath.ToSlash(path)
if strings.HasPrefix(slashPath, vendorPath) {
return nil
}
if strings.HasSuffix(info.Name(), "_test.go") {
packages[filepath.ToSlash(filepath.Dir(slashPath))] = true
}
return nil
}
fmt.Println("Collecting test files from " + dir)
filepath.Walk(dir, visitFile)
coverFile, err := os.Create(finalCoverFile)
check(err)
defer coverFile.Close()
coverFile.WriteString(fmt.Sprintf("mode: %v\n", mode))
for pkg, _ := range packages {
relativePackage := strings.TrimPrefix(pkg, srcpath)
fmt.Println("Executing tests for ", relativePackage)
commandString := []string{
"test", "-covermode", mode, "-coverprofile", tempCoverFile, relativePackage,
}
_, err := exec.Command("go", commandString...).Output()
if err != nil {
fmt.Println(err)
if exiterr, ok := err.(*exec.ExitError); ok {
fmt.Println(string(exiterr.Stderr))
}
return
}
file, err := os.Open(tempCoverFile)
check(err)
defer file.Close()
scanner := bufio.NewScanner(file)
header := true
for scanner.Scan() {
if !header {
coverFile.WriteString(scanner.Text() + "\n")
}
header = false
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
coverFile.Sync()
_, err = exec.Command("go", "tool", "cover", "-html="+finalCoverFile).Output()
if err != nil {
fmt.Println(err)
if exiterr, ok := err.(*exec.ExitError); ok {
fmt.Println(string(exiterr.Stderr))
}
return
}
err = os.Remove(tempCoverFile)
fmt.Println(err)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment