11"""Setup for the myst-nb sphinx extension."""
22from __future__ import annotations
33
4+ import contextlib
45import hashlib
56from importlib import resources as import_resources
67import os
78from pathlib import Path
8- from typing import Any
9+ import sys
10+ from types import ModuleType
11+ from typing import Any , Iterator
912
1013from myst_parser .sphinx_ext .main import setup_sphinx as setup_myst_parser
1114from sphinx .application import Sphinx
@@ -184,9 +187,21 @@ def _get_file_hash(path: Path):
184187 return hashlib .sha256 (path .read_bytes ()).hexdigest ()
185188
186189
190+ @contextlib .contextmanager
191+ def _import_resources_path (package : ModuleType , resource : str ) -> Iterator [Path ]:
192+ if sys .version_info < (3 , 9 ):
193+ with import_resources .path (package , resource ) as path :
194+ yield path
195+ else :
196+ with import_resources .as_file (
197+ import_resources .files (package ).joinpath (resource )
198+ ) as path :
199+ yield path
200+
201+
187202def add_css (app : Sphinx ):
188203 """Add CSS for myst-nb."""
189- with import_resources . path (static , "mystnb.css" ) as source_path :
204+ with _import_resources_path (static , "mystnb.css" ) as source_path :
190205 hash = _get_file_hash (source_path )
191206 app .add_css_file (f"mystnb.{ hash } .css" )
192207
@@ -195,9 +210,8 @@ def add_global_html_resources(app: Sphinx, exception):
195210 """Add HTML resources that apply to all pages."""
196211 # see https://github.com/sphinx-doc/sphinx/issues/1379
197212 if app .builder is not None and app .builder .format == "html" and not exception :
198- with import_resources .path (static , "mystnb.css" ) as source_path :
199- with import_resources .path (static , "mystnb.css" ) as source_path :
200- hash = _get_file_hash (source_path )
213+ with _import_resources_path (static , "mystnb.css" ) as source_path :
214+ hash = _get_file_hash (source_path )
201215 destination = os .path .join (
202216 app .builder .outdir , "_static" , f"mystnb.{ hash } .css"
203217 )
@@ -210,6 +224,6 @@ def add_per_page_html_resources(
210224 """Add JS files for this page, identified from the parsing of the notebook."""
211225 if app .env is None or app .builder is None or app .builder .format != "html" :
212226 return
213- js_files = NbMetadataCollector .get_js_files (app .env , pagename ) # type: ignore
227+ js_files = NbMetadataCollector .get_js_files (app .env , pagename )
214228 for path , kwargs in js_files .values ():
215- app .add_js_file (path , ** kwargs ) # type: ignore
229+ app .add_js_file (path , ** kwargs )
0 commit comments