summaryrefslogtreecommitdiff
path: root/mangle-db.py
blob: 463e5bc50ceeae3e743a1668e4b0ba0ad7868918 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4

"""
Insert includes for the element-*-details.xml files into the related docbook
files.
"""

from __future__ import print_function, unicode_literals

import codecs
import glob
import os
import sys

import xml.dom.minidom

def patch(related, details):
    try:
        doc = xml.dom.minidom.parse(related)
    except IOError:
        return

    # find the insertion point
    elem = None
    for e in doc.childNodes:
        if e.nodeType == e.ELEMENT_NODE and e.localName == 'refentry':
            elem = e
            break
    if elem == None:
        return

    elem2 = None
    for e in elem.childNodes:
        if e.nodeType == e.ELEMENT_NODE and e.localName == 'refsect1':
            id = e.getAttributeNode('id')
            role = e.getAttributeNode('role')
            if id and id.nodeValue.endswith('.description') and role and role.nodeValue == 'desc':
                elem2 = e
                break
    if elem2 == None:
        return

    # insert include
    include = doc.createElement('include')
    include.setAttribute('xmlns', 'http://www.w3.org/2003/XInclude')
    include.setAttribute('href', details)
    fallback = doc.createElement('fallback')
    fallback.setAttribute('xmlns', 'http://www.w3.org/2003/XInclude')
    include.appendChild(fallback)
    elem2.appendChild(include)

    # store patched file
    result = codecs.open(related, mode="w", encoding="utf-8")
    #result = open(related, "wb")
    doc.writexml(result)
    result.close()

def main():
    if not len(sys.argv) == 2:
        sys.stderr.write('Please specify the xml/ dir')
        sys.exit(1)

    xmldir = sys.argv[1]

    # parse all *-details.xml files and patch includes into the corresponding
    # xml files
    for details in glob.glob("%s/element-*-details.xml" % xmldir):
        patch (details.replace("-details", ""), os.path.basename(details))

main()