summaryrefslogtreecommitdiff
path: root/doc/build.py
blob: 5818cb7f3d8c1274c113d75f0d13fade4a3c722f (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python3
#
# Copyright 2017 Lars Wirzenius
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.



import os
import sys
import tempfile

import cliapp


def parse_markdown(f, tmpdir):
    lines = f.readlines()
    result = []
    uml_filenames = []
    while lines:
        prefix, uml, lines = extract_uml(lines)
        result.extend(prefix)
        if uml:
            filename = create_uml_file(tmpdir, uml)
            uml_filenames.append(filename)
            result.extend(include(uml, filename))
    return result, uml_filenames


def extract_uml(lines):
    start = find_line(lines, '@startuml\n')
    if start is None:
        return lines, None, []

    end = find_line(lines, '@enduml\n')
    if end is None:
        return lines, None, []

    return lines[:start], lines[start:end+1], lines[end+1:]


def find_line(lines, pattern):
    for i, line in enumerate(lines):
        if line.startswith(pattern):
            return i
    return None


def create_uml_file(tmpdir, lines):
    text = ''.join(lines)
    fd, filename = tempfile.mkstemp(dir=tmpdir)
    os.write(fd, text.encode())
    os.close(fd)
    return filename


def include(uml, filename):
    title = get_title(uml)
    return [
        '![{}]({}.png)\\ \n'.format(title, filename),
        '\n',
    ]


def get_title(uml):
    i = find_line(uml, 'title ')
    if i is not None:
        return uml[i].split(' ', 1)[1]


def plantuml(filename):
    cliapp.runcmd(['plantuml', '-tpng', '-output', '.', filename])


def main():
    tmpdir = sys.argv[1]
    lines, filenames = parse_markdown(sys.stdin, tmpdir)
    sys.stdout.write(''.join(lines))
    for filename in filenames:
        plantuml(filename)


if __name__ == '__main__':
    main()