dot_printer.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
  4. """Class to generate files in dot format and image formats supported by Graphviz."""
  5. from __future__ import annotations
  6. import os
  7. import subprocess
  8. import tempfile
  9. from enum import Enum
  10. from pathlib import Path
  11. from astroid import nodes
  12. from pylint.pyreverse.printer import EdgeType, Layout, NodeProperties, NodeType, Printer
  13. from pylint.pyreverse.utils import get_annotation_label
  14. class HTMLLabels(Enum):
  15. LINEBREAK_LEFT = '<br ALIGN="LEFT"/>'
  16. ALLOWED_CHARSETS: frozenset[str] = frozenset(("utf-8", "iso-8859-1", "latin1"))
  17. SHAPES: dict[NodeType, str] = {
  18. NodeType.PACKAGE: "box",
  19. NodeType.INTERFACE: "record",
  20. NodeType.CLASS: "record",
  21. }
  22. # pylint: disable-next=consider-using-namedtuple-or-dataclass
  23. ARROWS: dict[EdgeType, dict[str, str]] = {
  24. EdgeType.INHERITS: {"arrowtail": "none", "arrowhead": "empty"},
  25. EdgeType.IMPLEMENTS: {"arrowtail": "node", "arrowhead": "empty", "style": "dashed"},
  26. EdgeType.ASSOCIATION: {
  27. "fontcolor": "green",
  28. "arrowtail": "none",
  29. "arrowhead": "diamond",
  30. "style": "solid",
  31. },
  32. EdgeType.AGGREGATION: {
  33. "fontcolor": "green",
  34. "arrowtail": "none",
  35. "arrowhead": "odiamond",
  36. "style": "solid",
  37. },
  38. EdgeType.USES: {"arrowtail": "none", "arrowhead": "open"},
  39. }
  40. class DotPrinter(Printer):
  41. DEFAULT_COLOR = "black"
  42. def __init__(
  43. self,
  44. title: str,
  45. layout: Layout | None = None,
  46. use_automatic_namespace: bool | None = None,
  47. ):
  48. layout = layout or Layout.BOTTOM_TO_TOP
  49. self.charset = "utf-8"
  50. super().__init__(title, layout, use_automatic_namespace)
  51. def _open_graph(self) -> None:
  52. """Emit the header lines."""
  53. self.emit(f'digraph "{self.title}" {{')
  54. if self.layout:
  55. self.emit(f"rankdir={self.layout.value}")
  56. if self.charset:
  57. assert (
  58. self.charset.lower() in ALLOWED_CHARSETS
  59. ), f"unsupported charset {self.charset}"
  60. self.emit(f'charset="{self.charset}"')
  61. def emit_node(
  62. self,
  63. name: str,
  64. type_: NodeType,
  65. properties: NodeProperties | None = None,
  66. ) -> None:
  67. """Create a new node.
  68. Nodes can be classes, packages, participants etc.
  69. """
  70. if properties is None:
  71. properties = NodeProperties(label=name)
  72. shape = SHAPES[type_]
  73. color = properties.color if properties.color is not None else self.DEFAULT_COLOR
  74. style = "filled" if color != self.DEFAULT_COLOR else "solid"
  75. label = self._build_label_for_node(properties)
  76. label_part = f", label=<{label}>" if label else ""
  77. fontcolor_part = (
  78. f', fontcolor="{properties.fontcolor}"' if properties.fontcolor else ""
  79. )
  80. self.emit(
  81. f'"{name}" [color="{color}"{fontcolor_part}{label_part}, shape="{shape}", style="{style}"];'
  82. )
  83. def _build_label_for_node(self, properties: NodeProperties) -> str:
  84. if not properties.label:
  85. return ""
  86. label: str = properties.label
  87. if properties.attrs is None and properties.methods is None:
  88. # return a "compact" form which only displays the class name in a box
  89. return label
  90. # Add class attributes
  91. attrs: list[str] = properties.attrs or []
  92. attrs_string = rf"{HTMLLabels.LINEBREAK_LEFT.value}".join(
  93. attr.replace("|", r"\|") for attr in attrs
  94. )
  95. label = rf"{{{label}|{attrs_string}{HTMLLabels.LINEBREAK_LEFT.value}|"
  96. # Add class methods
  97. methods: list[nodes.FunctionDef] = properties.methods or []
  98. for func in methods:
  99. args = self._get_method_arguments(func)
  100. method_name = (
  101. f"<I>{func.name}</I>" if func.is_abstract() else f"{func.name}"
  102. )
  103. label += rf"{method_name}({', '.join(args)})"
  104. if func.returns:
  105. annotation_label = get_annotation_label(func.returns)
  106. label += ": " + self._escape_annotation_label(annotation_label)
  107. label += rf"{HTMLLabels.LINEBREAK_LEFT.value}"
  108. label += "}"
  109. return label
  110. def _escape_annotation_label(self, annotation_label: str) -> str:
  111. # Escape vertical bar characters to make them appear as a literal characters
  112. # otherwise it gets treated as field separator of record-based nodes
  113. annotation_label = annotation_label.replace("|", r"\|")
  114. return annotation_label
  115. def emit_edge(
  116. self,
  117. from_node: str,
  118. to_node: str,
  119. type_: EdgeType,
  120. label: str | None = None,
  121. ) -> None:
  122. """Create an edge from one node to another to display relationships."""
  123. arrowstyle = ARROWS[type_]
  124. attrs = [f'{prop}="{value}"' for prop, value in arrowstyle.items()]
  125. if label:
  126. attrs.append(f'label="{label}"')
  127. self.emit(f'"{from_node}" -> "{to_node}" [{", ".join(sorted(attrs))}];')
  128. def generate(self, outputfile: str) -> None:
  129. self._close_graph()
  130. graphviz_extensions = ("dot", "gv")
  131. name = self.title
  132. if outputfile is None:
  133. target = "png"
  134. pdot, dot_sourcepath = tempfile.mkstemp(".gv", name)
  135. ppng, outputfile = tempfile.mkstemp(".png", name)
  136. os.close(pdot)
  137. os.close(ppng)
  138. else:
  139. target = Path(outputfile).suffix.lstrip(".")
  140. if not target:
  141. target = "png"
  142. outputfile = outputfile + "." + target
  143. if target not in graphviz_extensions:
  144. pdot, dot_sourcepath = tempfile.mkstemp(".gv", name)
  145. os.close(pdot)
  146. else:
  147. dot_sourcepath = outputfile
  148. with open(dot_sourcepath, "w", encoding="utf8") as outfile:
  149. outfile.writelines(self.lines)
  150. if target not in graphviz_extensions:
  151. subprocess.run(
  152. ["dot", "-T", target, dot_sourcepath, "-o", outputfile], check=True
  153. )
  154. os.unlink(dot_sourcepath)
  155. def _close_graph(self) -> None:
  156. """Emit the lines needed to properly close the graph."""
  157. self.emit("}\n")