blob: 2f69b50b89c3c98f6f0fc1f0b3c6ed6a07627220 [file] [log] [blame]
Zbigniew Jędrzejewski-Szmeke5dd26c2020-04-07 16:58:58 +02001#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-2.1+
3
4import collections
5import sys
6import shlex
7import subprocess
8import io
9import pprint
10from lxml import etree
11
12PARSER = etree.XMLParser(no_network=True,
13 remove_comments=False,
14 strip_cdata=False,
15 resolve_entities=False)
16
17PRINT_ERRORS = True
18
19class NoCommand(Exception):
20 pass
21
22def find_command(lines):
23 acc = []
24 for num, line in enumerate(lines):
25 # skip empty leading line
26 if num == 0 and not line:
27 continue
28 cont = line.endswith('\\')
29 if cont:
30 line = line[:-1].rstrip()
31 acc.append(line if not acc else line.lstrip())
32 if not cont:
33 break
34 joined = ' '.join(acc)
35 if not joined.startswith('$ '):
36 raise NoCommand
37 return joined[2:], lines[:num+1] + [''], lines[-1]
38
39BORING_INTERFACES = [
40 'org.freedesktop.DBus.Peer',
41 'org.freedesktop.DBus.Introspectable',
42 'org.freedesktop.DBus.Properties',
43]
44
45def print_method(declarations, elem, *, prefix, file, is_signal=False):
46 name = elem.get('name')
47 klass = 'signal' if is_signal else 'method'
48 declarations[klass].append(name)
49
50 print(f'''{prefix}{name}(''', file=file, end='')
51 lead = ',\n' + prefix + ' ' * len(name) + ' '
52
53 for num, arg in enumerate(elem.findall('./arg')):
54 argname = arg.get('name')
55
56 if argname is None:
57 if PRINT_ERRORS:
58 print(f'method {name}: argument {num+1} has no name', file=sys.stderr)
59 argname = 'UNNAMED'
60
61 type = arg.get('type')
62 if not is_signal:
63 direction = arg.get('direction')
64 print(f'''{lead if num > 0 else ''}{direction:3} {type} {argname}''', file=file, end='')
65 else:
66 print(f'''{lead if num > 0 else ''}{type} {argname}''', file=file, end='')
67
68 print(f');', file=file)
69
70ACCESS_MAP = {
71 'read' : 'readonly',
72 'write' : 'readwrite',
73}
74
75def value_ellipsis(type):
76 if type == 's':
77 return "'...'";
78 if type[0] == 'a':
79 inner = value_ellipsis(type[1:])
80 return f"[{inner}{', ...' if inner != '...' else ''}]";
81 return '...'
82
83def print_property(declarations, elem, *, prefix, file):
84 name = elem.get('name')
85 type = elem.get('type')
86 access = elem.get('access')
87
88 declarations['property'].append(name)
89
90 # @org.freedesktop.DBus.Property.EmitsChangedSignal("false")
91 # @org.freedesktop.systemd1.Privileged("true")
92 # readwrite b EnableWallMessages = false;
93
94 for anno in elem.findall('./annotation'):
95 anno_name = anno.get('name')
96 anno_value = anno.get('value')
97 print(f'''{prefix}@{anno_name}("{anno_value}")''', file=file)
98
99 access = ACCESS_MAP.get(access, access)
100 print(f'''{prefix}{access} {type} {name} = {value_ellipsis(type)};''', file=file)
101
102def print_interface(iface, *, prefix, file, print_boring, declarations):
103 name = iface.get('name')
104
105 is_boring = name in BORING_INTERFACES
106 if is_boring and print_boring:
107 print(f'''{prefix}interface {name} {{ ... }};''', file=file)
108 elif not is_boring and not print_boring:
109 print(f'''{prefix}interface {name} {{''', file=file)
110 prefix2 = prefix + ' '
111
112 for num, elem in enumerate(iface.findall('./method')):
113 if num == 0:
114 print(f'''{prefix2}methods:''', file=file)
115 print_method(declarations, elem, prefix=prefix2 + ' ', file=file)
116
117 for num, elem in enumerate(iface.findall('./signal')):
118 if num == 0:
119 print(f'''{prefix2}signals:''', file=file)
120 print_method(declarations, elem, prefix=prefix2 + ' ', file=file, is_signal=True)
121
122 for num, elem in enumerate(iface.findall('./property')):
123 if num == 0:
124 print(f'''{prefix2}properties:''', file=file)
125 print_property(declarations, elem, prefix=prefix2 + ' ', file=file)
126
127 print(f'''{prefix}}};''', file=file)
128
129def document_has_elem_with_text(document, elem, item_repr):
130 predicate = f".//{elem}" # [text() = 'foo'] doesn't seem supported :(
131 for loc in document.findall(predicate):
132 if loc.text == item_repr:
133 return True
134 else:
135 return False
136
137def check_documented(document, declarations):
138 missing = []
139 for klass, items in declarations.items():
140 for item in items:
141 if klass == 'method':
142 elem = 'function'
143 item_repr = f'{item}()'
144 elif klass == 'signal':
145 elem = 'function'
146 item_repr = item
147 elif klass == 'property':
148 elem = 'varname'
149 item_repr = item
150 else:
151 assert False, (klass, item)
152
153 if not document_has_elem_with_text(document, elem, item_repr):
154 if PRINT_ERRORS:
155 print(f'{klass} {item} is not documented :(')
156 missing.append((klass, item))
157
158 return missing
159
160def xml_to_text(destination, xml):
161 file = io.StringIO()
162
163 declarations = collections.defaultdict(list)
164
165 print(f'''node {destination} {{''', file=file)
166
167 for print_boring in [False, True]:
168 for iface in xml.findall('./interface'):
169 print_interface(iface, prefix=' ', file=file,
170 print_boring=print_boring,
171 declarations=declarations)
172
173 print(f'''}};''', file=file)
174
175 return file.getvalue(), declarations
176
177def subst_output(document, programlisting):
178 try:
179 cmd, prefix_lines, footer = find_command(programlisting.text.splitlines())
180 except NoCommand:
181 return
182
183 argv = shlex.split(cmd)
184 argv += ['--xml']
185 print(f'COMMAND: {shlex.join(argv)}')
186
187 object_idx = argv.index('--object-path')
188 object_path = argv[object_idx + 1]
189
190 try:
191 out = subprocess.check_output(argv, text=True)
192 except subprocess.CalledProcessError:
193 print('command failed, ignoring', file=sys.stderr)
194 return
195
196 xml = etree.fromstring(out, parser=PARSER)
197
198 new_text, declarations = xml_to_text(object_path, xml)
199
200 programlisting.text = '\n'.join(prefix_lines) + '\n' + new_text + footer
201
202 if declarations:
203 missing = check_documented(document, declarations)
204 parent = programlisting.getparent()
205
206 # delete old comments
207 for child in parent:
208 if (child.tag == etree.Comment
209 and 'not documented' in child.text):
210 parent.remove(child)
211
212 # insert comments for undocumented items
213 for item in reversed(missing):
214 comment = etree.Comment(f'{item[0]} {item[1]} is not documented!')
215 comment.tail = programlisting.tail
216 parent.insert(parent.index(programlisting) + 1, comment)
217
218def process(page):
219 src = open(page).read()
220 xml = etree.fromstring(src, parser=PARSER)
221
222 # print('parsing {}'.format(name), file=sys.stderr)
223 if xml.tag != 'refentry':
224 return
225
226 pls = xml.findall('.//programlisting')
227 for pl in pls:
228 subst_output(xml, pl)
229
230 out_text = etree.tostring(xml, encoding='unicode')
231 # massage format to avoid some lxml whitespace handling idiosyncracies
232 # https://bugs.launchpad.net/lxml/+bug/526799
233 out_text = (src[:src.find('<refentryinfo')] +
234 out_text[out_text.find('<refentryinfo'):] +
235 '\n')
236
237 with open(page, 'w') as out:
238 out.write(out_text)
239
240if __name__ == '__main__':
241 pages = sys.argv[1:]
242
243 for page in pages:
244 process(page)