Debian Codegraph @

cylc/flow/print_tree.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import re
18
19 # Recursively pretty-print a nested dict as a tree
20
21 # Plain ASCII tree characters
22 a_hbar = '-'
23 a_vbar = '|'
24 a_tee = a_vbar + a_hbar
25 a_trm = '`' + a_hbar
26 a_tee_re = r'\|' + a_hbar
27
28 # Unicode box-printing characters
29 u_hbar = '\u2500'
30 u_vbar = '\u2502'
31 u_tee = '\u251C' + u_hbar
32 u_trm = '\u2514' + u_hbar
33
34
35 def get_tree(tree, padding, use_unicode=False, prefix='', labels=None,
36 eq=False, sort=True):
37
38 ret = []
39 if use_unicode:
40 vbar = u_vbar
41 trm = u_trm
42 tee = u_tee
43 tee_re = tee
44 else:
45 vbar = a_vbar
46 trm = a_trm
47 tee = a_tee
48 tee_re = a_tee_re
49
50 keys = list(tree)
51 if sort:
52 keys.sort()
53 # don't sort an ordered-dict tree!
54 for item in keys:
55 if item == keys[-1]:
56 pprefix = prefix + ' ' + trm
57 else:
58 pprefix = prefix + ' ' + tee
59
60 pp = pprefix
61 pp = re.sub('^ (' + trm + '|' + tee_re + ')', '', pp)
62 pp = re.sub(trm + ' ', ' ', pp)
63 pp = re.sub(tee_re + ' ', vbar + ' ', pp)
64
65 result = pp + item
66 line = result + ' ' + padding[len(result):]
67 if isinstance(tree[item], dict):
68 ret.append(line)
69 ret.extend(
70 get_tree(
71 tree[item],
72 padding,
73 use_unicode,
74 pprefix,
75 labels,
76 eq
77 )
78 )
79 else:
80 if labels:
81 if item in labels:
82 reason = labels[item][1]
83 ret.append(f'{line} ... {reason}')
84 else:
85 ret.append(line)
86 else:
87 if eq:
88 joiner = '= '
89 else:
90 joiner = ''
91 ret.append(f'{line}{joiner}{tree[item]}')
92 return ret
93
94
95 def print_tree(*args, **kwargs):
96 print('\n'.join(get_tree(*args, **kwargs)))