graph-depends 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. #!/usr/bin/python
  2. # Usage (the graphviz package must be installed in your distribution)
  3. # ./support/scripts/graph-depends [-p package-name] > test.dot
  4. # dot -Tpdf test.dot -o test.pdf
  5. #
  6. # With no arguments, graph-depends will draw a complete graph of
  7. # dependencies for the current configuration.
  8. # If '-p <package-name>' is specified, graph-depends will draw a graph
  9. # of dependencies for the given package name.
  10. # If '-d <depth>' is specified, graph-depends will limit the depth of
  11. # the dependency graph to 'depth' levels.
  12. #
  13. # Limitations
  14. #
  15. # * Some packages have dependencies that depend on the Buildroot
  16. # configuration. For example, many packages have a dependency on
  17. # openssl if openssl has been enabled. This tool will graph the
  18. # dependencies as they are with the current Buildroot
  19. # configuration.
  20. #
  21. # Copyright (C) 2010-2013 Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
  22. import sys
  23. import subprocess
  24. import argparse
  25. from fnmatch import fnmatch
  26. # Modes of operation:
  27. MODE_FULL = 1 # draw full dependency graph for all selected packages
  28. MODE_PKG = 2 # draw dependency graph for a given package
  29. mode = 0
  30. # Limit drawing the dependency graph to this depth. 0 means 'no limit'.
  31. max_depth = 0
  32. # Whether to draw the transitive dependencies
  33. transitive = True
  34. parser = argparse.ArgumentParser(description="Graph packages dependencies")
  35. parser.add_argument("--package", '-p', metavar="PACKAGE",
  36. help="Graph the dependencies of PACKAGE")
  37. parser.add_argument("--depth", '-d', metavar="DEPTH", dest="depth", type=int, default=0,
  38. help="Limit the dependency graph to DEPTH levels; 0 means no limit.")
  39. parser.add_argument("--stop-on", "-s", metavar="PACKAGE", dest="stop_list", action="append",
  40. help="Do not graph past this package (can be given multiple times)." \
  41. + " Can be a package name or a glob, or" \
  42. + " 'virtual' to stop on virtual packages.")
  43. parser.add_argument("--exclude", "-x", metavar="PACKAGE", dest="exclude_list", action="append",
  44. help="Like --stop-on, but do not add PACKAGE to the graph.")
  45. parser.add_argument("--colours", "-c", metavar="COLOR_LIST", dest="colours",
  46. default="lightblue,grey,gainsboro",
  47. help="Comma-separated list of the three colours to use" \
  48. + " to draw the top-level package, the target" \
  49. + " packages, and the host packages, in this order." \
  50. + " Defaults to: 'lightblue,grey,gainsboro'")
  51. parser.add_argument("--transitive", dest="transitive", action='store_true',
  52. default=False)
  53. parser.add_argument("--no-transitive", dest="transitive", action='store_false',
  54. help="Draw (do not draw) transitive dependencies")
  55. args = parser.parse_args()
  56. if args.package is None:
  57. mode = MODE_FULL
  58. else:
  59. mode = MODE_PKG
  60. rootpkg = args.package
  61. max_depth = args.depth
  62. if args.stop_list is None:
  63. stop_list = []
  64. else:
  65. stop_list = args.stop_list
  66. if args.exclude_list is None:
  67. exclude_list = []
  68. else:
  69. exclude_list = args.exclude_list
  70. transitive = args.transitive
  71. # Get the colours: we need exactly three colours,
  72. # so no need not split more than 4
  73. # We'll let 'dot' validate the colours...
  74. colours = args.colours.split(',',4)
  75. if len(colours) != 3:
  76. sys.stderr.write("Error: incorrect colour list '%s'\n" % args.colours)
  77. sys.exit(1)
  78. root_colour = colours[0]
  79. target_colour = colours[1]
  80. host_colour = colours[2]
  81. allpkgs = []
  82. # Execute the "make <pkg>-show-version" command to get the version of a given
  83. # list of packages, and return the version formatted as a Python dictionary.
  84. def get_version(pkgs):
  85. sys.stderr.write("Getting version for %s\n" % pkgs)
  86. cmd = ["make", "-s", "--no-print-directory" ]
  87. for pkg in pkgs:
  88. cmd.append("%s-show-version" % pkg)
  89. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
  90. output = p.communicate()[0]
  91. if p.returncode != 0:
  92. sys.stderr.write("Error getting version %s\n" % pkgs)
  93. sys.exit(1)
  94. output = output.split("\n")
  95. if len(output) != len(pkgs) + 1:
  96. sys.stderr.write("Error getting version\n")
  97. sys.exit(1)
  98. version = {}
  99. for i in range(0, len(pkgs)):
  100. pkg = pkgs[i]
  101. version[pkg] = output[i]
  102. return version
  103. # Execute the "make show-targets" command to get the list of the main
  104. # Buildroot TARGETS and return it formatted as a Python list. This
  105. # list is used as the starting point for full dependency graphs
  106. def get_targets():
  107. sys.stderr.write("Getting targets\n")
  108. cmd = ["make", "-s", "--no-print-directory", "show-targets"]
  109. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
  110. output = p.communicate()[0].strip()
  111. if p.returncode != 0:
  112. return None
  113. if output == '':
  114. return []
  115. return output.split(' ')
  116. # Execute the "make <pkg>-show-depends" command to get the list of
  117. # dependencies of a given list of packages, and return the list of
  118. # dependencies formatted as a Python dictionary.
  119. def get_depends(pkgs):
  120. sys.stderr.write("Getting dependencies for %s\n" % pkgs)
  121. cmd = ["make", "-s", "--no-print-directory" ]
  122. for pkg in pkgs:
  123. cmd.append("%s-show-depends" % pkg)
  124. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
  125. output = p.communicate()[0]
  126. if p.returncode != 0:
  127. sys.stderr.write("Error getting dependencies %s\n" % pkgs)
  128. sys.exit(1)
  129. output = output.split("\n")
  130. if len(output) != len(pkgs) + 1:
  131. sys.stderr.write("Error getting dependencies\n")
  132. sys.exit(1)
  133. deps = {}
  134. for i in range(0, len(pkgs)):
  135. pkg = pkgs[i]
  136. pkg_deps = output[i].split(" ")
  137. if pkg_deps == ['']:
  138. deps[pkg] = []
  139. else:
  140. deps[pkg] = pkg_deps
  141. return deps
  142. # Recursive function that builds the tree of dependencies for a given
  143. # list of packages. The dependencies are built in a list called
  144. # 'dependencies', which contains tuples of the form (pkg1 ->
  145. # pkg2_on_which_pkg1_depends, pkg3 -> pkg4_on_which_pkg3_depends) and
  146. # the function finally returns this list.
  147. def get_all_depends(pkgs):
  148. dependencies = []
  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. if len(filtered_pkgs) == 0:
  157. return []
  158. depends = get_depends(filtered_pkgs)
  159. deps = set()
  160. for pkg in filtered_pkgs:
  161. pkg_deps = depends[pkg]
  162. # This package has no dependency.
  163. if pkg_deps == []:
  164. continue
  165. # Add dependencies to the list of dependencies
  166. for dep in pkg_deps:
  167. dependencies.append((pkg, dep))
  168. deps.add(dep)
  169. if len(deps) != 0:
  170. newdeps = get_all_depends(deps)
  171. if newdeps is not None:
  172. dependencies += newdeps
  173. return dependencies
  174. # The Graphviz "dot" utility doesn't like dashes in node names. So for
  175. # node names, we strip all dashes.
  176. def pkg_node_name(pkg):
  177. return pkg.replace("-","")
  178. TARGET_EXCEPTIONS = [
  179. "target-finalize",
  180. "target-post-image",
  181. ]
  182. # In full mode, start with the result of get_targets() to get the main
  183. # targets and then use get_all_depends() for all targets
  184. if mode == MODE_FULL:
  185. targets = get_targets()
  186. dependencies = []
  187. allpkgs.append('all')
  188. filtered_targets = []
  189. for tg in targets:
  190. # Skip uninteresting targets
  191. if tg in TARGET_EXCEPTIONS:
  192. continue
  193. dependencies.append(('all', tg))
  194. filtered_targets.append(tg)
  195. deps = get_all_depends(filtered_targets)
  196. if deps is not None:
  197. dependencies += deps
  198. rootpkg = 'all'
  199. # In pkg mode, start directly with get_all_depends() on the requested
  200. # package
  201. elif mode == MODE_PKG:
  202. dependencies = get_all_depends([rootpkg])
  203. # Make the dependencies a dictionnary { 'pkg':[dep1, dep2, ...] }
  204. dict_deps = {}
  205. for dep in dependencies:
  206. if dep[0] not in dict_deps:
  207. dict_deps[dep[0]] = []
  208. dict_deps[dep[0]].append(dep[1])
  209. # This function return True if pkg is a dependency (direct or
  210. # transitive) of pkg2, dependencies being listed in the deps
  211. # dictionary. Returns False otherwise.
  212. def is_dep(pkg,pkg2,deps):
  213. if pkg2 in deps:
  214. for p in deps[pkg2]:
  215. if pkg == p:
  216. return True
  217. if is_dep(pkg,p,deps):
  218. return True
  219. return False
  220. # This function eliminates transitive dependencies; for example, given
  221. # these dependency chain: A->{B,C} and B->{C}, the A->{C} dependency is
  222. # already covered by B->{C}, so C is a transitive dependency of A, via B.
  223. # The functions does:
  224. # - for each dependency d[i] of the package pkg
  225. # - if d[i] is a dependency of any of the other dependencies d[j]
  226. # - do not keep d[i]
  227. # - otherwise keep d[i]
  228. def remove_transitive_deps(pkg,deps):
  229. d = deps[pkg]
  230. new_d = []
  231. for i in range(len(d)):
  232. keep_me = True
  233. for j in range(len(d)):
  234. if j==i:
  235. continue
  236. if is_dep(d[i],d[j],deps):
  237. keep_me = False
  238. if keep_me:
  239. new_d.append(d[i])
  240. return new_d
  241. # This function removes the dependency on the 'toolchain' package
  242. def remove_toolchain_deps(pkg,deps):
  243. return [p for p in deps[pkg] if not p == 'toolchain']
  244. # This functions trims down the dependency list of all packages.
  245. # It applies in sequence all the dependency-elimination methods.
  246. def remove_extra_deps(deps):
  247. for pkg in list(deps.keys()):
  248. if not pkg == 'all':
  249. deps[pkg] = remove_toolchain_deps(pkg,deps)
  250. for pkg in list(deps.keys()):
  251. if not transitive or pkg == 'all':
  252. deps[pkg] = remove_transitive_deps(pkg,deps)
  253. return deps
  254. dict_deps = remove_extra_deps(dict_deps)
  255. dict_version = get_version([pkg for pkg in allpkgs
  256. if pkg != "all" and not pkg.startswith("root")])
  257. # Print the attributes of a node: label and fill-color
  258. def print_attrs(pkg):
  259. name = pkg_node_name(pkg)
  260. if pkg == 'all':
  261. label = 'ALL'
  262. else:
  263. label = pkg
  264. if pkg == 'all' or (mode == MODE_PKG and pkg == rootpkg):
  265. color = root_colour
  266. else:
  267. if pkg.startswith('host') \
  268. or pkg.startswith('toolchain') \
  269. or pkg.startswith('rootfs'):
  270. color = host_colour
  271. else:
  272. color = target_colour
  273. version = dict_version.get(pkg)
  274. if version == "virtual":
  275. print("%s [label = <<I>%s</I>>]" % (name, label))
  276. else:
  277. print("%s [label = \"%s\"]" % (name, label))
  278. print("%s [color=%s,style=filled]" % (name, color))
  279. # Print the dependency graph of a package
  280. def print_pkg_deps(depth, pkg):
  281. if pkg in done_deps:
  282. return
  283. done_deps.append(pkg)
  284. print_attrs(pkg)
  285. if pkg not in dict_deps:
  286. return
  287. for p in stop_list:
  288. if fnmatch(pkg, p):
  289. return
  290. if dict_version.get(pkg) == "virtual" and "virtual" in stop_list:
  291. return
  292. if max_depth == 0 or depth < max_depth:
  293. for d in dict_deps[pkg]:
  294. add = True
  295. for p in exclude_list:
  296. if fnmatch(d,p):
  297. add = False
  298. break
  299. if dict_version.get(d) == "virtual" \
  300. and "virtual" in exclude_list:
  301. add = False
  302. break
  303. if add:
  304. print("%s -> %s" % (pkg_node_name(pkg), pkg_node_name(d)))
  305. print_pkg_deps(depth+1, d)
  306. # Start printing the graph data
  307. print("digraph G {")
  308. done_deps = []
  309. print_pkg_deps(0, rootpkg)
  310. print("}")