-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgopackages.go
85 lines (73 loc) · 1.98 KB
/
gopackages.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
package gopackages
// ke: {"package": {"complete": true}}
import (
"fmt"
"os/exec"
"path/filepath"
"strings"
"os"
"github.com/dave/kerr"
)
func GetDirFromPackage(environ []string, gopath string, packagePath string) (string, error) {
exe := exec.Command("go", "list", "-f", "{{.Dir}}", packagePath)
exe.Env = environ
out, err := exe.CombinedOutput()
if err == nil {
return strings.TrimSpace(string(out)), nil
}
dir, err := GetDirFromEmptyPackage(gopath, packagePath)
if err != nil {
return "", kerr.Wrap("GXTUPMHETV", err)
}
return dir, nil
}
func GetDirFromEmptyPackage(gopathEnv string, path string) (string, error) {
gopaths := filepath.SplitList(gopathEnv)
for _, gopath := range gopaths {
dir := filepath.Join(gopath, "src", path)
if s, err := os.Stat(dir); err == nil && s.IsDir() {
return dir, nil
}
}
return "", NotFoundError{Struct: kerr.New("SUTCWEVRXS", "%s not found", path).(kerr.Struct)}
}
type NotFoundError struct {
kerr.Struct
}
func GetPackageFromDir(gopath string, dir string) (string, error) {
gopaths := filepath.SplitList(gopath)
var savedError error
for _, gopath := range gopaths {
if strings.HasPrefix(dir, gopath) {
gosrc := fmt.Sprintf("%s/src", gopath)
relpath, err := filepath.Rel(gosrc, dir)
if err != nil {
// notest
// I don't *think* we can trigger this error if dir starts with gopath
savedError = err
continue
}
if relpath == "" {
// notest
// I don't *think* we can trigger this either
continue
}
// Remember we're returning a package path which uses forward slashes even on windows
return filepath.ToSlash(relpath), nil
}
}
if savedError != nil {
// notest
return "", savedError
}
return "", kerr.New("CXOETFPTGM", "Package not found for %s", dir)
}
func GetCurrentGopath(gopath string, currentDir string) string {
gopaths := filepath.SplitList(gopath)
for _, gopath := range gopaths {
if strings.HasPrefix(currentDir, gopath) {
return gopath
}
}
return gopaths[0]
}