summaryrefslogtreecommitdiff
path: root/doc/src/tools/stitch_text.py
blob: c9ed99aad8b873e94b622251537ca7e5f194946e (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
#! /usr/bin/env python
"""A script to stitch together the generated text files in the correct order.
"""

import os
import sys

def main():
    if len(sys.argv) != 3:
        sys.stderr.write("usage: %s index.rst text-dir\n")
        return 2

    _, index, txt_dir = sys.argv

    for fb in iter_file_base(index):
        emit(fb, txt_dir)

    return 0

def iter_file_base(fn):
    f = open(fn)
    if sys.version_info[0] >= 3:
        have_line = iter(f).__next__
    else:
        have_line = iter(f).next

    while not have_line().startswith('.. toctree'):
        pass
    while have_line().strip().startswith(':'):
        pass

    yield os.path.splitext(os.path.basename(fn))[0]

    n = 0
    while True:
        line = have_line()
        if line.isspace():
            continue
        if line.startswith(".."):
            break
        n += 1
        yield line.strip()

    f.close()

    if n < 5:
        # maybe format changed?
        raise Exception("Not enough files found. Format change in index.rst?")

def emit(basename, txt_dir):
    f = open(os.path.join(txt_dir, basename + ".txt"))
    for line in f:
        line = line.replace("``", "'")
        sys.stdout.write(line)
    f.close()

    # some space between sections
    sys.stdout.write("\n\n")

    
if __name__ == '__main__':
    sys.exit(main())