-
Notifications
You must be signed in to change notification settings - Fork 0
/
depgraph.go
111 lines (91 loc) · 2.07 KB
/
depgraph.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
package errgoengine
import "fmt"
type DepGraph map[string]*DepNode
type DepNode struct {
Graph DepGraph
Path string // path where the module/library/package is located
Dependencies map[string]string // mapped as map[label]depPath
}
func (node *DepNode) GetDependencies() []*DepNode {
deps := make([]*DepNode, len(node.Dependencies))
i := 0
for _, path := range node.Dependencies {
deps[i] = node.Graph[path]
i++
}
return deps
}
func (node *DepNode) Dependents() []*DepNode {
deps := []*DepNode{}
for _, cnode := range node.Graph {
if cnode.HasDependency(node.Path) {
deps = append(deps, cnode)
}
}
return deps
}
func (node *DepNode) DependentPaths() []string {
deps := node.Dependents()
depPaths := make([]string, len(deps))
for i, dep := range deps {
depPaths[i] = dep.Path
}
return depPaths
}
func (node *DepNode) HasDependency(path string) bool {
for _, depPath := range node.Dependencies {
if depPath == path {
return true
}
}
return false
}
func (node *DepNode) Detach(path string) error {
if !node.HasDependency(path) {
return fmt.Errorf(
"dependency '%s' not found in %s's dependencies",
path,
node.Path,
)
}
for k, v := range node.Dependencies {
if v == path {
delete(node.Dependencies, k)
node.Graph.Delete(path)
break
}
}
return nil
}
func (graph DepGraph) Add(path string, deps map[string]string) {
if node, ok := graph[path]; ok {
for label, depPath := range deps {
if !graph.Has(depPath) {
graph.Add(depPath, map[string]string{})
}
node.Dependencies[label] = depPath
}
} else {
graph[path] = &DepNode{
Graph: graph,
Path: path,
Dependencies: map[string]string{},
}
graph.Add(path, deps)
}
}
func (graph DepGraph) Has(path string) bool {
_, hasDep := graph[path]
return hasDep
}
func (graph DepGraph) Delete(path string) {
if node, ok := graph[path]; !ok {
return
} else if len(node.Dependents()) > 0 {
return
}
delete(graph, path)
}
func (graph DepGraph) Detach(path string, dep string) error {
return graph[path].Detach(dep)
}