Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOGS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Change Logs
0.4.2
+++++

* :pr:`48`: Cache gdot script execution results in Sphinx environment`
* :pr:`47`: use svg by default with gdot

0.4.1
Expand Down
30 changes: 30 additions & 0 deletions _unittests/ut_gdot/test_gdot_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,36 @@ def test_gdot4_png(self):
return
self.assertIn("png", content)

@ignore_warnings(PendingDeprecationWarning)
def test_gdot_script_cache(self):
"""Test that identical scripts are cached and produce the same output."""
script = "print('digraph foo { HbarH -> HbazH; }')".replace("H", '"')
content = f"""
before

.. gdot::
:script:

{script}

middle

.. gdot::
:script:

{script}

after
"""
content = rst2html(
content, writer_name="rst", new_extensions=["sphinx_runpython.gdot"]
)
# Both gdot directives should produce the same DOT output
count = content.count('digraph foo { "bar" -> "baz"; }')
self.assertEqual(
count, 2, f"Expected the DOT code to appear twice, got {count}"
)


if __name__ == "__main__":
unittest.main(verbosity=2)
17 changes: 16 additions & 1 deletion sphinx_runpython/gdot/sphinx_gdot_extension.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import hashlib
import os
import logging
from docutils import nodes
Expand Down Expand Up @@ -153,7 +154,21 @@ def run(self):
# executes script if any
content = "\n".join(self.content)
if script or script == "":
stdout, stderr, _ = run_python_script(content, process=process)
env = info.get("env")
cache_key = hashlib.sha256(f"{content}:{process}".encode()).hexdigest()
Comment thread
xadupre marked this conversation as resolved.
Outdated
Comment thread
xadupre marked this conversation as resolved.
Outdated
if env is not None:
if not hasattr(env, "gdot_script_cache"):
env.gdot_script_cache = {}
cached = env.gdot_script_cache.get(cache_key, None)
else:
cached = None

if cached is not None:
stdout, stderr = cached
else:
stdout, stderr, _ = run_python_script(content, process=process)
if env is not None:
env.gdot_script_cache[cache_key] = (stdout, stderr)

if stderr:
out = [
Expand Down
Loading