]> git.ipfire.org Git - thirdparty/systemd.git/blame - tools/update-dbus-docs.py
update-dbus-docs: skip test if python is too old
[thirdparty/systemd.git] / tools / update-dbus-docs.py
CommitLineData
e5dd26cc
ZJS
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-2.1+
3
0f5cea02 4import argparse
e5dd26cc
ZJS
5import collections
6import sys
c351d568 7import os
e5dd26cc
ZJS
8import subprocess
9import io
e5dd26cc 10
8aaf611b
ZJS
11try:
12 from lxml import etree
13except ModuleNotFoundError as e:
14 etree = e
e5dd26cc 15
198fda4f
ZJS
16try:
17 from shlex import join as shlex_join
18except ImportError as e:
19 shlex_join = e
20
e5dd26cc
ZJS
21class NoCommand(Exception):
22 pass
23
e5dd26cc
ZJS
24BORING_INTERFACES = [
25 'org.freedesktop.DBus.Peer',
26 'org.freedesktop.DBus.Introspectable',
27 'org.freedesktop.DBus.Properties',
28]
29
8aaf611b
ZJS
30def xml_parser():
31 return etree.XMLParser(no_network=True,
32 remove_comments=False,
33 strip_cdata=False,
34 resolve_entities=False)
35
e5dd26cc
ZJS
36def print_method(declarations, elem, *, prefix, file, is_signal=False):
37 name = elem.get('name')
38 klass = 'signal' if is_signal else 'method'
39 declarations[klass].append(name)
40
41 print(f'''{prefix}{name}(''', file=file, end='')
42 lead = ',\n' + prefix + ' ' * len(name) + ' '
43
44 for num, arg in enumerate(elem.findall('./arg')):
45 argname = arg.get('name')
46
47 if argname is None:
04aa6fa8 48 if opts.print_errors:
e5dd26cc
ZJS
49 print(f'method {name}: argument {num+1} has no name', file=sys.stderr)
50 argname = 'UNNAMED'
51
52 type = arg.get('type')
53 if not is_signal:
54 direction = arg.get('direction')
55 print(f'''{lead if num > 0 else ''}{direction:3} {type} {argname}''', file=file, end='')
56 else:
57 print(f'''{lead if num > 0 else ''}{type} {argname}''', file=file, end='')
58
59 print(f');', file=file)
60
61ACCESS_MAP = {
62 'read' : 'readonly',
63 'write' : 'readwrite',
64}
65
66def value_ellipsis(type):
67 if type == 's':
68 return "'...'";
69 if type[0] == 'a':
70 inner = value_ellipsis(type[1:])
71 return f"[{inner}{', ...' if inner != '...' else ''}]";
72 return '...'
73
74def print_property(declarations, elem, *, prefix, file):
75 name = elem.get('name')
76 type = elem.get('type')
77 access = elem.get('access')
78
79 declarations['property'].append(name)
80
81 # @org.freedesktop.DBus.Property.EmitsChangedSignal("false")
82 # @org.freedesktop.systemd1.Privileged("true")
83 # readwrite b EnableWallMessages = false;
84
85 for anno in elem.findall('./annotation'):
86 anno_name = anno.get('name')
87 anno_value = anno.get('value')
88 print(f'''{prefix}@{anno_name}("{anno_value}")''', file=file)
89
90 access = ACCESS_MAP.get(access, access)
91 print(f'''{prefix}{access} {type} {name} = {value_ellipsis(type)};''', file=file)
92
08fe1b6c 93def print_interface(iface, *, prefix, file, print_boring, only_interface, declarations):
e5dd26cc
ZJS
94 name = iface.get('name')
95
08fe1b6c
ZJS
96 is_boring = (name in BORING_INTERFACES or
97 only_interface is not None and name != only_interface)
98
e5dd26cc
ZJS
99 if is_boring and print_boring:
100 print(f'''{prefix}interface {name} {{ ... }};''', file=file)
08fe1b6c 101
e5dd26cc
ZJS
102 elif not is_boring and not print_boring:
103 print(f'''{prefix}interface {name} {{''', file=file)
104 prefix2 = prefix + ' '
105
106 for num, elem in enumerate(iface.findall('./method')):
107 if num == 0:
108 print(f'''{prefix2}methods:''', file=file)
109 print_method(declarations, elem, prefix=prefix2 + ' ', file=file)
110
111 for num, elem in enumerate(iface.findall('./signal')):
112 if num == 0:
113 print(f'''{prefix2}signals:''', file=file)
114 print_method(declarations, elem, prefix=prefix2 + ' ', file=file, is_signal=True)
115
116 for num, elem in enumerate(iface.findall('./property')):
117 if num == 0:
118 print(f'''{prefix2}properties:''', file=file)
119 print_property(declarations, elem, prefix=prefix2 + ' ', file=file)
120
121 print(f'''{prefix}}};''', file=file)
122
123def document_has_elem_with_text(document, elem, item_repr):
124 predicate = f".//{elem}" # [text() = 'foo'] doesn't seem supported :(
125 for loc in document.findall(predicate):
126 if loc.text == item_repr:
127 return True
128 else:
129 return False
130
af4c7dc2 131def check_documented(document, declarations, stats):
e5dd26cc
ZJS
132 missing = []
133 for klass, items in declarations.items():
af4c7dc2
ZJS
134 stats['total'] += len(items)
135
e5dd26cc
ZJS
136 for item in items:
137 if klass == 'method':
138 elem = 'function'
139 item_repr = f'{item}()'
140 elif klass == 'signal':
141 elem = 'function'
142 item_repr = item
143 elif klass == 'property':
144 elem = 'varname'
145 item_repr = item
146 else:
147 assert False, (klass, item)
148
149 if not document_has_elem_with_text(document, elem, item_repr):
04aa6fa8 150 if opts.print_errors:
e5dd26cc
ZJS
151 print(f'{klass} {item} is not documented :(')
152 missing.append((klass, item))
153
af4c7dc2
ZJS
154 stats['missing'] += len(missing)
155
e5dd26cc
ZJS
156 return missing
157
08fe1b6c 158def xml_to_text(destination, xml, *, only_interface=None):
e5dd26cc
ZJS
159 file = io.StringIO()
160
161 declarations = collections.defaultdict(list)
f92c8d1c 162 interfaces = []
e5dd26cc
ZJS
163
164 print(f'''node {destination} {{''', file=file)
165
166 for print_boring in [False, True]:
167 for iface in xml.findall('./interface'):
168 print_interface(iface, prefix=' ', file=file,
169 print_boring=print_boring,
08fe1b6c 170 only_interface=only_interface,
e5dd26cc 171 declarations=declarations)
f92c8d1c
JR
172 name = iface.get('name')
173 if not name in BORING_INTERFACES:
174 interfaces.append(name)
e5dd26cc
ZJS
175
176 print(f'''}};''', file=file)
177
f92c8d1c 178 return file.getvalue(), declarations, interfaces
e5dd26cc 179
af4c7dc2 180def subst_output(document, programlisting, stats):
c351d568
ZJS
181 executable = programlisting.get('executable', None)
182 if executable is None:
183 # Not our thing
e5dd26cc 184 return
c351d568
ZJS
185 executable = programlisting.get('executable')
186 node = programlisting.get('node')
187 interface = programlisting.get('interface')
e5dd26cc 188
0f5cea02 189 argv = [f'{opts.build_dir}/{executable}', f'--bus-introspect={interface}']
198fda4f 190 print(f'COMMAND: {shlex_join(argv)}')
e5dd26cc 191
e5dd26cc
ZJS
192 try:
193 out = subprocess.check_output(argv, text=True)
c351d568
ZJS
194 except FileNotFoundError:
195 print(f'{executable} not found, ignoring', file=sys.stderr)
e5dd26cc
ZJS
196 return
197
8aaf611b 198 xml = etree.fromstring(out, parser=xml_parser())
e5dd26cc 199
c351d568
ZJS
200 new_text, declarations, interfaces = xml_to_text(node, xml, only_interface=interface)
201 programlisting.text = '\n' + new_text + ' '
e5dd26cc
ZJS
202
203 if declarations:
af4c7dc2 204 missing = check_documented(document, declarations, stats)
e5dd26cc
ZJS
205 parent = programlisting.getparent()
206
207 # delete old comments
208 for child in parent:
f92c8d1c
JR
209 if (child.tag == etree.Comment
210 and 'Autogenerated' in child.text):
211 parent.remove(child)
e5dd26cc
ZJS
212 if (child.tag == etree.Comment
213 and 'not documented' in child.text):
214 parent.remove(child)
f92c8d1c
JR
215 if (child.tag == "variablelist"
216 and child.attrib.get("generated",False) == "True"):
217 parent.remove(child)
218
219 # insert pointer for systemd-directives generation
220 the_tail = programlisting.tail #tail is erased by addnext, so save it here.
221 prev_element = etree.Comment("Autogenerated cross-references for systemd.directives, do not edit")
222 programlisting.addnext(prev_element)
223 programlisting.tail = the_tail
224
225 for interface in interfaces:
226 variablelist = etree.Element("variablelist")
227 variablelist.attrib['class'] = 'dbus-interface'
228 variablelist.attrib['generated'] = 'True'
229 variablelist.attrib['extra-ref'] = interface
230
231 prev_element.addnext(variablelist)
232 prev_element.tail = the_tail
233 prev_element = variablelist
234
235 for decl_type,decl_list in declarations.items():
236 for declaration in decl_list:
237 variablelist = etree.Element("variablelist")
238 variablelist.attrib['class'] = 'dbus-'+decl_type
239 variablelist.attrib['generated'] = 'True'
240 if decl_type == 'method' :
241 variablelist.attrib['extra-ref'] = declaration + '()'
242 else:
243 variablelist.attrib['extra-ref'] = declaration
244
245 prev_element.addnext(variablelist)
246 prev_element.tail = the_tail
247 prev_element = variablelist
248
249 last_element = etree.Comment("End of Autogenerated section")
250 prev_element.addnext(last_element)
251 prev_element.tail = the_tail
252 last_element.tail = the_tail
e5dd26cc
ZJS
253
254 # insert comments for undocumented items
255 for item in reversed(missing):
256 comment = etree.Comment(f'{item[0]} {item[1]} is not documented!')
257 comment.tail = programlisting.tail
258 parent.insert(parent.index(programlisting) + 1, comment)
259
260def process(page):
261 src = open(page).read()
8aaf611b 262 xml = etree.fromstring(src, parser=xml_parser())
e5dd26cc
ZJS
263
264 # print('parsing {}'.format(name), file=sys.stderr)
265 if xml.tag != 'refentry':
266 return
267
af4c7dc2
ZJS
268 stats = collections.Counter()
269
e5dd26cc
ZJS
270 pls = xml.findall('.//programlisting')
271 for pl in pls:
af4c7dc2 272 subst_output(xml, pl, stats)
e5dd26cc
ZJS
273
274 out_text = etree.tostring(xml, encoding='unicode')
86b52a39 275 # massage format to avoid some lxml whitespace handling idiosyncrasies
e5dd26cc
ZJS
276 # https://bugs.launchpad.net/lxml/+bug/526799
277 out_text = (src[:src.find('<refentryinfo')] +
278 out_text[out_text.find('<refentryinfo'):] +
279 '\n')
280
1b584f38
ZJS
281 if not opts.test:
282 with open(page, 'w') as out:
283 out.write(out_text)
e5dd26cc 284
1b584f38 285 return dict(stats=stats, outdated=(out_text != src))
af4c7dc2 286
0f5cea02
ZJS
287def parse_args():
288 p = argparse.ArgumentParser()
1b584f38
ZJS
289 p.add_argument('--test', action='store_true',
290 help='only verify that everything is up2date')
0f5cea02
ZJS
291 p.add_argument('--build-dir', default='build')
292 p.add_argument('pages', nargs='+')
04aa6fa8
ZJS
293 opts = p.parse_args()
294 opts.print_errors = not opts.test
295 return opts
e5dd26cc 296
0f5cea02
ZJS
297if __name__ == '__main__':
298 opts = parse_args()
c351d568 299
198fda4f
ZJS
300 for item in (etree, shlex_join):
301 if isinstance(item, Exception):
302 print(item, file=sys.stderr)
303 exit(77 if opts.test else 1)
8aaf611b 304
0f5cea02
ZJS
305 if not os.path.exists(f'{opts.build_dir}/systemd'):
306 exit(f"{opts.build_dir}/systemd doesn't exist. Use --build-dir=.")
c351d568 307
0f5cea02 308 stats = {page.split('/')[-1] : process(page) for page in opts.pages}
af4c7dc2
ZJS
309
310 # Let's print all statistics at the end
311 mlen = max(len(page) for page in stats)
1b584f38
ZJS
312 total = sum((item['stats'] for item in stats.values()), start=collections.Counter())
313 total = 'total', dict(stats=total, outdated=False)
314 outdated = []
315 for page, info in sorted(stats.items()) + [total]:
316 m = info['stats']['missing']
317 t = info['stats']['total']
af4c7dc2 318 p = page + ':'
1b584f38
ZJS
319 c = 'OUTDATED' if info['outdated'] else ''
320 if c:
321 outdated.append(page)
322 print(f'{p:{mlen + 1}} {t - m}/{t} {c}')
323
324 if opts.test and outdated:
c91e3116
ZJS
325 exit(f'Outdated pages: {", ".join(outdated)}\n'
326 f'Hint: ninja -C {opts.build_dir} man/update-dbus-docs')