1#!/usr/bin/env python3
2# Copyright (c) 2016 Jon Turney <jon.turney@dronecode.org.uk>
3#
4# python script to convert the handwritten chapter .texi files, which include
5# the generated files for each function, to DocBook XML
6#
7# all we care about is the content of the refentries, so all this needs to do is
8# convert the @include of the makedoc generated .def files to xi:include of the
9# makedocbook generated .xml files.
10#
11
12from __future__ import print_function
13import sys
14import re
15
16def main():
17    first_node = True
18    prev_sect = False
19
20    print('<?xml version="1.0" encoding="UTF-8"?>')
21    print('<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">')
22
23    for l in sys.stdin.readlines():
24        l = l.rstrip()
25
26        # transform @file{foo} to <filename>foo</filename>
27        l = re.sub("@file{(.*?)}", "<filename>\\1</filename>", l)
28
29        if l.startswith("@node"):
30            l = l.replace("@node", "", 1)
31            l = l.strip()
32            if first_node:
33                print('<chapter id="%s_chapter" xmlns:xi="http://www.w3.org/2001/XInclude">' % l.lower().replace(' ', '_'))
34                first_node = False
35            else:
36                if prev_sect:
37                    print('</section>')
38                print('<section id="%s">' % l)
39                prev_sect = True
40        elif l.startswith("@chapter "):
41            l = l.replace("@chapter ", "", 1)
42            print('<title>%s</title>' % l)
43        elif l.startswith("@section "):
44            l = l.replace("@section ", "", 1)
45            print('<title>%s</title>' % l)
46        elif l.startswith("@include "):
47            l = l.replace("@include ", "", 1)
48            l = l.replace(".def", ".xml", 1)
49            print('<xi:include href="%s"/>' % l.strip())
50
51    if prev_sect:
52        print('</section>')
53    print('</chapter>')
54
55if __name__ == "__main__":
56    main()
57