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
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.
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
22 # Copyright (C) 2010-2013 Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
27 from fnmatch
import fnmatch
32 MODE_FULL
= 1 # draw full dependency graph for all selected packages
33 MODE_PKG
= 2 # draw dependency graph for a given package
36 # Limit drawing the dependency graph to this depth. 0 means 'no limit'.
39 # Whether to draw the transitive dependencies
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',
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()
74 check_only
= args
.check_only
76 if args
.outfile
is None:
80 sys
.stderr
.write("don't specify outfile and check-only at the same time\n")
82 outfile
= open(args
.outfile
, "w")
84 if args
.package
is None:
88 rootpkg
= args
.package
90 max_depth
= args
.depth
92 if args
.stop_list
is None:
95 stop_list
= args
.stop_list
97 if args
.exclude_list
is None:
100 exclude_list
= args
.exclude_list
102 transitive
= args
.transitive
105 get_depends_func
= pkgutil
.get_depends
106 arrow_dir
= "forward"
108 if mode
== MODE_FULL
:
109 sys
.stderr
.write("--reverse needs a package\n")
111 get_depends_func
= pkgutil
.get_rdepends
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
)
121 root_colour
= colours
[0]
122 target_colour
= colours
[1]
123 host_colour
= colours
[2]
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
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:
139 return output
.split(' ')
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
):
149 # Filter the packages for which we already have the dependencies
154 filtered_pkgs
.append(pkg
)
157 if len(filtered_pkgs
) == 0:
160 depends
= get_depends_func(filtered_pkgs
)
163 for pkg
in filtered_pkgs
:
164 pkg_deps
= depends
[pkg
]
166 # This package has no dependency.
170 # Add dependencies to the list of dependencies
172 dependencies
.append((pkg
, dep
))
176 newdeps
= get_all_depends(deps
)
177 if newdeps
is not None:
178 dependencies
+= newdeps
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("-","")
187 TARGET_EXCEPTIONS
= [
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()
197 allpkgs
.append('all')
198 filtered_targets
= []
200 # Skip uninteresting targets
201 if tg
in TARGET_EXCEPTIONS
:
203 dependencies
.append(('all', tg
))
204 filtered_targets
.append(tg
)
205 deps
= get_all_depends(filtered_targets
)
210 # In pkg mode, start directly with get_all_depends() on the requested
212 elif mode
== MODE_PKG
:
213 dependencies
= get_all_depends([rootpkg
])
215 # Make the dependencies a dictionnary { 'pkg':[dep1, dep2, ...] }
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])
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".
228 def is_dep_cache_insert(pkg
, pkg2
, val
):
230 is_dep_cache
[pkg
].update({pkg2
: val
})
232 is_dep_cache
[pkg
] = {pkg2
: val
}
234 # Retrieves from the cache whether pkg2 is a transitive dependency
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
]
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
):
249 if is_dep(pkg
,p
,deps
):
255 # See is_dep_uncached() above; this is the cached version.
256 def is_dep(pkg
,pkg2
,deps
):
258 return is_dep_cache_lookup(pkg
, pkg2
)
260 val
= is_dep_uncached(pkg
, pkg2
, deps
)
261 is_dep_cache_insert(pkg
, pkg2
, val
)
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]
271 # - otherwise keep d[i]
272 def remove_transitive_deps(pkg
,deps
):
275 for i
in range(len(d
)):
277 for j
in range(len(d
)):
280 if is_dep(d
[i
],d
[j
],deps
):
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']]
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
):
295 if not pkg
in list(deps
.keys()):
303 sys
.stderr
.write("\nRecursion detected for : %s\n" % (p
))
306 sys
.stderr
.write("which is a dependency of: %s\n" % (_p
))
314 for pkg
in list(deps
.keys()):
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()):
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
)
328 check_circular_deps(dict_deps
)
332 dict_deps
= remove_extra_deps(dict_deps
)
333 dict_version
= pkgutil
.get_version([pkg
for pkg
in allpkgs
334 if pkg
!= "all" and not pkg
.startswith("root")])
336 # Print the attributes of a node: label and fill-color
337 def print_attrs(pkg
):
338 name
= pkg_node_name(pkg
)
343 if pkg
== 'all' or (mode
== MODE_PKG
and pkg
== rootpkg
):
346 if pkg
.startswith('host') \
347 or pkg
.startswith('toolchain') \
348 or pkg
.startswith('rootfs'):
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
))
356 outfile
.write("%s [label = \"%s\"]\n" % (name
, label
))
357 outfile
.write("%s [color=%s,style=filled]\n" % (name
, color
))
359 # Print the dependency graph of a package
360 def print_pkg_deps(depth
, pkg
):
363 done_deps
.append(pkg
)
365 if pkg
not in dict_deps
:
370 if dict_version
.get(pkg
) == "virtual" and "virtual" in stop_list
:
372 if pkg
.startswith("host-") and "host" in stop_list
:
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
:
379 if d
.startswith("host-") \
380 and "host" in exclude_list
:
383 for p
in exclude_list
:
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
)
391 # Start printing the graph data
392 outfile
.write("digraph G {\n")
395 print_pkg_deps(0, rootpkg
)