diagrams.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. # Copyright (c) 2006, 2008-2010, 2012-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  2. # Copyright (c) 2014-2018, 2020 Claudiu Popa <pcmanticore@gmail.com>
  3. # Copyright (c) 2014 Brett Cannon <brett@python.org>
  4. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  5. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  6. # Copyright (c) 2018 ssolanki <sushobhitsolanki@gmail.com>
  7. # Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
  8. # Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
  9. # Copyright (c) 2021 Takahide Nojima <nozzy123nozzy@gmail.com>
  10. # Copyright (c) 2021 bot <bot@noreply.github.com>
  11. # Copyright (c) 2021 Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
  12. # Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  13. # Copyright (c) 2021 Andreas Finkler <andi.finkler@gmail.com>
  14. # Copyright (c) 2021 Mark Byrne <31762852+mbyrnepr2@users.noreply.github.com>
  15. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  16. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  17. """diagram objects
  18. """
  19. import astroid
  20. from astroid import nodes
  21. from pylint.checkers.utils import decorated_with_property
  22. from pylint.pyreverse.utils import FilterMixIn, is_interface
  23. class Figure:
  24. """base class for counter handling"""
  25. class Relationship(Figure):
  26. """a relation ship from an object in the diagram to another"""
  27. def __init__(self, from_object, to_object, relation_type, name=None):
  28. super().__init__()
  29. self.from_object = from_object
  30. self.to_object = to_object
  31. self.type = relation_type
  32. self.name = name
  33. class DiagramEntity(Figure):
  34. """a diagram object, i.e. a label associated to an astroid node"""
  35. def __init__(self, title="No name", node=None):
  36. super().__init__()
  37. self.title = title
  38. self.node = node
  39. class PackageEntity(DiagramEntity):
  40. """A diagram object representing a package"""
  41. class ClassEntity(DiagramEntity):
  42. """A diagram object representing a class"""
  43. def __init__(self, title, node):
  44. super().__init__(title=title, node=node)
  45. self.attrs = None
  46. self.methods = None
  47. class ClassDiagram(Figure, FilterMixIn):
  48. """main class diagram handling"""
  49. TYPE = "class"
  50. def __init__(self, title, mode):
  51. FilterMixIn.__init__(self, mode)
  52. Figure.__init__(self)
  53. self.title = title
  54. self.objects = []
  55. self.relationships = {}
  56. self._nodes = {}
  57. self.depends = []
  58. def get_relationships(self, role):
  59. # sorted to get predictable (hence testable) results
  60. return sorted(
  61. self.relationships.get(role, ()),
  62. key=lambda x: (x.from_object.fig_id, x.to_object.fig_id),
  63. )
  64. def add_relationship(self, from_object, to_object, relation_type, name=None):
  65. """create a relation ship"""
  66. rel = Relationship(from_object, to_object, relation_type, name)
  67. self.relationships.setdefault(relation_type, []).append(rel)
  68. def get_relationship(self, from_object, relation_type):
  69. """return a relation ship or None"""
  70. for rel in self.relationships.get(relation_type, ()):
  71. if rel.from_object is from_object:
  72. return rel
  73. raise KeyError(relation_type)
  74. def get_attrs(self, node):
  75. """return visible attributes, possibly with class name"""
  76. attrs = []
  77. properties = [
  78. (n, m)
  79. for n, m in node.items()
  80. if isinstance(m, nodes.FunctionDef) and decorated_with_property(m)
  81. ]
  82. for node_name, associated_nodes in (
  83. list(node.instance_attrs_type.items())
  84. + list(node.locals_type.items())
  85. + properties
  86. ):
  87. if not self.show_attr(node_name):
  88. continue
  89. names = self.class_names(associated_nodes)
  90. if names:
  91. node_name = f"{node_name} : {', '.join(names)}"
  92. attrs.append(node_name)
  93. return sorted(attrs)
  94. def get_methods(self, node):
  95. """return visible methods"""
  96. methods = [
  97. m
  98. for m in node.values()
  99. if isinstance(m, nodes.FunctionDef)
  100. and not isinstance(m, astroid.objects.Property)
  101. and not decorated_with_property(m)
  102. and self.show_attr(m.name)
  103. ]
  104. return sorted(methods, key=lambda n: n.name)
  105. def add_object(self, title, node):
  106. """create a diagram object"""
  107. assert node not in self._nodes
  108. ent = DiagramEntity(title, node)
  109. self._nodes[node] = ent
  110. self.objects.append(ent)
  111. def class_names(self, nodes_lst):
  112. """return class names if needed in diagram"""
  113. names = []
  114. for node in nodes_lst:
  115. if isinstance(node, astroid.Instance):
  116. node = node._proxied
  117. if (
  118. isinstance(node, (nodes.ClassDef, nodes.Name, nodes.Subscript))
  119. and hasattr(node, "name")
  120. and not self.has_node(node)
  121. ):
  122. if node.name not in names:
  123. node_name = node.name
  124. names.append(node_name)
  125. return names
  126. def nodes(self):
  127. """return the list of underlying nodes"""
  128. return self._nodes.keys()
  129. def has_node(self, node):
  130. """return true if the given node is included in the diagram"""
  131. return node in self._nodes
  132. def object_from_node(self, node):
  133. """return the diagram object mapped to node"""
  134. return self._nodes[node]
  135. def classes(self):
  136. """return all class nodes in the diagram"""
  137. return [o for o in self.objects if isinstance(o.node, nodes.ClassDef)]
  138. def classe(self, name):
  139. """return a class by its name, raise KeyError if not found"""
  140. for klass in self.classes():
  141. if klass.node.name == name:
  142. return klass
  143. raise KeyError(name)
  144. def extract_relationships(self):
  145. """extract relation ships between nodes in the diagram"""
  146. for obj in self.classes():
  147. node = obj.node
  148. obj.attrs = self.get_attrs(node)
  149. obj.methods = self.get_methods(node)
  150. # shape
  151. if is_interface(node):
  152. obj.shape = "interface"
  153. else:
  154. obj.shape = "class"
  155. # inheritance link
  156. for par_node in node.ancestors(recurs=False):
  157. try:
  158. par_obj = self.object_from_node(par_node)
  159. self.add_relationship(obj, par_obj, "specialization")
  160. except KeyError:
  161. continue
  162. # implements link
  163. for impl_node in node.implements:
  164. try:
  165. impl_obj = self.object_from_node(impl_node)
  166. self.add_relationship(obj, impl_obj, "implements")
  167. except KeyError:
  168. continue
  169. # associations link
  170. for name, values in list(node.instance_attrs_type.items()) + list(
  171. node.locals_type.items()
  172. ):
  173. for value in values:
  174. if value is astroid.Uninferable:
  175. continue
  176. if isinstance(value, astroid.Instance):
  177. value = value._proxied
  178. try:
  179. associated_obj = self.object_from_node(value)
  180. self.add_relationship(associated_obj, obj, "association", name)
  181. except KeyError:
  182. continue
  183. class PackageDiagram(ClassDiagram):
  184. """package diagram handling"""
  185. TYPE = "package"
  186. def modules(self):
  187. """return all module nodes in the diagram"""
  188. return [o for o in self.objects if isinstance(o.node, nodes.Module)]
  189. def module(self, name):
  190. """return a module by its name, raise KeyError if not found"""
  191. for mod in self.modules():
  192. if mod.node.name == name:
  193. return mod
  194. raise KeyError(name)
  195. def get_module(self, name, node):
  196. """return a module by its name, looking also for relative imports;
  197. raise KeyError if not found
  198. """
  199. for mod in self.modules():
  200. mod_name = mod.node.name
  201. if mod_name == name:
  202. return mod
  203. # search for fullname of relative import modules
  204. package = node.root().name
  205. if mod_name == f"{package}.{name}":
  206. return mod
  207. if mod_name == f"{package.rsplit('.', 1)[0]}.{name}":
  208. return mod
  209. raise KeyError(name)
  210. def add_from_depend(self, node, from_module):
  211. """add dependencies created by from-imports"""
  212. mod_name = node.root().name
  213. obj = self.module(mod_name)
  214. if from_module not in obj.node.depends:
  215. obj.node.depends.append(from_module)
  216. def extract_relationships(self):
  217. """extract relation ships between nodes in the diagram"""
  218. super().extract_relationships()
  219. for obj in self.classes():
  220. # ownership
  221. try:
  222. mod = self.object_from_node(obj.node.root())
  223. self.add_relationship(obj, mod, "ownership")
  224. except KeyError:
  225. continue
  226. for obj in self.modules():
  227. obj.shape = "package"
  228. # dependencies
  229. for dep_name in obj.node.depends:
  230. try:
  231. dep = self.get_module(dep_name, obj.node)
  232. except KeyError:
  233. continue
  234. self.add_relationship(obj, dep, "depends")