#!/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 . 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()