graph-depends 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. # Modes of operation:
  26. MODE_FULL = 1 # draw full dependency graph for all selected packages
  27. MODE_PKG = 2 # draw dependency graph for a given package
  28. mode = 0
  29. # Limit drawing the dependency graph to this depth. 0 means 'no limit'.
  30. max_depth = 0
  31. # Whether to draw the transitive dependencies
  32. transitive = True
  33. parser = argparse.ArgumentParser(description="Graph pacakges dependencies")
  34. parser.add_argument("--package", '-p', metavar="PACKAGE",
  35. help="Graph the dependencies of PACKAGE")
  36. parser.add_argument("--depth", '-d', metavar="DEPTH", dest="depth", type=int, default=0,
  37. help="Limit the dependency graph to DEPTH levels; 0 means no limit.")
  38. parser.add_argument("--colours", "-c", metavar="COLOR_LIST", dest="colours",
  39. default="lightblue,grey,gainsboro",
  40. help="Comma-separated list of the three colours to use" \
  41. + " to draw the top-level package, the target" \
  42. + " packages, and the host packages, in this order." \
  43. + " Defaults to: 'lightblue,grey,gainsboro'")
  44. parser.add_argument("--transitive", dest="transitive", action='store_true',
  45. default=False)
  46. parser.add_argument("--no-transitive", dest="transitive", action='store_false',
  47. help="Draw (do not draw) transitive dependencies")
  48. args = parser.parse_args()
  49. if args.package is None:
  50. mode = MODE_FULL
  51. else:
  52. mode = MODE_PKG
  53. rootpkg = args.package
  54. max_depth = args.depth
  55. transitive = args.transitive
  56. # Get the colours: we need exactly three colours,
  57. # so no need not split more than 4
  58. # We'll let 'dot' validate the colours...
  59. colours = args.colours.split(',',4)
  60. if len(colours) != 3:
  61. sys.stderr.write("Error: incorrect colour list '%s'\n" % args.colours)
  62. sys.exit(1)
  63. root_colour = colours[0]
  64. target_colour = colours[1]
  65. host_colour = colours[2]
  66. allpkgs = []
  67. # Execute the "make show-targets" command to get the list of the main
  68. # Buildroot TARGETS and return it formatted as a Python list. This
  69. # list is used as the starting point for full dependency graphs
  70. def get_targets():
  71. sys.stderr.write("Getting targets\n")
  72. cmd = ["make", "-s", "--no-print-directory", "show-targets"]
  73. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
  74. output = p.communicate()[0].strip()
  75. if p.returncode != 0:
  76. return None
  77. if output == '':
  78. return []
  79. return output.split(' ')
  80. # Execute the "make <pkg>-show-depends" command to get the list of
  81. # dependencies of a given list of packages, and return the list of
  82. # dependencies formatted as a Python dictionary.
  83. def get_depends(pkgs):
  84. sys.stderr.write("Getting dependencies for %s\n" % pkgs)
  85. cmd = ["make", "-s", "--no-print-directory" ]
  86. for pkg in pkgs:
  87. cmd.append("%s-show-depends" % pkg)
  88. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
  89. output = p.communicate()[0]
  90. if p.returncode != 0:
  91. sys.stderr.write("Error getting dependencies %s\n" % pkgs)
  92. sys.exit(1)
  93. output = output.split("\n")
  94. if len(output) != len(pkgs) + 1:
  95. sys.stderr.write("Error getting dependencies\n")
  96. sys.exit(1)
  97. deps = {}
  98. for i in range(0, len(pkgs)):
  99. pkg = pkgs[i]
  100. pkg_deps = output[i].split(" ")
  101. if pkg_deps == ['']:
  102. deps[pkg] = []
  103. else:
  104. deps[pkg] = pkg_deps
  105. return deps
  106. # Recursive function that builds the tree of dependencies for a given
  107. # list of packages. The dependencies are built in a list called
  108. # 'dependencies', which contains tuples of the form (pkg1 ->
  109. # pkg2_on_which_pkg1_depends, pkg3 -> pkg4_on_which_pkg3_depends) and
  110. # the function finally returns this list.
  111. def get_all_depends(pkgs):
  112. dependencies = []
  113. # Filter the packages for which we already have the dependencies
  114. filtered_pkgs = []
  115. for pkg in pkgs:
  116. if pkg in allpkgs:
  117. continue
  118. filtered_pkgs.append(pkg)
  119. allpkgs.append(pkg)
  120. if len(filtered_pkgs) == 0:
  121. return []
  122. depends = get_depends(filtered_pkgs)
  123. deps = set()
  124. for pkg in filtered_pkgs:
  125. pkg_deps = depends[pkg]
  126. # This package has no dependency.
  127. if pkg_deps == []:
  128. continue
  129. # Add dependencies to the list of dependencies
  130. for dep in pkg_deps:
  131. dependencies.append((pkg, dep))
  132. deps.add(dep)
  133. if len(deps) != 0:
  134. newdeps = get_all_depends(deps)
  135. if newdeps is not None:
  136. dependencies += newdeps
  137. return dependencies
  138. # The Graphviz "dot" utility doesn't like dashes in node names. So for
  139. # node names, we strip all dashes.
  140. def pkg_node_name(pkg):
  141. return pkg.replace("-","")
  142. TARGET_EXCEPTIONS = [
  143. "target-generic-securetty",
  144. "target-generic-issue",
  145. "target-generic-getty-busybox",
  146. "target-generic-do-remount-rw",
  147. "target-generic-dont-remount-rw",
  148. "target-finalize",
  149. "erase-fakeroots",
  150. "target-generic-hostname",
  151. "target-root-passwd",
  152. "target-post-image",
  153. "target-purgelocales",
  154. ]
  155. # In full mode, start with the result of get_targets() to get the main
  156. # targets and then use get_all_depends() for all targets
  157. if mode == MODE_FULL:
  158. targets = get_targets()
  159. dependencies = []
  160. allpkgs.append('all')
  161. filtered_targets = []
  162. for tg in targets:
  163. # Skip uninteresting targets
  164. if tg in TARGET_EXCEPTIONS:
  165. continue
  166. dependencies.append(('all', tg))
  167. filtered_targets.append(tg)
  168. deps = get_all_depends(filtered_targets)
  169. if deps is not None:
  170. dependencies += deps
  171. rootpkg = 'all'
  172. # In pkg mode, start directly with get_all_depends() on the requested
  173. # package
  174. elif mode == MODE_PKG:
  175. dependencies = get_all_depends([rootpkg])
  176. # Make the dependencies a dictionnary { 'pkg':[dep1, dep2, ...] }
  177. dict_deps = {}
  178. for dep in dependencies:
  179. if dep[0] not in dict_deps:
  180. dict_deps[dep[0]] = []
  181. dict_deps[dep[0]].append(dep[1])
  182. # This function return True if pkg is a dependency (direct or
  183. # transitive) of pkg2, dependencies being listed in the deps
  184. # dictionary. Returns False otherwise.
  185. def is_dep(pkg,pkg2,deps):
  186. if pkg2 in deps:
  187. for p in deps[pkg2]:
  188. if pkg == p:
  189. return True
  190. if is_dep(pkg,p,deps):
  191. return True
  192. return False
  193. # This function eliminates transitive dependencies; for example, given
  194. # these dependency chain: A->{B,C} and B->{C}, the A->{C} dependency is
  195. # already covered by B->{C}, so C is a transitive dependency of A, via B.
  196. # The functions does:
  197. # - for each dependency d[i] of the package pkg
  198. # - if d[i] is a dependency of any of the other dependencies d[j]
  199. # - do not keep d[i]
  200. # - otherwise keep d[i]
  201. def remove_transitive_deps(pkg,deps):
  202. d = deps[pkg]
  203. new_d = []
  204. for i in range(len(d)):
  205. keep_me = True
  206. for j in range(len(d)):
  207. if j==i:
  208. continue
  209. if is_dep(d[i],d[j],deps):
  210. keep_me = False
  211. if keep_me:
  212. new_d.append(d[i])
  213. return new_d
  214. # This function removes the dependency on the 'toolchain' package
  215. def remove_toolchain_deps(pkg,deps):
  216. return [p for p in deps[pkg] if not p == 'toolchain']
  217. # This functions trims down the dependency list of all packages.
  218. # It applies in sequence all the dependency-elimination methods.
  219. def remove_extra_deps(deps):
  220. for pkg in list(deps.keys()):
  221. if not pkg == 'all':
  222. deps[pkg] = remove_toolchain_deps(pkg,deps)
  223. for pkg in list(deps.keys()):
  224. if not transitive or pkg == 'all':
  225. deps[pkg] = remove_transitive_deps(pkg,deps)
  226. return deps
  227. dict_deps = remove_extra_deps(dict_deps)
  228. # Print the attributes of a node: label and fill-color
  229. def print_attrs(pkg):
  230. name = pkg_node_name(pkg)
  231. if pkg == 'all':
  232. label = 'ALL'
  233. else:
  234. label = pkg
  235. if pkg == 'all' or (mode == MODE_PKG and pkg == rootpkg):
  236. color = root_colour
  237. else:
  238. if pkg.startswith('host') \
  239. or pkg.startswith('toolchain') \
  240. or pkg.startswith('rootfs'):
  241. color = host_colour
  242. else:
  243. color = target_colour
  244. print("%s [label = \"%s\"]" % (name, label))
  245. print("%s [color=%s,style=filled]" % (name, color))
  246. # Print the dependency graph of a package
  247. def print_pkg_deps(depth, pkg):
  248. if pkg in done_deps:
  249. return
  250. done_deps.append(pkg)
  251. print_attrs(pkg)
  252. if pkg not in dict_deps:
  253. return
  254. if max_depth == 0 or depth < max_depth:
  255. for d in dict_deps[pkg]:
  256. print("%s -> %s" % (pkg_node_name(pkg), pkg_node_name(d)))
  257. print_pkg_deps(depth+1, d)
  258. # Start printing the graph data
  259. print("digraph G {")
  260. done_deps = []
  261. print_pkg_deps(0, rootpkg)
  262. print("}")