PageRenderTime 23ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/sphinx/ext/inheritance_diagram.py

http://github.com/IronLanguages/main
Python | 366 lines | 293 code | 20 blank | 53 comment | 13 complexity | 43e241d54120f7398bf5aa2042abbab8 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. # -*- coding: utf-8 -*-
  2. """
  3. sphinx.ext.inheritance_diagram
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Defines a docutils directive for inserting inheritance diagrams.
  6. Provide the directive with one or more classes or modules (separated
  7. by whitespace). For modules, all of the classes in that module will
  8. be used.
  9. Example::
  10. Given the following classes:
  11. class A: pass
  12. class B(A): pass
  13. class C(A): pass
  14. class D(B, C): pass
  15. class E(B): pass
  16. .. inheritance-diagram: D E
  17. Produces a graph like the following:
  18. A
  19. / \
  20. B C
  21. / \ /
  22. E D
  23. The graph is inserted as a PNG+image map into HTML and a PDF in
  24. LaTeX.
  25. :copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS.
  26. :license: BSD, see LICENSE for details.
  27. """
  28. import re
  29. import sys
  30. import inspect
  31. try:
  32. from hashlib import md5
  33. except ImportError:
  34. from md5 import md5
  35. from docutils import nodes
  36. from docutils.parsers.rst import directives
  37. from sphinx.roles import xfileref_role
  38. from sphinx.ext.graphviz import render_dot_html, render_dot_latex
  39. from sphinx.util.compat import Directive
  40. class_sig_re = re.compile(r'''^([\w.]*\.)? # module names
  41. (\w+) \s* $ # class/final module name
  42. ''', re.VERBOSE)
  43. class InheritanceException(Exception):
  44. pass
  45. class InheritanceGraph(object):
  46. """
  47. Given a list of classes, determines the set of classes that they inherit
  48. from all the way to the root "object", and then is able to generate a
  49. graphviz dot graph from them.
  50. """
  51. def __init__(self, class_names, currmodule, show_builtins=False):
  52. """
  53. *class_names* is a list of child classes to show bases from.
  54. If *show_builtins* is True, then Python builtins will be shown
  55. in the graph.
  56. """
  57. self.class_names = class_names
  58. self.classes = self._import_classes(class_names, currmodule)
  59. self.all_classes = self._all_classes(self.classes)
  60. if len(self.all_classes) == 0:
  61. raise InheritanceException('No classes found for '
  62. 'inheritance diagram')
  63. self.show_builtins = show_builtins
  64. def _import_class_or_module(self, name, currmodule):
  65. """
  66. Import a class using its fully-qualified *name*.
  67. """
  68. try:
  69. path, base = class_sig_re.match(name).groups()
  70. except ValueError:
  71. raise InheritanceException('Invalid class or module %r specified '
  72. 'for inheritance diagram' % name)
  73. fullname = (path or '') + base
  74. path = (path and path.rstrip('.') or '')
  75. # two possibilities: either it is a module, then import it
  76. try:
  77. module = __import__(fullname)
  78. todoc = sys.modules[fullname]
  79. except ImportError:
  80. # else it is a class, then import the module
  81. if not path:
  82. if currmodule:
  83. # try the current module
  84. path = currmodule
  85. else:
  86. raise InheritanceException(
  87. 'Could not import class %r specified for '
  88. 'inheritance diagram' % base)
  89. try:
  90. module = __import__(path)
  91. todoc = getattr(sys.modules[path], base)
  92. except (ImportError, AttributeError):
  93. raise InheritanceException(
  94. 'Could not import class or module %r specified for '
  95. 'inheritance diagram' % (path + '.' + base))
  96. # If a class, just return it
  97. if inspect.isclass(todoc):
  98. return [todoc]
  99. elif inspect.ismodule(todoc):
  100. classes = []
  101. for cls in todoc.__dict__.values():
  102. if inspect.isclass(cls) and cls.__module__ == todoc.__name__:
  103. classes.append(cls)
  104. return classes
  105. raise InheritanceException('%r specified for inheritance diagram is '
  106. 'not a class or module' % name)
  107. def _import_classes(self, class_names, currmodule):
  108. """
  109. Import a list of classes.
  110. """
  111. classes = []
  112. for name in class_names:
  113. classes.extend(self._import_class_or_module(name, currmodule))
  114. return classes
  115. def _all_classes(self, classes):
  116. """
  117. Return a list of all classes that are ancestors of *classes*.
  118. """
  119. all_classes = {}
  120. def recurse(cls):
  121. all_classes[cls] = None
  122. for c in cls.__bases__:
  123. if c not in all_classes:
  124. recurse(c)
  125. for cls in classes:
  126. recurse(cls)
  127. return all_classes.keys()
  128. def class_name(self, cls, parts=0):
  129. """
  130. Given a class object, return a fully-qualified name. This
  131. works for things I've tested in matplotlib so far, but may not
  132. be completely general.
  133. """
  134. module = cls.__module__
  135. if module == '__builtin__':
  136. fullname = cls.__name__
  137. else:
  138. fullname = '%s.%s' % (module, cls.__name__)
  139. if parts == 0:
  140. return fullname
  141. name_parts = fullname.split('.')
  142. return '.'.join(name_parts[-parts:])
  143. def get_all_class_names(self):
  144. """
  145. Get all of the class names involved in the graph.
  146. """
  147. return [self.class_name(x) for x in self.all_classes]
  148. # These are the default attrs for graphviz
  149. default_graph_attrs = {
  150. 'rankdir': 'LR',
  151. 'size': '"8.0, 12.0"',
  152. }
  153. default_node_attrs = {
  154. 'shape': 'box',
  155. 'fontsize': 10,
  156. 'height': 0.25,
  157. 'fontname': 'Vera Sans, DejaVu Sans, Liberation Sans, '
  158. 'Arial, Helvetica, sans',
  159. 'style': '"setlinewidth(0.5)"',
  160. }
  161. default_edge_attrs = {
  162. 'arrowsize': 0.5,
  163. 'style': '"setlinewidth(0.5)"',
  164. }
  165. def _format_node_attrs(self, attrs):
  166. return ','.join(['%s=%s' % x for x in attrs.items()])
  167. def _format_graph_attrs(self, attrs):
  168. return ''.join(['%s=%s;\n' % x for x in attrs.items()])
  169. def generate_dot(self, name, parts=0, urls={}, env=None,
  170. graph_attrs={}, node_attrs={}, edge_attrs={}):
  171. """
  172. Generate a graphviz dot graph from the classes that
  173. were passed in to __init__.
  174. *name* is the name of the graph.
  175. *urls* is a dictionary mapping class names to HTTP URLs.
  176. *graph_attrs*, *node_attrs*, *edge_attrs* are dictionaries containing
  177. key/value pairs to pass on as graphviz properties.
  178. """
  179. g_attrs = self.default_graph_attrs.copy()
  180. n_attrs = self.default_node_attrs.copy()
  181. e_attrs = self.default_edge_attrs.copy()
  182. g_attrs.update(graph_attrs)
  183. n_attrs.update(node_attrs)
  184. e_attrs.update(edge_attrs)
  185. if env:
  186. g_attrs.update(env.config.inheritance_graph_attrs)
  187. n_attrs.update(env.config.inheritance_node_attrs)
  188. e_attrs.update(env.config.inheritance_edge_attrs)
  189. res = []
  190. res.append('digraph %s {\n' % name)
  191. res.append(self._format_graph_attrs(g_attrs))
  192. for cls in self.all_classes:
  193. if not self.show_builtins and cls in __builtins__.values():
  194. continue
  195. name = self.class_name(cls, parts)
  196. # Write the node
  197. this_node_attrs = n_attrs.copy()
  198. url = urls.get(self.class_name(cls))
  199. if url is not None:
  200. this_node_attrs['URL'] = '"%s"' % url
  201. res.append(' "%s" [%s];\n' %
  202. (name, self._format_node_attrs(this_node_attrs)))
  203. # Write the edges
  204. for base in cls.__bases__:
  205. if not self.show_builtins and base in __builtins__.values():
  206. continue
  207. base_name = self.class_name(base, parts)
  208. res.append(' "%s" -> "%s" [%s];\n' %
  209. (base_name, name,
  210. self._format_node_attrs(e_attrs)))
  211. res.append('}\n')
  212. return ''.join(res)
  213. class inheritance_diagram(nodes.General, nodes.Element):
  214. """
  215. A docutils node to use as a placeholder for the inheritance diagram.
  216. """
  217. pass
  218. class InheritanceDiagram(Directive):
  219. """
  220. Run when the inheritance_diagram directive is first encountered.
  221. """
  222. has_content = False
  223. required_arguments = 1
  224. optional_arguments = 0
  225. final_argument_whitespace = True
  226. option_spec = {
  227. 'parts': directives.nonnegative_int,
  228. }
  229. def run(self):
  230. node = inheritance_diagram()
  231. node.document = self.state.document
  232. env = self.state.document.settings.env
  233. class_names = self.arguments[0].split()
  234. # Create a graph starting with the list of classes
  235. try:
  236. graph = InheritanceGraph(class_names, env.currmodule)
  237. except InheritanceException, err:
  238. return [node.document.reporter.warning(err.args[0],
  239. line=self.lineno)]
  240. # Create xref nodes for each target of the graph's image map and
  241. # add them to the doc tree so that Sphinx can resolve the
  242. # references to real URLs later. These nodes will eventually be
  243. # removed from the doctree after we're done with them.
  244. for name in graph.get_all_class_names():
  245. refnodes, x = xfileref_role(
  246. 'class', ':class:`%s`' % name, name, 0, self.state)
  247. node.extend(refnodes)
  248. # Store the graph object so we can use it to generate the
  249. # dot file later
  250. node['graph'] = graph
  251. # Store the original content for use as a hash
  252. node['parts'] = self.options.get('parts', 0)
  253. node['content'] = ' '.join(class_names)
  254. return [node]
  255. def get_graph_hash(node):
  256. return md5(node['content'] + str(node['parts'])).hexdigest()[-10:]
  257. def html_visit_inheritance_diagram(self, node):
  258. """
  259. Output the graph for HTML. This will insert a PNG with clickable
  260. image map.
  261. """
  262. graph = node['graph']
  263. parts = node['parts']
  264. graph_hash = get_graph_hash(node)
  265. name = 'inheritance%s' % graph_hash
  266. # Create a mapping from fully-qualified class names to URLs.
  267. urls = {}
  268. for child in node:
  269. if child.get('refuri') is not None:
  270. urls[child['reftitle']] = child.get('refuri')
  271. elif child.get('refid') is not None:
  272. urls[child['reftitle']] = '#' + child.get('refid')
  273. dotcode = graph.generate_dot(name, parts, urls, env=self.builder.env)
  274. render_dot_html(self, node, dotcode, [], 'inheritance', 'inheritance')
  275. raise nodes.SkipNode
  276. def latex_visit_inheritance_diagram(self, node):
  277. """
  278. Output the graph for LaTeX. This will insert a PDF.
  279. """
  280. graph = node['graph']
  281. parts = node['parts']
  282. graph_hash = get_graph_hash(node)
  283. name = 'inheritance%s' % graph_hash
  284. dotcode = graph.generate_dot(name, parts, env=self.builder.env,
  285. graph_attrs={'size': '"6.0,6.0"'})
  286. render_dot_latex(self, node, dotcode, [], 'inheritance')
  287. raise nodes.SkipNode
  288. def skip(self, node):
  289. raise nodes.SkipNode
  290. def setup(app):
  291. app.setup_extension('sphinx.ext.graphviz')
  292. app.add_node(
  293. inheritance_diagram,
  294. latex=(latex_visit_inheritance_diagram, None),
  295. html=(html_visit_inheritance_diagram, None),
  296. text=(skip, None))
  297. app.add_directive('inheritance-diagram', InheritanceDiagram)
  298. app.add_config_value('inheritance_graph_attrs', {}, False),
  299. app.add_config_value('inheritance_node_attrs', {}, False),
  300. app.add_config_value('inheritance_edge_attrs', {}, False),