chiark / gitweb /
Prep v228: Silence uninitialized usage warnings.
[elogind.git] / tools / make-directive-index.py
1 #  -*- Mode: python; coding: utf-8; indent-tabs-mode: nil -*- */
2 #
3 #  This file is part of elogind.
4 #
5 #  Copyright 2012-2013 Zbigniew JÄ™drzejewski-Szmek
6 #
7 #  elogind is free software; you can redistribute it and/or modify it
8 #  under the terms of the GNU Lesser General Public License as published by
9 #  the Free Software Foundation; either version 2.1 of the License, or
10 #  (at your option) any later version.
11 #
12 #  elogind is distributed in the hope that it will be useful, but
13 #  WITHOUT ANY WARRANTY; without even the implied warranty of
14 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 #  Lesser General Public License for more details.
16 #
17 #  You should have received a copy of the GNU Lesser General Public License
18 #  along with elogind; If not, see <http://www.gnu.org/licenses/>.
19
20 import sys
21 import collections
22 import re
23 from xml_helper import *
24 from copy import deepcopy
25
26 TEMPLATE = '''\
27 <refentry id="elogind.directives" conditional="HAVE_PYTHON">
28
29         <refentryinfo>
30                 <title>elogind.directives</title>
31                 <productname>elogind</productname>
32
33                 <authorgroup>
34                         <author>
35                                 <contrib>Developer</contrib>
36                                 <firstname>Zbigniew</firstname>
37                                 <surname>JÄ™drzejewski-Szmek</surname>
38                                 <email>zbyszek@in.waw.pl</email>
39                         </author>
40                 </authorgroup>
41         </refentryinfo>
42
43         <refmeta>
44                 <refentrytitle>elogind.directives</refentrytitle>
45                 <manvolnum>7</manvolnum>
46         </refmeta>
47
48         <refnamediv>
49                 <refname>elogind.directives</refname>
50                 <refpurpose>Index of configuration directives</refpurpose>
51         </refnamediv>
52
53         <refsect1>
54                 <title>Environment variables</title>
55
56                 <para>Environment variables understood by the elogind
57                 manager and other programs.</para>
58
59                 <variablelist id='environment-variables' />
60         </refsect1>
61
62         <refsect1>
63                 <title>PAM configuration directives</title>
64
65                 <para>Directives for configuring PAM behaviour.</para>
66
67                 <variablelist id='pam-directives' />
68         </refsect1>
69
70         <refsect1>
71                 <title>command line options</title>
72
73                 <para>Command-line options accepted by programs in the
74                 elogind suite.</para>
75
76                 <variablelist id='options' />
77         </refsect1>
78
79         <refsect1>
80                 <title>Constants</title>
81
82                 <para>Various constant used and/or defined by elogind.</para>
83
84                 <variablelist id='constants' />
85         </refsect1>
86
87         <refsect1>
88                 <title>Miscellaneous options and directives</title>
89
90                 <para>Other configuration elements which don't fit in
91                 any of the above groups.</para>
92
93                 <variablelist id='miscellaneous' />
94         </refsect1>
95
96         <refsect1>
97                 <title>Files and directories</title>
98
99                 <para>Paths and file names referred to in the
100                 documentation.</para>
101
102                 <variablelist id='filenames' />
103         </refsect1>
104
105         <refsect1>
106                 <title>Colophon</title>
107                 <para id='colophon' />
108         </refsect1>
109 </refentry>
110 '''
111
112 COLOPHON = '''\
113 This index contains {count} entries in {sections} sections,
114 referring to {pages} individual manual pages.
115 '''
116
117 def _extract_directives(directive_groups, formatting, page):
118     t = xml_parse(page)
119     section = t.find('./refmeta/manvolnum').text
120     pagename = t.find('./refmeta/refentrytitle').text
121
122     storopt = directive_groups['options']
123     for variablelist in t.iterfind('.//variablelist'):
124         klass = variablelist.attrib.get('class')
125         storvar = directive_groups[klass or 'miscellaneous']
126         # <option>s go in OPTIONS, unless class is specified
127         for xpath, stor in (('./varlistentry/term/varname', storvar),
128                             ('./varlistentry/term/option',
129                              storvar if klass else storopt)):
130             for name in variablelist.iterfind(xpath):
131                 text = re.sub(r'([= ]).*', r'\1', name.text).rstrip()
132                 stor[text].append((pagename, section))
133                 if text not in formatting:
134                     # use element as formatted display
135                     if name.text[-1] in '= ':
136                         name.clear()
137                     else:
138                         name.tail = ''
139                     name.text = text
140                     formatting[text] = name
141
142     storfile = directive_groups['filenames']
143     for xpath, absolute_only in (('.//refsynopsisdiv//filename', False),
144                                  ('.//refsynopsisdiv//command', False),
145                                  ('.//filename', True)):
146         for name in t.iterfind(xpath):
147             if absolute_only and not (name.text and name.text.startswith('/')):
148                 continue
149             if name.attrib.get('noindex'):
150                 continue
151             name.tail = ''
152             if name.text:
153                 if name.text.endswith('*'):
154                     name.text = name.text[:-1]
155                 if not name.text.startswith('.'):
156                     text = name.text.partition(' ')[0]
157                     if text != name.text:
158                         name.clear()
159                         name.text = text
160                     if text.endswith('/'):
161                         text = text[:-1]
162                     storfile[text].append((pagename, section))
163                     if text not in formatting:
164                         # use element as formatted display
165                         formatting[text] = name
166             else:
167                 text = ' '.join(name.itertext())
168                 storfile[text].append((pagename, section))
169                 formatting[text] = name
170
171     storfile = directive_groups['constants']
172     for name in t.iterfind('.//constant'):
173         if name.attrib.get('noindex'):
174             continue
175         name.tail = ''
176         if name.text.startswith('('): # a cast, strip it
177             name.text = name.text.partition(' ')[2]
178         storfile[name.text].append((pagename, section))
179         formatting[name.text] = name
180
181 def _make_section(template, name, directives, formatting):
182     varlist = template.find(".//*[@id='{}']".format(name))
183     for varname, manpages in sorted(directives.items()):
184         entry = tree.SubElement(varlist, 'varlistentry')
185         term = tree.SubElement(entry, 'term')
186         display = deepcopy(formatting[varname])
187         term.append(display)
188
189         para = tree.SubElement(tree.SubElement(entry, 'listitem'), 'para')
190
191         b = None
192         for manpage, manvolume in sorted(set(manpages)):
193             if b is not None:
194                 b.tail = ', '
195             b = tree.SubElement(para, 'citerefentry')
196             c = tree.SubElement(b, 'refentrytitle')
197             c.text = manpage
198             d = tree.SubElement(b, 'manvolnum')
199             d.text = manvolume
200         entry.tail = '\n\n'
201
202 def _make_colophon(template, groups):
203     count = 0
204     pages = set()
205     for group in groups:
206         count += len(group)
207         for pagelist in group.values():
208             pages |= set(pagelist)
209
210     para = template.find(".//para[@id='colophon']")
211     para.text = COLOPHON.format(count=count,
212                                 sections=len(groups),
213                                 pages=len(pages))
214
215 def _make_page(template, directive_groups, formatting):
216     """Create an XML tree from directive_groups.
217
218     directive_groups = {
219        'class': {'variable': [('manpage', 'manvolume'), ...],
220                  'variable2': ...},
221        ...
222     }
223     """
224     for name, directives in directive_groups.items():
225         _make_section(template, name, directives, formatting)
226
227     _make_colophon(template, directive_groups.values())
228
229     return template
230
231 def make_page(*xml_files):
232     "Extract directives from xml_files and return XML index tree."
233     template = tree.fromstring(TEMPLATE)
234     names = [vl.get('id') for vl in template.iterfind('.//variablelist')]
235     directive_groups = {name:collections.defaultdict(list)
236                         for name in names}
237     formatting = {}
238     for page in xml_files:
239         try:
240             _extract_directives(directive_groups, formatting, page)
241         except Exception:
242             raise ValueError("failed to process " + page)
243
244     return _make_page(template, directive_groups, formatting)
245
246 if __name__ == '__main__':
247     with open(sys.argv[1], 'wb') as f:
248         f.write(xml_print(make_page(*sys.argv[2:])))