Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
yt-project
GitHub Repository: yt-project/yt
Path: blob/main/doc/extensions/yt_colormaps.py
928 views
1
# This extension is quite simple:
2
# 1. It accepts a script name
3
# 2. This script is added to the document in a literalinclude
4
# 3. Any _static images found will be added
5
6
import glob
7
import os
8
import shutil
9
10
from docutils.parsers.rst import Directive, directives
11
12
# Some of this magic comes from the matplotlib plot_directive.
13
14
15
def setup(app):
16
app.add_directive("yt_colormaps", ColormapScript)
17
setup.app = app
18
setup.config = app.config
19
setup.confdir = app.confdir
20
21
retdict = dict(version="0.1", parallel_read_safe=True, parallel_write_safe=True)
22
23
return retdict
24
25
26
class ColormapScript(Directive):
27
required_arguments = 1
28
optional_arguments = 0
29
30
def run(self):
31
rst_file = self.state_machine.document.attributes["source"]
32
rst_dir = os.path.abspath(os.path.dirname(rst_file))
33
script_fn = directives.path(self.arguments[0])
34
script_bn = os.path.basename(script_fn)
35
36
# This magic is from matplotlib
37
dest_dir = os.path.abspath(
38
os.path.join(setup.app.builder.outdir, os.path.dirname(script_fn))
39
)
40
if not os.path.exists(dest_dir):
41
os.makedirs(dest_dir) # no problem here for me, but just use built-ins
42
43
rel_dir = os.path.relpath(rst_dir, setup.confdir)
44
place = os.path.join(dest_dir, rel_dir)
45
if not os.path.isdir(place):
46
os.makedirs(place)
47
shutil.copyfile(
48
os.path.join(rst_dir, script_fn), os.path.join(place, script_bn)
49
)
50
51
im_path = os.path.join(rst_dir, "_static")
52
images = sorted(glob.glob(os.path.join(im_path, "*.png")))
53
lines = []
54
for im in images:
55
im_name = os.path.join("_static", os.path.basename(im))
56
lines.append(f".. image:: {im_name}")
57
lines.append(" :width: 400")
58
lines.append(f" :target: ../../_images/{os.path.basename(im)}")
59
lines.append("\n")
60
lines.append("\n")
61
self.state_machine.insert_input(lines, rst_file)
62
return []
63
64