-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
90 lines (79 loc) · 2.27 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"flag"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
const (
covTmpFile = "profile.cov.tmp"
coverHeader = `mode: count
`
)
var (
dir string
ignore string
outputFilename string
fileIgnore *regexp.Regexp
)
func init() {
flag.StringVar(&dir, "dir", ".", "Directory to start recursing for tests")
flag.StringVar(&ignore, "ignore", `(vendor|\.\w+)`, "RegEx that ignores files and folders. Default ignores hidden folders and vendor folder.")
flag.StringVar(&outputFilename, "output", "profile.cov", "Filename for the output coverage file.")
flag.Parse()
fileIgnore = regexp.MustCompile(ignore)
}
func main() {
filepath.Walk(dir, performCoverage)
createOutputFile()
filepath.Walk(dir, collateCoverage)
filepath.Walk(dir, deleteFiles)
}
// A filepath.Walk function to use `go test` to generate all the coverage reports
func performCoverage(path string, info os.FileInfo, err error) error {
if err == nil && info.IsDir() && hasGoFile(path) && !fileIgnore.MatchString(path) {
path = "./" + path
log.Println(path)
exec.Command("go", "test", "-covermode=count", "-coverprofile="+path+"/"+covTmpFile, path).Output()
}
return nil
}
// Creates the final output file
func createOutputFile() {
err := ioutil.WriteFile(outputFilename, []byte(coverHeader), 0644)
check(err)
}
// A filepath.Walk function to collate the coverage reports together and saves into output file
func collateCoverage(path string, info os.FileInfo, err error) error {
if err == nil && !info.IsDir() && strings.Contains(path, covTmpFile) {
contentsB, err := ioutil.ReadFile(path)
check(err)
contents := strings.Replace(string(contentsB), "mode: count\n", "", 1)
f, err := os.OpenFile(outputFilename, os.O_APPEND|os.O_WRONLY, 0600)
check(err)
_, err = f.WriteString(contents)
check(err)
f.Close()
}
return nil
}
// A filepath.Walk function to delete all the temporary files
func deleteFiles(path string, info os.FileInfo, err error) error {
if err == nil && !info.IsDir() && strings.Contains(path, covTmpFile) {
os.Remove(path)
}
return nil
}
func hasGoFile(path string) bool {
matches, _ := filepath.Glob(path + "/*.go")
return (matches != nil && len(matches) > 0)
}
func check(err error) {
if err != nil {
panic(err)
}
}