-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathport_deptree.py
executable file
·227 lines (190 loc) · 6.67 KB
/
port_deptree.py
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/python2
# Copyright (c) 2014, 2015 Mathias Laurin
# BSD 3-Clause License (http://opensource.org/licenses/BSD-3-Clause)
r"""Print all dependencies required to build a port as a graph.
Usage:
port_deptree.py [--min] PORTNAME [VARIANTS ...]
Example:
port_deptree.py irssi -perl | dot -Tpdf -oirssi.pdf
port_deptree.py --min $(port echo requested and outdated)\
| dot -Tpdf | open -fa Preview
"""
from __future__ import print_function
import sys
import subprocess
from itertools import product
from altgraph import Dot, Graph
__version__ = "0.9"
_stdout, sys.stdout = sys.stdout, sys.stderr
class NodeData(object):
__slots__ = ("type", "status")
def __init__(self, type):
self.type = type # in (root, vertex, leaf)
self.status = "missing" # in (installed, outdated, missing)
class EdgeData(object):
__slots__ = ("section",)
def __init__(self, section):
self.section = section
def get_deps(portname, variants):
"""Return `section, depname` dependents of `portname` with `variants`."""
process = ["port", "deps", portname]
process.extend(variants)
for line in subprocess.Popen(
process,
stdout=subprocess.PIPE,
universal_newlines=True,
).stdout.readlines():
section, sep, children = line.partition(":")
if not section.endswith("Dependencies"):
continue
for child in [child.strip() for child in children.split(",")]:
section = section.split()[0].lower()
child = child.strip()
if child:
yield section, child
def make_graph(graph, portname, variants):
"""Traverse dependency tree of `portname` with `variants`.
Args:
portname (str): The name of a port.
variants (list): The variants to apply to `portname`.
"""
def call(cmd):
return subprocess.Popen(
cmd.split(),
stdout=subprocess.PIPE,
universal_newlines=True,
).stdout.readlines()
installed = set(line.split()[0] for line in call("port echo installed"))
outdated = set(line.split()[0] for line in call("port echo outdated"))
visited = set(node for node in graph)
def traverse(parent):
"""Recursively traverse dependencies to `parent`."""
if parent in visited:
return
else:
visited.add(parent)
node_data = graph.node_data(parent)
if parent in outdated:
node_data.status = "outdated"
elif parent in installed:
node_data.status = "installed"
for section, child in get_deps(parent.strip('"'), variants):
if node_data.type != "root":
node_data.type = "vertex"
if child not in graph:
graph.add_node(child, NodeData("leaf"))
graph.add_edge(
parent, child, EdgeData(section), create_nodes=False
)
traverse(child)
graph.add_node(portname, NodeData("root"))
traverse(portname)
def reduce_graph(graph, root):
"""Keep only "missing" and "outdated" nodes and their parents."""
for node in graph.forw_bfs(root):
node_data = graph.node_data(node)
if node_data.type == "root" or node_data.status != "installed":
continue
children = set(graph.tail(edge) for edge in graph.out_edges(node))
if not set(("outdated", "missing")).intersection(
data.status
for data in (graph.node_data(child) for child in children)
):
parents = set(graph.head(edge) for edge in graph.inc_edges(node))
for parent, child in product(parents, children):
if not graph.edge_by_node(parent, child):
graph.add_edge(parent, child, EdgeData("virtual"))
graph.hide_node(node)
def make_dot(graph):
"""Convert the graph to a dot file.
Node and edge styles is obtained from the corresponding data.
Args:
graph (Graph.Graph): The graph.
Returns:
Dot.Dot: The dot file generator.
"""
dot = Dot.Dot(graph, graphtype="digraph")
dot.style(overlap=False, bgcolor="transparent")
for node in graph:
node_data = graph.node_data(node)
shape = "circle" if node_data.type == "vertex" else "doublecircle"
color, fillcolor = dict(
missing=("red", "moccasin"), outdated=("forestgreen", "lightblue")
).get(node_data.status, ("black", "white"))
dot.node_style(
node, shape=shape, style="filled", fillcolor=fillcolor, color=color
)
for edge, edge_data, head, tail in (
graph.describe_edge(edge) for edge in graph.edge_list()
):
section = edge_data.section
color = dict(
fetch="forestgreen",
extract="darkgreen",
build="blue",
runtime="red",
virtual="darkgray",
).get(section, "black")
style = dict(virtual="dashed").get(section, "solid")
dot.edge_style(
head,
tail,
label=section if section not in ("library", "virtual") else "",
style=style,
color=color,
fontcolor=color,
)
return dot
def make_stats(graph):
"""Return the stats for `graph`."""
stats = dict(
missing=0, installed=0, outdated=0, total=graph.number_of_nodes()
)
for node in graph:
node_data = graph.node_data(node)
stats[node_data.status] += 1
return stats
if __name__ == "__main__":
graph = Graph.Graph()
reduce = False
commandline = {}
try:
if not sys.argv[1:]:
raise RuntimeError
for arg in sys.argv[1:]:
if arg.startswith("@"):
continue
elif arg.startswith("--min"):
reduce = True
elif not (arg.startswith("+") or arg.startswith("-")):
portname = arg
commandline[portname] = []
else:
commandline[portname].append(arg)
except:
print(__doc__, file=sys.stderr)
exit(1)
for portname, variants in commandline.items():
print(
"Calculating dependencies for",
portname,
*variants,
file=sys.stderr
)
make_graph(graph, portname, variants)
stats = make_stats(graph)
if reduce:
for portname in commandline:
reduce_graph(graph, portname)
print(
"Total:",
stats["total"],
"(%i" % stats["outdated"],
"upgrades,",
stats["missing"],
"new)",
file=sys.stderr,
)
for line in make_dot(graph).iterdot():
print(line, file=_stdout)
_stdout.flush()