aboutsummaryrefslogtreecommitdiffstats
path: root/build/docbook-set-revhistory.py
blob: 8494ff0607b0455a385003143ef5f10826b01372 (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
78
#!/usr/bin/env python3
# Rewrite the revhistory part of the document for vty reference (OS#4063)
import os
import shutil
import sys

xml_in = sys.argv[1]
xml_out = os.environ["TEMPFILE"]
git_date = os.environ["GIT_DATE"]
revnumber = os.environ["REVNUMBER"]


def get_author_initials(line):
    return line.split("<authorinitials>")[1].split("</authorinitials>")[0]


def write_revhistory_block(h_out, author_initials):
    h_out.write("<revhistory>\n")
    h_out.write("<revision>\n")
    h_out.write(f"<revnumber>{revnumber}</revnumber>\n")
    h_out.write(f"<date>{git_date}</date>\n")
    h_out.write(f"<authorinitials>{author_initials}</authorinitials>\n")
    h_out.write("<revremark>Automatically Generated VTY Reference</revremark>\n")
    h_out.write("</revision>\n")
    h_out.write("</revhistory>\n")


def set_revhistory():
    """
    Replace the part of the docbook that looks like the following, and copy
    all other lines. Just using python's xml library would be better, but it
    fails on docbook's custom DTDs.
    <revhistory>
        <revision>
            <revnumber>v1</revnumber>
            <date>18th September 2017</date>
            <authorinitials>nh</authorinitials>
            <revremark>Initial</revremark>
        </revision>
    </revhistory>
    """
    before = 0
    inside = 1
    after = 2

    pos = before
    author_initials = ""

    with open(xml_out, "w") as h_out:
        with open(xml_in, "r") as h_in:
            for line in h_in.readlines():
                if pos == before:
                    if "<revhistory>" in line:
                        h_out.write(line.split("<revhistory>")[0] + "\n")
                        pos = inside

                if pos in [before, after]:
                    h_out.write(line)

                if pos == inside:
                    if "<authorinitials>" in line:
                        author_initials = get_author_initials(line)
                    if "</revhistory>" in line:
                        write_revhistory_block(h_out, author_initials)
                        h_out.write(line.split("</revhistory>")[1])
                        pos = after


def main():
    if xml_in.endswith("-vty-reference.xml"):
        print(f"Changing revhistory to {revnumber}, {git_date}...")
        set_revhistory()
    else:
        print("Copying without change of revhistory...")
        shutil.copyfile(xml_in, xml_out)


main()