Skip to content

Instantly share code, notes, and snippets.

@chenyukang
Last active January 16, 2016 05:57
Show Gist options
  • Save chenyukang/8b968320d959a6c25ec3 to your computer and use it in GitHub Desktop.
Save chenyukang/8b968320d959a6c25ec3 to your computer and use it in GitHub Desktop.
gocover.go
package main
import (
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
)
func parse(path string) *ast.File {
content, _ := ioutil.ReadFile(path)
// Create the AST by parsing src.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", content, 0)
if err != nil {
return nil
}
return f
}
func goPath(path string) string {
for {
cur := filepath.Base(path)
if cur == "src" {
abs, err := filepath.Abs(filepath.Dir(path))
if err != nil {
return ""
}
return abs
}
if filepath.Dir(path) == path {
break
}
path = filepath.Dir(path)
}
return ""
}
func runCmd(cmd string, gopath string) {
args := strings.SplitN(cmd, " ", -1)
fmt.Println(args)
if len(args) < 1 {
return
}
app := args[0]
args = args[1:]
proc := exec.Command(app, args...)
proc.Env = []string{"GOPATH=" + gopath}
proc.Stdout = os.Stdout
proc.Stderr = os.Stderr
if err := proc.Run(); err != nil {
fmt.Println(err)
os.Exit(2)
}
}
func main() {
flag.Parse()
if flag.NArg() != 1 {
return
}
file := flag.Arg(0)
if _, err := os.Stat(file); os.IsNotExist(err) {
fmt.Println(err)
return
}
gopath := goPath(file)
ast := parse(file)
cmd := fmt.Sprintf(
"go test %s -coverprofile=/tmp/cover.out",
ast.Name.Name)
runCmd(cmd, gopath)
runCmd("go tool cover -func=/tmp/cover.out",
gopath)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment