diadefslib.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. # Copyright (c) 2006, 2008-2010, 2013-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  2. # Copyright (c) 2014 Brett Cannon <brett@python.org>
  3. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  4. # Copyright (c) 2015-2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
  5. # Copyright (c) 2015 Florian Bruhin <me@the-compiler.org>
  6. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  7. # Copyright (c) 2016 Ashley Whetter <ashley@awhetter.co.uk>
  8. # Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com>
  9. # Copyright (c) 2018 ssolanki <sushobhitsolanki@gmail.com>
  10. # Copyright (c) 2018 Sushobhit <31987769+sushobhit27@users.noreply.github.com>
  11. # Copyright (c) 2018 Ville Skyttä <ville.skytta@iki.fi>
  12. # Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
  13. # Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
  14. # Copyright (c) 2020 Anthony Sottile <asottile@umich.edu>
  15. # Copyright (c) 2021 bot <bot@noreply.github.com>
  16. # Copyright (c) 2021 Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
  17. # Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  18. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  19. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  20. """handle diagram generation options for class diagram or default diagrams
  21. """
  22. from typing import Any, Optional
  23. import astroid
  24. from astroid import nodes
  25. from pylint.pyreverse.diagrams import ClassDiagram, PackageDiagram
  26. from pylint.pyreverse.inspector import Project
  27. from pylint.pyreverse.utils import LocalsVisitor
  28. # diagram generators ##########################################################
  29. class DiaDefGenerator:
  30. """handle diagram generation options"""
  31. def __init__(self, linker, handler):
  32. """common Diagram Handler initialization"""
  33. self.config = handler.config
  34. self._set_default_options()
  35. self.linker = linker
  36. self.classdiagram = None # defined by subclasses
  37. def get_title(self, node):
  38. """get title for objects"""
  39. title = node.name
  40. if self.module_names:
  41. title = f"{node.root().name}.{title}"
  42. return title
  43. def _set_option(self, option):
  44. """activate some options if not explicitly deactivated"""
  45. # if we have a class diagram, we want more information by default;
  46. # so if the option is None, we return True
  47. if option is None:
  48. return bool(self.config.classes)
  49. return option
  50. def _set_default_options(self):
  51. """set different default options with _default dictionary"""
  52. self.module_names = self._set_option(self.config.module_names)
  53. all_ancestors = self._set_option(self.config.all_ancestors)
  54. all_associated = self._set_option(self.config.all_associated)
  55. anc_level, association_level = (0, 0)
  56. if all_ancestors:
  57. anc_level = -1
  58. if all_associated:
  59. association_level = -1
  60. if self.config.show_ancestors is not None:
  61. anc_level = self.config.show_ancestors
  62. if self.config.show_associated is not None:
  63. association_level = self.config.show_associated
  64. self.anc_level, self.association_level = anc_level, association_level
  65. def _get_levels(self):
  66. """help function for search levels"""
  67. return self.anc_level, self.association_level
  68. def show_node(self, node):
  69. """true if builtins and not show_builtins"""
  70. if self.config.show_builtin:
  71. return True
  72. return node.root().name != "builtins"
  73. def add_class(self, node):
  74. """visit one class and add it to diagram"""
  75. self.linker.visit(node)
  76. self.classdiagram.add_object(self.get_title(node), node)
  77. def get_ancestors(self, node, level):
  78. """return ancestor nodes of a class node"""
  79. if level == 0:
  80. return
  81. for ancestor in node.ancestors(recurs=False):
  82. if not self.show_node(ancestor):
  83. continue
  84. yield ancestor
  85. def get_associated(self, klass_node, level):
  86. """return associated nodes of a class node"""
  87. if level == 0:
  88. return
  89. for association_nodes in list(klass_node.instance_attrs_type.values()) + list(
  90. klass_node.locals_type.values()
  91. ):
  92. for node in association_nodes:
  93. if isinstance(node, astroid.Instance):
  94. node = node._proxied
  95. if not (isinstance(node, nodes.ClassDef) and self.show_node(node)):
  96. continue
  97. yield node
  98. def extract_classes(self, klass_node, anc_level, association_level):
  99. """extract recursively classes related to klass_node"""
  100. if self.classdiagram.has_node(klass_node) or not self.show_node(klass_node):
  101. return
  102. self.add_class(klass_node)
  103. for ancestor in self.get_ancestors(klass_node, anc_level):
  104. self.extract_classes(ancestor, anc_level - 1, association_level)
  105. for node in self.get_associated(klass_node, association_level):
  106. self.extract_classes(node, anc_level, association_level - 1)
  107. class DefaultDiadefGenerator(LocalsVisitor, DiaDefGenerator):
  108. """generate minimum diagram definition for the project :
  109. * a package diagram including project's modules
  110. * a class diagram including project's classes
  111. """
  112. def __init__(self, linker, handler):
  113. DiaDefGenerator.__init__(self, linker, handler)
  114. LocalsVisitor.__init__(self)
  115. def visit_project(self, node: Project) -> None:
  116. """visit a pyreverse.utils.Project node
  117. create a diagram definition for packages
  118. """
  119. mode = self.config.mode
  120. if len(node.modules) > 1:
  121. self.pkgdiagram: Optional[PackageDiagram] = PackageDiagram(
  122. f"packages {node.name}", mode
  123. )
  124. else:
  125. self.pkgdiagram = None
  126. self.classdiagram = ClassDiagram(f"classes {node.name}", mode)
  127. def leave_project(self, _: Project) -> Any:
  128. """leave the pyreverse.utils.Project node
  129. return the generated diagram definition
  130. """
  131. if self.pkgdiagram:
  132. return self.pkgdiagram, self.classdiagram
  133. return (self.classdiagram,)
  134. def visit_module(self, node: nodes.Module) -> None:
  135. """visit an astroid.Module node
  136. add this class to the package diagram definition
  137. """
  138. if self.pkgdiagram:
  139. self.linker.visit(node)
  140. self.pkgdiagram.add_object(node.name, node)
  141. def visit_classdef(self, node: nodes.ClassDef) -> None:
  142. """visit an astroid.Class node
  143. add this class to the class diagram definition
  144. """
  145. anc_level, association_level = self._get_levels()
  146. self.extract_classes(node, anc_level, association_level)
  147. def visit_importfrom(self, node: nodes.ImportFrom) -> None:
  148. """visit astroid.ImportFrom and catch modules for package diagram"""
  149. if self.pkgdiagram:
  150. self.pkgdiagram.add_from_depend(node, node.modname)
  151. class ClassDiadefGenerator(DiaDefGenerator):
  152. """generate a class diagram definition including all classes related to a
  153. given class
  154. """
  155. def class_diagram(self, project, klass):
  156. """return a class diagram definition for the given klass and its
  157. related klasses
  158. """
  159. self.classdiagram = ClassDiagram(klass, self.config.mode)
  160. if len(project.modules) > 1:
  161. module, klass = klass.rsplit(".", 1)
  162. module = project.get_module(module)
  163. else:
  164. module = project.modules[0]
  165. klass = klass.split(".")[-1]
  166. klass = next(module.ilookup(klass))
  167. anc_level, association_level = self._get_levels()
  168. self.extract_classes(klass, anc_level, association_level)
  169. return self.classdiagram
  170. # diagram handler #############################################################
  171. class DiadefsHandler:
  172. """handle diagram definitions :
  173. get it from user (i.e. xml files) or generate them
  174. """
  175. def __init__(self, config):
  176. self.config = config
  177. def get_diadefs(self, project, linker):
  178. """Get the diagrams configuration data
  179. :param project:The pyreverse project
  180. :type project: pyreverse.utils.Project
  181. :param linker: The linker
  182. :type linker: pyreverse.inspector.Linker(IdGeneratorMixIn, LocalsVisitor)
  183. :returns: The list of diagram definitions
  184. :rtype: list(:class:`pylint.pyreverse.diagrams.ClassDiagram`)
  185. """
  186. # read and interpret diagram definitions (Diadefs)
  187. diagrams = []
  188. generator = ClassDiadefGenerator(linker, self)
  189. for klass in self.config.classes:
  190. diagrams.append(generator.class_diagram(project, klass))
  191. if not diagrams:
  192. diagrams = DefaultDiadefGenerator(linker, self).visit(project)
  193. for diagram in diagrams:
  194. diagram.extract_relationships()
  195. return diagrams