cliverage/main.go

117 lines
2.7 KiB
Go
Raw Permalink Normal View History

2019-11-23 01:13:54 +00:00
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"path"
"strings"
"git.xdrm.io/go/cliverage/coverage"
)
func main() {
var codepath string
var coverfile string
var filepath string
var showUsage bool
flag.StringVar(&codepath, "d", "", "path to where lives your code")
flag.StringVar(&coverfile, "c", "", "path to the coverage file")
flag.StringVar(&filepath, "f", ".", "path to the file to print relative to -d option")
flag.BoolVar(&showUsage, "h", false, "")
flag.Usage = usage
flag.Parse()
// 1. show usage
if showUsage {
flag.Usage()
os.Exit(0)
}
// 2. missing required arguments
if len(codepath) < 1 || len(coverfile) < 1 {
fmt.Printf("%s missing arguments.\n\n", warning("/!\\"))
fmt.Printf("run -h to show usage.\n")
os.Exit(1)
}
// 3. check codepath
if info, err := os.Stat(codepath); true {
if err != nil && os.IsNotExist(err) {
fmt.Printf("%s codepath does not exist.\n\n", warning("/!\\"))
os.Exit(1)
}
if !info.IsDir() {
fmt.Printf("%s codepath is not a directory.\n\n", warning("/!\\"))
os.Exit(1)
}
if err != nil {
fmt.Printf("%s invalid codepath: %s.\n\n", warning("/!\\"), err)
os.Exit(1)
}
}
// 4. check coverfile
if info, err := os.Stat(coverfile); true {
if err != nil && os.IsNotExist(err) {
fmt.Printf("%s coverfile does not exist.\n\n", warning("/!\\"))
os.Exit(1)
}
if info.IsDir() {
fmt.Printf("%s coverfile is not a file.\n\n", warning("/!\\"))
os.Exit(1)
}
if err != nil {
fmt.Printf("%s invalid coverfile: %s.\n\n", warning("/!\\"), err)
os.Exit(1)
}
}
// 5. extract package path
os.Chdir(codepath)
var getGoPkgPath = exec.Command("go", "list", ".")
pkgPath, err := getGoPkgPath.Output()
if err != nil {
fmt.Printf("%s cannot get go package path: %s.\n\n", warning("/!\\"), err)
os.Exit(1)
}
// 6. parse coverfile
fdCoverfile, err := os.OpenFile(coverfile, os.O_RDONLY, 0755)
if err != nil {
fmt.Printf("%s cannot open coverfile: %s.\n\n", warning("/!\\"), err)
os.Exit(1)
}
defer fdCoverfile.Close()
parsedCoverage, err := coverage.Parse(fdCoverfile, strings.Trim(string(pkgPath), " \t\r\n"))
if err != nil {
fmt.Printf("%s error reading coverfile: %s.\n\n", warning("/!\\"), err)
os.Exit(1)
}
// 7. iterate over files
coveredFiles := parsedCoverage.GetFile(filepath)
for fname, coveredChunks := range coveredFiles.Files {
path := path.Join(codepath, fname)
fmt.Printf("----- %s -----\n", fname)
fdFile, err := os.OpenFile(path, os.O_RDONLY, 0755)
if err != nil {
fmt.Printf("%s cannot open file '%s': %s.\n\n", warning("/!\\"), path, err)
continue
}
defer fdFile.Close()
printCoverage(fdFile, os.Stdout, coveredChunks)
fmt.Printf("\n\n")
}
os.Exit(0)
}