forked from cugu/gocap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
108 lines (88 loc) · 2.01 KB
/
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
package main
import (
"fmt"
"sort"
"strings"
)
type Tree struct {
root string
nodes map[string]*Node
}
type Node struct {
capabilities *Set
imports *Set
}
func NewTree(start string) (*Tree, error) {
t := &Tree{nodes: map[string]*Node{}}
rootPackagePath, err := parsePackagePath(start)
if err != nil {
return nil, err
}
if err := t.addPackagesRecursive(rootPackagePath); err != nil {
return nil, err
}
t.root = rootPackagePath
return t, nil
}
func (t *Tree) addPackagesRecursive(pkgPath string) (err error) {
if _, ok := t.nodes[pkgPath]; ok {
return nil
}
if pkgPath == "C" {
t.addNote("C", nil, []string{"syscall"})
return nil
}
imports, err := parsePackage(pkgPath)
if err != nil {
return err
}
var external []string
var standard []string
for _, im := range imports {
if !isStandard(im) {
if err := t.addPackagesRecursive(im); err != nil {
return err
}
external = append(external, im)
} else {
standard = append(standard, im)
}
}
t.addNote(pkgPath, external, toCapabilities(standard))
return nil
}
func isStandard(name string) bool {
_, ok := standardPackages[name]
return ok
}
func (t *Tree) addNote(name string, imports, capabilities []string) {
t.nodes[name] = &Node{
capabilities: NewSet(capabilities...),
imports: NewSet(imports...),
}
}
func (t *Tree) GenerateFile() string {
sb := strings.Builder{}
sb.WriteString(goCapLine(t.root, t.nodes[t.root].capabilities.Values()))
sb.WriteString("\n")
for _, name := range sortedKeys(t.nodes) {
if name != t.root {
values := t.nodes[name].capabilities.Values()
if len(values) > 0 {
sb.WriteString(goCapLine(name, t.nodes[name].capabilities.Values()))
}
}
}
return sb.String()
}
func sortedKeys(m map[string]*Node) (keys []string) {
for key := range m {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func goCapLine(name string, capabilities []string) string {
sort.Strings(capabilities)
return fmt.Sprintf("%s (%s)\n", name, strings.Join(capabilities, ", "))
}