1# -*- Mode: Python -*-
2# vi:si:et:sw=4:sts=4:ts=4
3
4"""
5Insert includes for the element-*-details.xml files into the related docbook
6files.
7"""
8
9from __future__ import print_function, unicode_literals
10
11import codecs
12import glob
13import os
14import sys
15
16import xml.dom.minidom
17
18def patch(related, details):
19    try:
20        doc = xml.dom.minidom.parse(related)
21    except IOError:
22        return
23
24    # find the insertion point
25    elem = None
26    for e in doc.childNodes:
27        if e.nodeType == e.ELEMENT_NODE and e.localName == 'refentry':
28            elem = e
29            break
30    if elem == None:
31        return
32
33    elem2 = None
34    for e in elem.childNodes:
35        if e.nodeType == e.ELEMENT_NODE and e.localName == 'refsect1':
36            id = e.getAttributeNode('id')
37            role = e.getAttributeNode('role')
38            if id and id.nodeValue.endswith('.description') and role and role.nodeValue == 'desc':
39                elem2 = e
40                break
41    if elem2 == None:
42        return
43
44    # insert include
45    include = doc.createElement('include')
46    include.setAttribute('xmlns', 'http://www.w3.org/2003/XInclude')
47    include.setAttribute('href', details)
48    fallback = doc.createElement('fallback')
49    fallback.setAttribute('xmlns', 'http://www.w3.org/2003/XInclude')
50    include.appendChild(fallback)
51    elem2.appendChild(include)
52
53    # store patched file
54    result = codecs.open(related, mode="w", encoding="utf-8")
55    #result = open(related, "wb")
56    doc.writexml(result)
57    result.close()
58
59def main():
60    if not len(sys.argv) == 2:
61        sys.stderr.write('Please specify the xml/ dir')
62        sys.exit(1)
63
64    xmldir = sys.argv[1]
65
66    # parse all *-details.xml files and patch includes into the corresponding
67    # xml files
68    for details in glob.glob("%s/element-*-details.xml" % xmldir):
69        patch (details.replace("-details", ""), os.path.basename(details))
70
71main()
72