clean code && add arguments & options
This commit is contained in:
parent
3aa4cbf553
commit
6febc0a475
1 changed files with 34 additions and 13 deletions
|
@ -1,27 +1,48 @@
|
||||||
from docutils import nodes
|
from docutils import nodes
|
||||||
|
|
||||||
from docutils.parsers.rst import Directive
|
from docutils.parsers.rst import Directive, directives
|
||||||
|
from sphinx.util.docutils import SphinxDirective
|
||||||
|
|
||||||
from shutil import which
|
from shutil import which
|
||||||
import shlex
|
import shlex
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
class D2langDirective(Directive):
|
class D2langDirective(SphinxDirective):
|
||||||
|
required_arguments = 0
|
||||||
has_content = True
|
has_content = True
|
||||||
|
optional_arguments = 3
|
||||||
|
option_spec = {
|
||||||
|
'layout': directives.unchanged_required,
|
||||||
|
'filename': directives.unchanged_required,
|
||||||
|
}
|
||||||
def run(self):
|
def run(self):
|
||||||
# TODO : add tempfile for diag_source
|
|
||||||
d2_bin = which('d2')
|
d2_bin = which('d2')
|
||||||
outdir = self.state.document.settings.env.app.builder.outdir
|
|
||||||
srcdir = self.state.document.settings.env.srcdir
|
srcdir = self.state.document.settings.env.srcdir
|
||||||
diag_source = self.content
|
diag_source = self.content
|
||||||
|
if 'filename' in self.options:
|
||||||
|
output_fname = self.options.get('filename')
|
||||||
|
else:
|
||||||
|
output_fname = 'test.svg'
|
||||||
|
if 'layout':
|
||||||
|
layout = self.options.get('layout')
|
||||||
|
else:
|
||||||
|
layout = 'dagre'
|
||||||
|
if self.arguments:
|
||||||
|
build_svg(self.arguments[0], srcdir, output_fname, layout)
|
||||||
|
else:
|
||||||
with tempfile.NamedTemporaryFile() as fp:
|
with tempfile.NamedTemporaryFile() as fp:
|
||||||
for line in self.content.data:
|
for line in self.content.data:
|
||||||
fp.write(bytes(line,'utf-8'))
|
fp.write(bytes(line,'utf-8'))
|
||||||
fp.write(bytes('\n','utf-8'))
|
fp.write(bytes('\n','utf-8'))
|
||||||
fp.seek(0)
|
fp.seek(0)
|
||||||
cmd_line = '%s %s %s' % (d2_bin, fp.name, srcdir + "/test.svg")
|
build_svg(fp.name, srcdir, output_fname, layout)
|
||||||
|
image_node = nodes.image(uri=output_fname)
|
||||||
|
return [image_node]
|
||||||
|
|
||||||
|
def build_svg(diag_src, out_dir, filename, layout)
|
||||||
|
d2_bin = which('d2')
|
||||||
|
cmd_line = '%s -l %s %s %s' % (d2_bin, layout, diag_src, out_dir + "/" + filename)
|
||||||
args = shlex.split(cmd_line)
|
args = shlex.split(cmd_line)
|
||||||
subprocess.run(args)
|
subprocess.run(args)
|
||||||
image_node = nodes.image(uri="/test.svg")
|
return True
|
||||||
return [image_node]
|
|
||||||
|
|
Loading…
Reference in a new issue