/
pkgs.go
100 lines (85 loc) · 2.38 KB
/
pkgs.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
95
96
97
98
99
100
package pkgs
import (
"strings"
"golang.org/x/tools/go/packages"
)
const pkgMain = "main"
const testSuffix = ".test"
// Package is a type alias so other packages can save the import
type Package = packages.Package
// PkgType is an enum with values like 'Tool' and 'HalfDB'
type PkgType int
const (
PkgTypeStandard PkgType = iota
PkgTypeHalfTool
PkgTypeTool
PkgTypeHalfDB
PkgTypeDB
PkgTypeGod
)
type PackageInfo struct {
UniqName string
Size int
Type PkgType
Deps []*PackageInfo
Pkg *Package
}
// RelativePackageName return the package name relative towards the given root package.
// relPkg can be `/`, `main` or a path like `pkg/x/mytool`.
// strictRelPkg can be `/`, a path like `pkg/x/mytool` or empty.
func RelativePackageName(pkg *Package, rootPkg string) (relPkg, strictRelPkg string) {
if !strings.HasPrefix(pkg.PkgPath, rootPkg) {
return pkg.PkgPath, ""
}
relPkg = pkg.PkgPath[len(rootPkg):]
if pkg.Name == pkgMain {
return pkgMain, strictRelativePkg(relPkg)
}
return strictRelativePkg(relPkg), ""
}
func strictRelativePkg(rawRelPkg string) string {
if rawRelPkg == "" {
return "/"
} else if rawRelPkg[0] == '/' && len(rawRelPkg) > 1 {
return removeDotTest(rawRelPkg[1:])
}
return removeDotTest(rawRelPkg)
}
func removeDotTest(pkg string) string {
if strings.HasSuffix(pkg, testSuffix) {
return pkg[:len(pkg)-len(testSuffix)]
}
return pkg
}
// UniquePackageName returns strictRelPkg if it isn't empty and relPkg otherwise.
func UniquePackageName(relPkg, strictRelPkg string) string {
if strictRelPkg != "" {
return strictRelPkg
}
return relPkg
}
// UniquePackages makes the given list of packages unique.
func UniquePackages(pkgs []*Package) map[string]*PackageInfo {
uniqPkgs := make(map[string]*PackageInfo, len(pkgs))
for _, pkg := range pkgs {
relPkg, strictRelPkg := RelativePackageName(pkg, "")
uniqName := UniquePackageName(relPkg, strictRelPkg)
if _, ok := uniqPkgs[uniqName]; !ok {
uniqPkg := &PackageInfo{
UniqName: uniqName,
Pkg: pkg,
}
uniqPkgs[uniqName] = uniqPkg
}
}
return uniqPkgs
}
// IsTestPackage returns true if the given package is a test package and false
// otherwise.
func IsTestPackage(pkg *Package) bool {
result := strings.HasSuffix(pkg.PkgPath, "_test") ||
strings.HasSuffix(pkg.PkgPath, ".test") ||
strings.HasSuffix(pkg.ID, ".test]") ||
strings.HasSuffix(pkg.ID, ".test")
return result
}