chiark / gitweb /
ef407324d6602fcff4e5274979f3b71e347c9867
[elogind.git] / tools / make-directive-index.py
1 #!/usr/bin/env python3
2 #  -*- Mode: python; coding: utf-8; indent-tabs-mode: nil -*- */
3 # SPDX-License-Identifier: LGPL-2.1+
4 #
5 #  Copyright © 2012-2013 Zbigniew Jędrzejewski-Szmek
6
7 import sys
8 import collections
9 import re
10 from xml_helper import xml_parse, xml_print, tree
11 from copy import deepcopy
12
13 TEMPLATE = '''\
14 <refentry id="elogind.directives" conditional="HAVE_PYTHON">
15
16         <refentryinfo>
17                 <title>elogind.directives</title>
18                 <productname>elogind</productname>
19         </refentryinfo>
20
21         <refmeta>
22                 <refentrytitle>elogind.directives</refentrytitle>
23                 <manvolnum>7</manvolnum>
24         </refmeta>
25
26         <refnamediv>
27                 <refname>elogind.directives</refname>
28                 <refpurpose>Index of configuration directives</refpurpose>
29         </refnamediv>
30
31         <refsect1>
32                 <title>Unit directives</title>
33
34                 <para>Directives for configuring units, used in unit
35                 files.</para>
36
37                 <variablelist id='unit-directives' />
38         </refsect1>
39
40         <refsect1>
41                 <title>Options on the kernel command line</title>
42
43                 <para>Kernel boot options for configuring the behaviour of the
44                 elogind process.</para>
45
46                 <variablelist id='kernel-commandline-options' />
47         </refsect1>
48
49         <refsect1>
50                 <title>Environment variables</title>
51
52                 <para>Environment variables understood by the elogind
53                 manager and other programs.</para>
54
55                 <variablelist id='environment-variables' />
56         </refsect1>
57
58         <refsect1>
59                 <title>UDEV directives</title>
60
61                 <para>Directives for configuring elogind units through the
62                 udev database.</para>
63
64                 <variablelist id='udev-directives' />
65         </refsect1>
66
67         <refsect1>
68                 <title>Network directives</title>
69
70                 <para>Directives for configuring network links through the
71                 net-setup-link udev builtin and networks through
72                 elogind-networkd.</para>
73
74                 <variablelist id='network-directives' />
75         </refsect1>
76
77         <refsect1>
78                 <title>Journal fields</title>
79
80                 <para>Fields in the journal events with a well known meaning.</para>
81
82                 <variablelist id='journal-directives' />
83         </refsect1>
84
85         <refsect1>
86                 <title>PAM configuration directives</title>
87
88                 <para>Directives for configuring PAM behaviour.</para>
89
90                 <variablelist id='pam-directives' />
91         </refsect1>
92
93         <refsect1>
94                 <title><filename>/etc/crypttab</filename> and
95                 <filename>/etc/fstab</filename> options</title>
96
97                 <para>Options which influence mounted filesystems and
98                 encrypted volumes.</para>
99
100                 <variablelist id='fstab-options' />
101         </refsect1>
102
103         <refsect1>
104                 <title>System manager directives</title>
105
106                 <para>Directives for configuring the behaviour of the
107                 elogind process.</para>
108
109                 <variablelist id='elogind-directives' />
110         </refsect1>
111
112         <refsect1>
113                 <title>command line options</title>
114
115                 <para>Command-line options accepted by programs in the
116                 elogind suite.</para>
117
118                 <variablelist id='options' />
119         </refsect1>
120
121         <refsect1>
122                 <title>Constants</title>
123
124                 <para>Various constant used and/or defined by elogind.</para>
125
126                 <variablelist id='constants' />
127         </refsect1>
128
129         <refsect1>
130                 <title>Miscellaneous options and directives</title>
131
132                 <para>Other configuration elements which don't fit in
133                 any of the above groups.</para>
134
135                 <variablelist id='miscellaneous' />
136         </refsect1>
137
138         <refsect1>
139                 <title>Files and directories</title>
140
141                 <para>Paths and file names referred to in the
142                 documentation.</para>
143
144                 <variablelist id='filenames' />
145         </refsect1>
146
147         <refsect1>
148                 <title>Colophon</title>
149                 <para id='colophon' />
150         </refsect1>
151 </refentry>
152 '''
153
154 COLOPHON = '''\
155 This index contains {count} entries in {sections} sections,
156 referring to {pages} individual manual pages.
157 '''
158
159 def _extract_directives(directive_groups, formatting, page):
160     t = xml_parse(page)
161     section = t.find('./refmeta/manvolnum').text
162     pagename = t.find('./refmeta/refentrytitle').text
163
164     storopt = directive_groups['options']
165     for variablelist in t.iterfind('.//variablelist'):
166         klass = variablelist.attrib.get('class')
167         storvar = directive_groups[klass or 'miscellaneous']
168         # <option>s go in OPTIONS, unless class is specified
169         for xpath, stor in (('./varlistentry/term/varname', storvar),
170                             ('./varlistentry/term/option',
171                              storvar if klass else storopt)):
172             for name in variablelist.iterfind(xpath):
173                 text = re.sub(r'([= ]).*', r'\1', name.text).rstrip()
174                 stor[text].append((pagename, section))
175                 if text not in formatting:
176                     # use element as formatted display
177                     if name.text[-1] in '= ':
178                         name.clear()
179                     else:
180                         name.tail = ''
181                     name.text = text
182                     formatting[text] = name
183
184     storfile = directive_groups['filenames']
185     for xpath, absolute_only in (('.//refsynopsisdiv//filename', False),
186                                  ('.//refsynopsisdiv//command', False),
187                                  ('.//filename', True)):
188         for name in t.iterfind(xpath):
189             if absolute_only and not (name.text and name.text.startswith('/')):
190                 continue
191             if name.attrib.get('noindex'):
192                 continue
193             name.tail = ''
194             if name.text:
195                 if name.text.endswith('*'):
196                     name.text = name.text[:-1]
197                 if not name.text.startswith('.'):
198                     text = name.text.partition(' ')[0]
199                     if text != name.text:
200                         name.clear()
201                         name.text = text
202                     if text.endswith('/'):
203                         text = text[:-1]
204                     storfile[text].append((pagename, section))
205                     if text not in formatting:
206                         # use element as formatted display
207                         formatting[text] = name
208             else:
209                 text = ' '.join(name.itertext())
210                 storfile[text].append((pagename, section))
211                 formatting[text] = name
212
213     storfile = directive_groups['constants']
214     for name in t.iterfind('.//constant'):
215         if name.attrib.get('noindex'):
216             continue
217         name.tail = ''
218         if name.text.startswith('('): # a cast, strip it
219             name.text = name.text.partition(' ')[2]
220         storfile[name.text].append((pagename, section))
221         formatting[name.text] = name
222
223 def _make_section(template, name, directives, formatting):
224     varlist = template.find(".//*[@id='{}']".format(name))
225     for varname, manpages in sorted(directives.items()):
226         entry = tree.SubElement(varlist, 'varlistentry')
227         term = tree.SubElement(entry, 'term')
228         display = deepcopy(formatting[varname])
229         term.append(display)
230
231         para = tree.SubElement(tree.SubElement(entry, 'listitem'), 'para')
232
233         b = None
234         for manpage, manvolume in sorted(set(manpages)):
235             if b is not None:
236                 b.tail = ', '
237             b = tree.SubElement(para, 'citerefentry')
238             c = tree.SubElement(b, 'refentrytitle')
239             c.text = manpage
240             c.attrib['target'] = varname
241             d = tree.SubElement(b, 'manvolnum')
242             d.text = manvolume
243         entry.tail = '\n\n'
244
245 def _make_colophon(template, groups):
246     count = 0
247     pages = set()
248     for group in groups:
249         count += len(group)
250         for pagelist in group.values():
251             pages |= set(pagelist)
252
253     para = template.find(".//para[@id='colophon']")
254     para.text = COLOPHON.format(count=count,
255                                 sections=len(groups),
256                                 pages=len(pages))
257
258 def _make_page(template, directive_groups, formatting):
259     """Create an XML tree from directive_groups.
260
261     directive_groups = {
262        'class': {'variable': [('manpage', 'manvolume'), ...],
263                  'variable2': ...},
264        ...
265     }
266     """
267     for name, directives in directive_groups.items():
268         _make_section(template, name, directives, formatting)
269
270     _make_colophon(template, directive_groups.values())
271
272     return template
273
274 def make_page(*xml_files):
275     "Extract directives from xml_files and return XML index tree."
276     template = tree.fromstring(TEMPLATE)
277     names = [vl.get('id') for vl in template.iterfind('.//variablelist')]
278     directive_groups = {name:collections.defaultdict(list)
279                         for name in names}
280     formatting = {}
281     for page in xml_files:
282         try:
283             _extract_directives(directive_groups, formatting, page)
284         except Exception:
285             raise ValueError("failed to process " + page)
286
287     return _make_page(template, directive_groups, formatting)
288
289 if __name__ == '__main__':
290     with open(sys.argv[1], 'wb') as f:
291         f.write(xml_print(make_page(*sys.argv[2:])))