|
7 | 7 | import re |
8 | 8 | from collections import defaultdict |
9 | 9 | from pathlib import Path |
| 10 | +from shutil import copyfileobj |
10 | 11 | from typing import Dict, List, Set, Union, cast |
11 | 12 |
|
12 | 13 | import sphinx |
|
28 | 29 |
|
29 | 30 | from .. import __version__ |
30 | 31 |
|
| 32 | +try: |
| 33 | + import importlib.resources as pkg_resources |
| 34 | +except ImportError: |
| 35 | + # Use backported to PY<3.7 `importlib_resources` lib. |
| 36 | + import importlib_resources as pkg_resources |
| 37 | + |
31 | 38 | obj_name = "graphtik diagram" |
32 | 39 | role_name = "graphtik" |
33 | 40 | log = logging.getLogger(__name__) |
@@ -444,6 +451,26 @@ def _purge_old_document_images(app: Sphinx, env: BuildEnvironment, docname: str) |
444 | 451 | env.graphtik_image_purgatory = DocFilesPurgatory() |
445 | 452 |
|
446 | 453 |
|
| 454 | +def _stage_my_pkg_resource(inp_fname, out_fpath): |
| 455 | + with pkg_resources.open_binary(__package__, inp_fname) as inp, open( |
| 456 | + out_fpath, "wb" |
| 457 | + ) as out: |
| 458 | + copyfileobj(inp, out) |
| 459 | + |
| 460 | + |
| 461 | +_css_fname = "graphtik.css" |
| 462 | + |
| 463 | + |
| 464 | +def _copy_graphtik_static_assets(app: Sphinx, exc: Exception) -> None: |
| 465 | + """Callback of `build-finished`` event. """ |
| 466 | + if not exc and _should_work(app): |
| 467 | + dst = Path(app.outdir, "_static", _css_fname) |
| 468 | + ## Builder `latex` does not have _static folder. |
| 469 | + # |
| 470 | + if not dst.exists() and dst.parent.exists(): |
| 471 | + _stage_my_pkg_resource(_css_fname, dst) |
| 472 | + |
| 473 | + |
447 | 474 | def _validate_and_apply_configs(app: Sphinx, config: Config): |
448 | 475 | """Callback of `config-inited`` event. """ |
449 | 476 | config.graphtik_default_graph_format is None or _valid_format_option( |
@@ -507,6 +534,9 @@ def setup(app: Sphinx): |
507 | 534 | app.connect("config-inited", _validate_and_apply_configs) |
508 | 535 | app.connect("doctree-read", _run_doctests_on_graphtik_document) |
509 | 536 | app.connect("env-purge-doc", _purge_old_document_images) |
| 537 | + app.connect("build-finished", _copy_graphtik_static_assets) |
| 538 | + |
| 539 | + app.add_css_file(_css_fname) |
510 | 540 |
|
511 | 541 | # Permanently set this, or else, e.g. +SKIP will not work! |
512 | 542 | app.config.trim_doctest_flags = False |
|
0 commit comments