Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/docs/_ext/applyxrefs.py
blob: ecc67bc877804f4fa73609157d4224093d5a7325 (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
72
73
74
75
76
77
"""Adds xref targets to the top of files."""

import os
import sys

testing = False

DONT_TOUCH = (
    './index.txt',
)


def target_name(fn):
    if fn.endswith('.txt'):
        fn = fn[:-4]
    return '_' + fn.lstrip('./').replace('/', '-')


def process_file(fn, lines):
    lines.insert(0, '\n')
    lines.insert(0, '.. %s:\n' % target_name(fn))
    try:
        with open(fn, 'w') as fp:
            fp.writelines(lines)
    except IOError:
        print("Can't open %s for writing. Not touching it." % fn)


def has_target(fn):
    try:
        with open(fn, 'r') as fp:
            lines = fp.readlines()
    except IOError:
        print("Can't open or read %s. Not touching it." % fn)
        return (True, None)

    # print fn, len(lines)
    if len(lines) < 1:
        print("Not touching empty file %s." % fn)
        return (True, None)
    if lines[0].startswith('.. _'):
        return (True, None)
    return (False, lines)


def main(argv=None):
    if argv is None:
        argv = sys.argv

    if len(argv) == 1:
        argv.extend('.')

    files = []
    for root in argv[1:]:
        for (dirpath, dirnames, filenames) in os.walk(root):
            files.extend((dirpath, f) for f in filenames)
    files.sort()
    files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
    # print files

    for fn in files:
        if fn in DONT_TOUCH:
            print("Skipping blacklisted file %s." % fn)
            continue

        target_found, lines = has_target(fn)
        if not target_found:
            if testing:
                print('%s: %s' % (fn, lines[0]))
            else:
                print("Adding xref to %s" % fn)
                process_file(fn, lines)
        else:
            print("Skipping %s: already has a xref" % fn)

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