forked from t-yuki/gocover-cobertura
-
Notifications
You must be signed in to change notification settings - Fork 1
/
func.go
94 lines (85 loc) · 2.41 KB
/
func.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
91
92
93
94
// Imported from https://github.com/golang/go/blob/96745b980cfde139e8611772e2bc0c59a8e6cdf7/src/cmd/cover/func.go
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements the visitor that computes the (line, column)-(line-column) range for each function.
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
)
// Pkg describes a single package, compatible with the JSON output from 'go list'; see 'go help list'.
type Pkg struct {
ImportPath string
Dir string
Error *struct {
Err string
}
}
func findPkgs(profiles []*Profile) (map[string]*Pkg, error) {
// Run go list to find the location of every package we care about.
pkgs := make(map[string]*Pkg)
var list []string
for _, profile := range profiles {
if strings.HasPrefix(profile.FileName, ".") || filepath.IsAbs(profile.FileName) {
// Relative or absolute path.
continue
}
pkg := path.Dir(profile.FileName)
if _, ok := pkgs[pkg]; !ok {
pkgs[pkg] = nil
list = append(list, pkg)
}
}
if len(list) == 0 {
return pkgs, nil
}
// Note: usually run as "go tool cover" in which case $GOROOT is set,
// in which case runtime.GOROOT() does exactly what we want.
goTool := filepath.Join(runtime.GOROOT(), "bin/go")
cmd := exec.Command(goTool, append([]string{"list", "-e", "-json"}, list...)...)
var stderr bytes.Buffer
cmd.Stderr = &stderr
stdout, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("cannot run go list: %v\n%s", err, stderr.Bytes())
}
dec := json.NewDecoder(bytes.NewReader(stdout))
for {
var pkg Pkg
err := dec.Decode(&pkg)
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("decoding go list json: %v", err)
}
pkgs[pkg.ImportPath] = &pkg
}
return pkgs, nil
}
// findFile finds the location of the named file in GOROOT, GOPATH etc.
func findFile(pkgs map[string]*Pkg, file string) (string, error) {
if strings.HasPrefix(file, ".") || filepath.IsAbs(file) {
// Relative or absolute path.
return file, nil
}
pkg := pkgs[path.Dir(file)]
if pkg != nil {
if pkg.Dir != "" {
return filepath.Join(pkg.Dir, path.Base(file)), nil
}
if pkg.Error != nil {
return "", errors.New(pkg.Error.Err)
}
}
return "", fmt.Errorf("did not find package for %s in go list output", file)
}