| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# |
| 3 |
# SPDX-FileCopyrightText: 2014 Aurélien Gâteau <[email protected]> |
| 4 |
# |
| 5 |
# SPDX-License-Identifier: BSD-2-Clause |
| 6 |
|
| 7 |
from contextlib import contextmanager |
| 8 |
|
| 9 |
|
| 10 |
class Block(object): |
| 11 |
INDENT_SIZE = 4 |
| 12 |
|
| 13 |
def __init__(self, out, depth=0): |
| 14 |
self.out = out |
| 15 |
self.depth = depth |
| 16 |
|
| 17 |
def writeln(self, text): |
| 18 |
self.out.write(self.depth * Block.INDENT_SIZE * " " + text + "\n") |
| 19 |
|
| 20 |
def write_attrs(self, **attrs): |
| 21 |
for key, value in attrs.items(): |
| 22 |
self.writeln(f'"{key}" = "{value}";') |
| 23 |
|
| 24 |
def write_list_attrs(self, name, **attrs): |
| 25 |
with self.square_block(name) as b: |
| 26 |
for key, value in attrs.items(): |
| 27 |
b.writeln(f'"{key}" = "{value}"') |
| 28 |
|
| 29 |
def write_nodes(self, nodes): |
| 30 |
for node in sorted(nodes): |
| 31 |
self.writeln(f'"{node}";') |
| 32 |
|
| 33 |
@contextmanager |
| 34 |
def block(self, opener, closer, **attrs): |
| 35 |
self.writeln(opener) |
| 36 |
block = Block(self.out, depth=self.depth + 1) |
| 37 |
block.write_attrs(**attrs) |
| 38 |
yield block |
| 39 |
self.writeln(closer) |
| 40 |
|
| 41 |
def square_block(self, prefix, **attrs): |
| 42 |
return self.block(prefix + " [", "]", **attrs) |
| 43 |
|
| 44 |
def curly_block(self, prefix, **attrs): |
| 45 |
return self.block(prefix + " {", "}", **attrs) |
| 46 |
|
| 47 |
def cluster_block(self, title, **attrs): |
| 48 |
return self.curly_block("subgraph " + quote("cluster_" + title), label=title, **attrs) |
| 49 |
|
| 50 |
|
| 51 |
def quote(txt): |
| 52 |
return f'"{txt}"' |