|
| 1 | +# Copyright (c) 2021 Andreas Finkler <[email protected]> |
| 2 | + |
| 3 | +# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html |
| 4 | +# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE |
| 5 | + |
| 6 | +""" |
| 7 | +Class to generate files in dot format and image formats supported by Graphviz. |
| 8 | +""" |
| 9 | +import os |
| 10 | +import subprocess |
| 11 | +import sys |
| 12 | +import tempfile |
| 13 | +from pathlib import Path |
| 14 | +from typing import Dict, FrozenSet, Optional |
| 15 | + |
| 16 | +from pylint.pyreverse.printer import EdgeType, Layout, NodeProperties, NodeType, Printer |
| 17 | +from pylint.pyreverse.utils import check_graphviz_availability |
| 18 | + |
| 19 | +ALLOWED_CHARSETS: FrozenSet[str] = frozenset(("utf-8", "iso-8859-1", "latin1")) |
| 20 | +SHAPES: Dict[NodeType, str] = { |
| 21 | + NodeType.PACKAGE: "box", |
| 22 | + NodeType.INTERFACE: "record", |
| 23 | + NodeType.CLASS: "record", |
| 24 | +} |
| 25 | +ARROWS: Dict[EdgeType, Dict] = { |
| 26 | + EdgeType.INHERITS: dict(arrowtail="none", arrowhead="empty"), |
| 27 | + EdgeType.IMPLEMENTS: dict(arrowtail="node", arrowhead="empty", style="dashed"), |
| 28 | + EdgeType.ASSOCIATION: dict( |
| 29 | + fontcolor="green", arrowtail="none", arrowhead="diamond", style="solid" |
| 30 | + ), |
| 31 | + EdgeType.USES: dict(arrowtail="none", arrowhead="open"), |
| 32 | +} |
| 33 | + |
| 34 | + |
| 35 | +class DotPrinter(Printer): |
| 36 | + def __init__( |
| 37 | + self, |
| 38 | + title: str, |
| 39 | + layout: Optional[Layout] = None, |
| 40 | + use_automatic_namespace: Optional[bool] = None, |
| 41 | + ): |
| 42 | + self.charset = "utf-8" |
| 43 | + self.node_style = "solid" |
| 44 | + super().__init__(title, layout, use_automatic_namespace) |
| 45 | + |
| 46 | + def _open_graph(self) -> None: |
| 47 | + """Emit the header lines""" |
| 48 | + self.emit(f'digraph "{self.title}" {{') |
| 49 | + if self.layout: |
| 50 | + self.emit(f"rankdir={self.layout.value}") |
| 51 | + if self.charset: |
| 52 | + assert ( |
| 53 | + self.charset.lower() in ALLOWED_CHARSETS |
| 54 | + ), f"unsupported charset {self.charset}" |
| 55 | + self.emit(f'charset="{self.charset}"') |
| 56 | + |
| 57 | + def emit_node( |
| 58 | + self, |
| 59 | + name: str, |
| 60 | + type_: NodeType, |
| 61 | + properties: Optional[NodeProperties] = None, |
| 62 | + ) -> None: |
| 63 | + """Create a new node. Nodes can be classes, packages, participants etc.""" |
| 64 | + if properties is None: |
| 65 | + properties = NodeProperties(label=name) |
| 66 | + shape = SHAPES[type_] |
| 67 | + color = properties.color if properties.color is not None else "black" |
| 68 | + label = properties.label |
| 69 | + if label: |
| 70 | + if type_ is NodeType.INTERFACE: |
| 71 | + label = "<<interface>>\\n" + label |
| 72 | + label_part = f', label="{label}"' |
| 73 | + else: |
| 74 | + label_part = "" |
| 75 | + fontcolor_part = ( |
| 76 | + f', fontcolor="{properties.fontcolor}"' if properties.fontcolor else "" |
| 77 | + ) |
| 78 | + self.emit( |
| 79 | + f'"{name}" [color="{color}"{fontcolor_part}{label_part}, shape="{shape}", style="{self.node_style}"];' |
| 80 | + ) |
| 81 | + |
| 82 | + def emit_edge( |
| 83 | + self, |
| 84 | + from_node: str, |
| 85 | + to_node: str, |
| 86 | + type_: EdgeType, |
| 87 | + label: Optional[str] = None, |
| 88 | + ) -> None: |
| 89 | + """Create an edge from one node to another to display relationships.""" |
| 90 | + arrowstyle = ARROWS[type_] |
| 91 | + attrs = [f'{prop}="{value}"' for prop, value in arrowstyle.items()] |
| 92 | + if label: |
| 93 | + attrs.append(f'label="{label}"') |
| 94 | + self.emit(f'"{from_node}" -> "{to_node}" [{", ".join(sorted(attrs))}];') |
| 95 | + |
| 96 | + def generate(self, outputfile: str) -> None: |
| 97 | + self._close_graph() |
| 98 | + graphviz_extensions = ("dot", "gv") |
| 99 | + name = self.title |
| 100 | + if outputfile is None: |
| 101 | + target = "png" |
| 102 | + pdot, dot_sourcepath = tempfile.mkstemp(".gv", name) |
| 103 | + ppng, outputfile = tempfile.mkstemp(".png", name) |
| 104 | + os.close(pdot) |
| 105 | + os.close(ppng) |
| 106 | + else: |
| 107 | + target = Path(outputfile).suffix.lstrip(".") |
| 108 | + if not target: |
| 109 | + target = "png" |
| 110 | + outputfile = outputfile + "." + target |
| 111 | + if target not in graphviz_extensions: |
| 112 | + pdot, dot_sourcepath = tempfile.mkstemp(".gv", name) |
| 113 | + os.close(pdot) |
| 114 | + else: |
| 115 | + dot_sourcepath = outputfile |
| 116 | + with open(dot_sourcepath, "w", encoding="utf8") as outfile: |
| 117 | + outfile.writelines(self.lines) |
| 118 | + if target not in graphviz_extensions: |
| 119 | + check_graphviz_availability() |
| 120 | + use_shell = sys.platform == "win32" |
| 121 | + subprocess.call( |
| 122 | + ["dot", "-T", target, dot_sourcepath, "-o", outputfile], |
| 123 | + shell=use_shell, |
| 124 | + ) |
| 125 | + os.unlink(dot_sourcepath) |
| 126 | + |
| 127 | + def _close_graph(self) -> None: |
| 128 | + """Emit the lines needed to properly close the graph.""" |
| 129 | + self.emit("}\n") |
0 commit comments