]> rtime.felk.cvut.cz Git - coffee/buildroot.git/blob - support/scripts/graph-depends
db3041b32e8ed5ac4fdec41dcf4c234853c806ca
[coffee/buildroot.git] / support / scripts / graph-depends
1 #!/usr/bin/env python
2
3 # Usage (the graphviz package must be installed in your distribution)
4 #  ./support/scripts/graph-depends [-p package-name] > test.dot
5 #  dot -Tpdf test.dot -o test.pdf
6 #
7 # With no arguments, graph-depends will draw a complete graph of
8 # dependencies for the current configuration.
9 # If '-p <package-name>' is specified, graph-depends will draw a graph
10 # of dependencies for the given package name.
11 # If '-d <depth>' is specified, graph-depends will limit the depth of
12 # the dependency graph to 'depth' levels.
13 #
14 # Limitations
15 #
16 #  * Some packages have dependencies that depend on the Buildroot
17 #    configuration. For example, many packages have a dependency on
18 #    openssl if openssl has been enabled. This tool will graph the
19 #    dependencies as they are with the current Buildroot
20 #    configuration.
21 #
22 # Copyright (C) 2010-2013 Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
23
24 import sys
25 import subprocess
26 import argparse
27 from fnmatch import fnmatch
28
29 import brpkgutil
30
31 # Modes of operation:
32 MODE_FULL = 1   # draw full dependency graph for all selected packages
33 MODE_PKG  = 2   # draw dependency graph for a given package
34 mode = 0
35
36 # Limit drawing the dependency graph to this depth. 0 means 'no limit'.
37 max_depth = 0
38
39 # Whether to draw the transitive dependencies
40 transitive = True
41
42 parser = argparse.ArgumentParser(description="Graph packages dependencies")
43 parser.add_argument("--check-only", "-C", dest="check_only", action="store_true", default=False,
44                     help="Only do the dependency checks (circular deps...)")
45 parser.add_argument("--outfile", "-o", metavar="OUT_FILE", dest="outfile",
46                     help="File in which to generate the dot representation")
47 parser.add_argument("--package", '-p', metavar="PACKAGE",
48                     help="Graph the dependencies of PACKAGE")
49 parser.add_argument("--depth", '-d', metavar="DEPTH", dest="depth", type=int, default=0,
50                     help="Limit the dependency graph to DEPTH levels; 0 means no limit.")
51 parser.add_argument("--stop-on", "-s", metavar="PACKAGE", dest="stop_list", action="append",
52                     help="Do not graph past this package (can be given multiple times)." \
53                        + " Can be a package name or a glob, " \
54                        + " 'virtual' to stop on virtual packages, or " \
55                        + "'host' to stop on host packages.")
56 parser.add_argument("--exclude", "-x", metavar="PACKAGE", dest="exclude_list", action="append",
57                     help="Like --stop-on, but do not add PACKAGE to the graph.")
58 parser.add_argument("--colours", "-c", metavar="COLOR_LIST", dest="colours",
59                     default="lightblue,grey,gainsboro",
60                     help="Comma-separated list of the three colours to use" \
61                        + " to draw the top-level package, the target" \
62                        + " packages, and the host packages, in this order." \
63                        + " Defaults to: 'lightblue,grey,gainsboro'")
64 parser.add_argument("--transitive", dest="transitive", action='store_true',
65                     default=False)
66 parser.add_argument("--no-transitive", dest="transitive", action='store_false',
67                     help="Draw (do not draw) transitive dependencies")
68 parser.add_argument("--direct", dest="direct", action='store_true', default=True,
69                     help="Draw direct dependencies (the default)")
70 parser.add_argument("--reverse", dest="direct", action='store_false',
71                     help="Draw reverse dependencies")
72 args = parser.parse_args()
73
74 check_only = args.check_only
75
76 if args.outfile is None:
77     outfile = sys.stdout
78 else:
79     if check_only:
80         sys.stderr.write("don't specify outfile and check-only at the same time\n")
81         sys.exit(1)
82     outfile = open(args.outfile, "w")
83
84 if args.package is None:
85     mode = MODE_FULL
86 else:
87     mode = MODE_PKG
88     rootpkg = args.package
89
90 max_depth = args.depth
91
92 if args.stop_list is None:
93     stop_list = []
94 else:
95     stop_list = args.stop_list
96
97 if args.exclude_list is None:
98     exclude_list = []
99 else:
100     exclude_list = args.exclude_list
101
102 transitive = args.transitive
103
104 if args.direct:
105     get_depends_func = brpkgutil.get_depends
106     arrow_dir = "forward"
107 else:
108     if mode == MODE_FULL:
109         sys.stderr.write("--reverse needs a package\n")
110         sys.exit(1)
111     get_depends_func = brpkgutil.get_rdepends
112     arrow_dir = "back"
113
114 # Get the colours: we need exactly three colours,
115 # so no need not split more than 4
116 # We'll let 'dot' validate the colours...
117 colours = args.colours.split(',',4)
118 if len(colours) != 3:
119     sys.stderr.write("Error: incorrect colour list '%s'\n" % args.colours)
120     sys.exit(1)
121 root_colour = colours[0]
122 target_colour = colours[1]
123 host_colour = colours[2]
124
125 allpkgs = []
126
127 # Execute the "make show-targets" command to get the list of the main
128 # Buildroot PACKAGES and return it formatted as a Python list. This
129 # list is used as the starting point for full dependency graphs
130 def get_targets():
131     sys.stderr.write("Getting targets\n")
132     cmd = ["make", "-s", "--no-print-directory", "show-targets"]
133     p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
134     output = p.communicate()[0].strip()
135     if p.returncode != 0:
136         return None
137     if output == '':
138         return []
139     return output.split(' ')
140
141 # Recursive function that builds the tree of dependencies for a given
142 # list of packages. The dependencies are built in a list called
143 # 'dependencies', which contains tuples of the form (pkg1 ->
144 # pkg2_on_which_pkg1_depends, pkg3 -> pkg4_on_which_pkg3_depends) and
145 # the function finally returns this list.
146 def get_all_depends(pkgs):
147     dependencies = []
148
149     # Filter the packages for which we already have the dependencies
150     filtered_pkgs = []
151     for pkg in pkgs:
152         if pkg in allpkgs:
153             continue
154         filtered_pkgs.append(pkg)
155         allpkgs.append(pkg)
156
157     if len(filtered_pkgs) == 0:
158         return []
159
160     depends = get_depends_func(filtered_pkgs)
161
162     deps = set()
163     for pkg in filtered_pkgs:
164         pkg_deps = depends[pkg]
165
166         # This package has no dependency.
167         if pkg_deps == []:
168             continue
169
170         # Add dependencies to the list of dependencies
171         for dep in pkg_deps:
172             dependencies.append((pkg, dep))
173             deps.add(dep)
174
175     if len(deps) != 0:
176         newdeps = get_all_depends(deps)
177         if newdeps is not None:
178             dependencies += newdeps
179
180     return dependencies
181
182 # The Graphviz "dot" utility doesn't like dashes in node names. So for
183 # node names, we strip all dashes.
184 def pkg_node_name(pkg):
185     return pkg.replace("-","")
186
187 TARGET_EXCEPTIONS = [
188     "target-finalize",
189     "target-post-image",
190 ]
191
192 # In full mode, start with the result of get_targets() to get the main
193 # targets and then use get_all_depends() for all targets
194 if mode == MODE_FULL:
195     targets = get_targets()
196     dependencies = []
197     allpkgs.append('all')
198     filtered_targets = []
199     for tg in targets:
200         # Skip uninteresting targets
201         if tg in TARGET_EXCEPTIONS:
202             continue
203         dependencies.append(('all', tg))
204         filtered_targets.append(tg)
205     deps = get_all_depends(filtered_targets)
206     if deps is not None:
207         dependencies += deps
208     rootpkg = 'all'
209
210 # In pkg mode, start directly with get_all_depends() on the requested
211 # package
212 elif mode == MODE_PKG:
213     dependencies = get_all_depends([rootpkg])
214
215 # Make the dependencies a dictionnary { 'pkg':[dep1, dep2, ...] }
216 dict_deps = {}
217 for dep in dependencies:
218     if dep[0] not in dict_deps:
219         dict_deps[dep[0]] = []
220     dict_deps[dep[0]].append(dep[1])
221
222 # Basic cache for the results of the is_dep() function, in order to
223 # optimize the execution time. The cache is a dict of dict of boolean
224 # values. The key to the primary dict is "pkg", and the key of the
225 # sub-dicts is "pkg2".
226 is_dep_cache = {}
227
228 def is_dep_cache_insert(pkg, pkg2, val):
229     try:
230         is_dep_cache[pkg].update({pkg2: val})
231     except KeyError:
232         is_dep_cache[pkg] = {pkg2: val}
233
234 # Retrieves from the cache whether pkg2 is a transitive dependency
235 # of pkg.
236 # Note: raises a KeyError exception if the dependency is not known.
237 def is_dep_cache_lookup(pkg, pkg2):
238     return is_dep_cache[pkg][pkg2]
239
240 # This function return True if pkg is a dependency (direct or
241 # transitive) of pkg2, dependencies being listed in the deps
242 # dictionary. Returns False otherwise.
243 # This is the un-cached version.
244 def is_dep_uncached(pkg,pkg2,deps):
245     try:
246         for p in deps[pkg2]:
247             if pkg == p:
248                 return True
249             if is_dep(pkg,p,deps):
250                 return True
251     except KeyError:
252         pass
253     return False
254
255 # See is_dep_uncached() above; this is the cached version.
256 def is_dep(pkg,pkg2,deps):
257     try:
258         return is_dep_cache_lookup(pkg, pkg2)
259     except KeyError:
260         val = is_dep_uncached(pkg, pkg2, deps)
261         is_dep_cache_insert(pkg, pkg2, val)
262         return val
263
264 # This function eliminates transitive dependencies; for example, given
265 # these dependency chain: A->{B,C} and B->{C}, the A->{C} dependency is
266 # already covered by B->{C}, so C is a transitive dependency of A, via B.
267 # The functions does:
268 #   - for each dependency d[i] of the package pkg
269 #     - if d[i] is a dependency of any of the other dependencies d[j]
270 #       - do not keep d[i]
271 #     - otherwise keep d[i]
272 def remove_transitive_deps(pkg,deps):
273     d = deps[pkg]
274     new_d = []
275     for i in range(len(d)):
276         keep_me = True
277         for j in range(len(d)):
278             if j==i:
279                 continue
280             if is_dep(d[i],d[j],deps):
281                 keep_me = False
282         if keep_me:
283             new_d.append(d[i])
284     return new_d
285
286 # This function removes the dependency on some 'mandatory' package, like the
287 # 'toolchain' package, or the 'skeleton' package
288 def remove_mandatory_deps(pkg,deps):
289     return [p for p in deps[pkg] if p not in ['toolchain', 'skeleton']]
290
291 # This function will check that there is no loop in the dependency chain
292 # As a side effect, it builds up the dependency cache.
293 def check_circular_deps(deps):
294     def recurse(pkg):
295         if not pkg in list(deps.keys()):
296             return
297         if pkg in not_loop:
298             return
299         not_loop.append(pkg)
300         chain.append(pkg)
301         for p in deps[pkg]:
302             if p in chain:
303                 sys.stderr.write("\nRecursion detected for  : %s\n" % (p))
304                 while True:
305                     _p = chain.pop()
306                     sys.stderr.write("which is a dependency of: %s\n" % (_p))
307                     if p == _p:
308                         sys.exit(1)
309             recurse(p)
310         chain.pop()
311
312     not_loop = []
313     chain = []
314     for pkg in list(deps.keys()):
315         recurse(pkg)
316
317 # This functions trims down the dependency list of all packages.
318 # It applies in sequence all the dependency-elimination methods.
319 def remove_extra_deps(deps):
320     for pkg in list(deps.keys()):
321         if not pkg == 'all':
322             deps[pkg] = remove_mandatory_deps(pkg,deps)
323     for pkg in list(deps.keys()):
324         if not transitive or pkg == 'all':
325             deps[pkg] = remove_transitive_deps(pkg,deps)
326     return deps
327
328 check_circular_deps(dict_deps)
329 if check_only:
330     sys.exit(0)
331
332 dict_deps = remove_extra_deps(dict_deps)
333 dict_version = brpkgutil.get_version([pkg for pkg in allpkgs
334                                 if pkg != "all" and not pkg.startswith("root")])
335
336 # Print the attributes of a node: label and fill-color
337 def print_attrs(pkg):
338     name = pkg_node_name(pkg)
339     if pkg == 'all':
340         label = 'ALL'
341     else:
342         label = pkg
343     if pkg == 'all' or (mode == MODE_PKG and pkg == rootpkg):
344         color = root_colour
345     else:
346         if pkg.startswith('host') \
347         or pkg.startswith('toolchain') \
348         or pkg.startswith('rootfs'):
349             color = host_colour
350         else:
351             color = target_colour
352     version = dict_version.get(pkg)
353     if version == "virtual":
354         outfile.write("%s [label = <<I>%s</I>>]\n" % (name, label))
355     else:
356         outfile.write("%s [label = \"%s\"]\n" % (name, label))
357     outfile.write("%s [color=%s,style=filled]\n" % (name, color))
358
359 # Print the dependency graph of a package
360 def print_pkg_deps(depth, pkg):
361     if pkg in done_deps:
362         return
363     done_deps.append(pkg)
364     print_attrs(pkg)
365     if pkg not in dict_deps:
366         return
367     for p in stop_list:
368         if fnmatch(pkg, p):
369             return
370     if dict_version.get(pkg) == "virtual" and "virtual" in stop_list:
371         return
372     if pkg.startswith("host-") and "host" in stop_list:
373         return
374     if max_depth == 0 or depth < max_depth:
375         for d in dict_deps[pkg]:
376             if dict_version.get(d) == "virtual" \
377                and "virtual" in exclude_list:
378                 continue
379             if d.startswith("host-") \
380                and "host" in exclude_list:
381                 continue
382             add = True
383             for p in exclude_list:
384                 if fnmatch(d,p):
385                     add = False
386                     break
387             if add:
388                 outfile.write("%s -> %s [dir=%s]\n" % (pkg_node_name(pkg), pkg_node_name(d), arrow_dir))
389                 print_pkg_deps(depth+1, d)
390
391 # Start printing the graph data
392 outfile.write("digraph G {\n")
393
394 done_deps = []
395 print_pkg_deps(0, rootpkg)
396
397 outfile.write("}\n")