Last active
January 16, 2016 05:57
-
-
Save chenyukang/8b968320d959a6c25ec3 to your computer and use it in GitHub Desktop.
gocover.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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