-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.go
117 lines (95 loc) · 2.41 KB
/
graph.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
package main
import (
"os"
"path/filepath"
"github.com/pgavlin/dawn"
"github.com/pgavlin/dawn/label"
"github.com/spf13/cobra"
)
type node struct {
label label.Label
dependencies []*node
dependents []*node
}
func (n *node) depends(visited map[string]struct{}, acc *[]string) bool {
if _, ok := visited[n.label.String()]; ok {
return false
}
visited[n.label.String()] = struct{}{}
for _, d := range n.dependencies {
if d.depends(visited, acc) {
*acc = append(*acc, d.label.String())
}
}
return true
}
func (n *node) whatDepends(visited map[string]struct{}, acc *[]string) bool {
if _, ok := visited[n.label.String()]; ok {
return false
}
visited[n.label.String()] = struct{}{}
for _, d := range n.dependents {
if d.whatDepends(visited, acc) {
*acc = append(*acc, d.label.String())
}
}
return true
}
type graph map[string]*node
func (g graph) depends(t dawn.Target) ([]string, error) {
n := g[t.Label().String()]
var labels []string
n.depends(map[string]struct{}{}, &labels)
return labels, nil
}
func (g graph) whatDepends(t dawn.Target) ([]string, error) {
n := g[t.Label().String()]
var labels []string
n.whatDepends(map[string]struct{}{}, &labels)
return labels, nil
}
func (g graph) sources(t dawn.Target, root string) ([]string, error) {
n := g[t.Label().String()]
var paths []string
for _, d := range n.dependencies {
if dawn.IsSource(&d.label) {
components := label.Split(d.label.Package)[1:]
paths = append(paths, filepath.Join(root, filepath.Join(components...), d.label.Name))
}
}
return paths, nil
}
func (g graph) getOrAddNode(label *label.Label) *node {
if n, ok := g[label.String()]; ok {
return n
}
n := &node{label: *label}
g[label.String()] = n
return n
}
func buildGraph(proj *dawn.Project) graph {
g := graph{}
targets := proj.Targets()
for _, t := range targets {
n := g.getOrAddNode(t.Label())
for _, l := range t.Dependencies() {
dep := g.getOrAddNode(l)
n.dependencies = append(n.dependencies, dep)
dep.dependents = append(dep.dependents, n)
}
}
return g
}
var graphCmd = &cobra.Command{
Use: "graph",
Short: "Write the project's dependency graph to stdout in DOT format",
Args: cobra.NoArgs,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if err := work.loadProject(args, true, true); err != nil {
return err
}
work.renderer.Close()
return work.graph.dot(os.Stdout)
},
}