-
Notifications
You must be signed in to change notification settings - Fork 34
/
handle_tree.go
158 lines (126 loc) · 2.43 KB
/
handle_tree.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package main
import (
"fmt"
"strings"
"github.com/reconquest/karma-go"
)
type Tree struct {
Package string
Nested []*Tree
}
func handleTree(withTests bool, usePath bool) error {
packages, err := listPackages()
if err != nil {
return karma.Format(
err,
"unable to list packages",
)
}
var inRoot bool
if len(packages) > 1 {
inRoot = true
for i, pkg := range packages {
if i == 0 {
continue
}
if !strings.HasPrefix(pkg, packages[0]) {
inRoot = false
break
}
}
}
var root *Tree
cache := map[string]*Tree{}
for i, pkg := range packages {
pkgTree := getTree(pkg, withTests, cache, usePath)
if !inRoot {
fmt.Println(formatTree(pkgTree))
} else {
if i == 0 {
root = pkgTree
} else {
root.Nested = append(root.Nested, pkgTree)
}
}
}
if inRoot {
fmt.Println(formatTree(root))
}
return nil
}
func formatTree(tree *Tree) karma.Reason {
var root karma.Reason
root = tree.Package
if len(tree.Nested) == 0 {
return root
}
var branches karma.Reason
for i, subtree := range tree.Nested {
var source karma.Reason
if i == 0 {
source = root
} else {
source = branches
}
branches = karma.Push(source, formatTree(subtree))
}
return branches
}
func getTree(
pkg string,
withTests bool,
cache map[string]*Tree,
usePath bool,
) *Tree {
if cached, ok := cache[pkg]; ok {
return cached
}
logger.Debugf("tree for %s", pkg)
tree := &Tree{
Package: pkg,
Nested: []*Tree{},
}
list, err := golist(pkg)
if err != nil {
logger.Fatal(err)
}
var imports []string
var importList []string
if usePath {
importList = list[0].Deps
} else {
importList = list[0].Imports
}
for _, importing := range importList {
imports = append(imports, removeVendorPrefix(importing))
}
imports = filterPackages(imports, 0)
logger.Debugf("%s -> %s", pkg, imports)
for _, imported := range imports {
if strings.HasPrefix(imported, pkg) {
continue
}
tree.Nested = append(
tree.Nested,
getTree(imported, withTests, cache, usePath),
)
}
if withTests {
testImports := filterPackages(list[0].TestImports, 0)
for _, imported := range testImports {
tree.Nested = append(
tree.Nested,
getTree(imported, withTests, cache, usePath),
)
}
}
cache[pkg] = tree
return tree
}
func removeVendorPrefix(path string) string {
index := strings.Index(path, "/vendor/")
if index > 0 {
return path[index+len("/vendor/"):]
}
return path
}