#!/usr/bin/env python3 # -*- python -*- from mdbook_plugin import Plugin import os import re import sqlite3 import subprocess import sys DITAA_TAG = r'ditaa(?: ((?:\w|-)+))?' class DitaaPlugin(Plugin): def __init__(self): self.figure_count = 0 self.cache = sqlite3.connect('.mdbook-ditaa.sqlite') try: self.cache.cursor().execute('CREATE TABLE diagrams(source text, svg text)') except: pass def expand_chapter_content(self, chapter): directory = os.path.dirname(chapter.source_path.value) chapter.content = self.expand_codeblock(DITAA_TAG, self.expand_ditaa, chapter.content, directory) def next_filename(self): self.figure_count = self.figure_count + 1 return f'figure_{self.figure_count}' def expand_ditaa(self, m, directory): filename_base = m.group(1) or self.next_filename() filename = os.path.join(directory, filename_base + '.svg') sys.stderr.write(f'ditaa {filename} ...') ditaa_source = m.group(2) cached = list(self.cache.cursor().execute('SELECT svg FROM diagrams WHERE source = ?', (ditaa_source,))) if cached: svg = cached[0][0] else: svg = subprocess.check_output(['ditaa', '-T', '--svg', '-'], input=ditaa_source.encode('utf-8')) svg = svg.decode('utf-8') svg = re.sub(r'<\?xml.*?\?>', '', svg) svg = svg.strip() self.cache.cursor().execute('INSERT INTO diagrams VALUES (?, ?)', (ditaa_source, svg)) self.cache.cursor().execute('COMMIT') # sourcedir = self.context['config']['book']['src'] # baseurl = self.context['config']['output']['html']['site-url'] # svgfilename = os.path.join(sourcedir, output_prefix, filename) # os.makedirs(os.path.dirname(svgfilename), exist_ok=True) # need_write = True # if os.path.exists(svgfilename): # with open(svgfilename, 'rt') as f: # existing = f.read() # if existing == svg: # need_write = False # if need_write: # sys.stderr.write('updated\n') # with open(svgfilename, 'wt') as f: # f.write(svg) # else: # sys.stderr.write('unchanged\n') # return f'

{filename}

\n' sys.stderr.write('inlined\n') return f'
{svg}
\n' if __name__ == '__main__': DitaaPlugin().main(sys.argv)