|
| 1 | +"""Extension to patch ignored mime types.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import sys |
| 6 | +from importlib.abc import MetaPathFinder |
| 7 | +from importlib.metadata import Distribution, EntryPoint, EntryPoints |
| 8 | +from types import MappingProxyType |
| 9 | +from typing import TYPE_CHECKING, override |
| 10 | + |
| 11 | +from myst_nb.core.render import MimeRenderPlugin |
| 12 | +from sphinx.util.typing import ExtensionMetadata |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + import os |
| 16 | + from collections.abc import Iterable, Sequence |
| 17 | + from importlib.machinery import ModuleSpec |
| 18 | + from importlib.metadata import DistributionFinder, SimplePath |
| 19 | + from types import ModuleType |
| 20 | + |
| 21 | + from docutils import nodes |
| 22 | + from myst_nb.core.render import MimeData, NbElementRenderer |
| 23 | + from sphinx.application import Sphinx |
| 24 | + |
| 25 | + |
| 26 | +ignore: set[str] = set() |
| 27 | + |
| 28 | + |
| 29 | +class _Ignore(MimeRenderPlugin): |
| 30 | + @override |
| 31 | + @staticmethod |
| 32 | + def handle_mime( |
| 33 | + renderer: NbElementRenderer, data: MimeData, inline: bool |
| 34 | + ) -> None | list[nodes.Element]: |
| 35 | + if data.mime_type in ignore: |
| 36 | + return [] # returning a list instead of `None` means “we handled it” |
| 37 | + return None |
| 38 | + |
| 39 | + |
| 40 | +class _IgnoreMimeDist(Distribution): |
| 41 | + metadata = MappingProxyType(dict(Name=__name__, Version="0.0.0")) |
| 42 | + |
| 43 | + @override |
| 44 | + def read_text(self, filename: str) -> str | None: |
| 45 | + return None |
| 46 | + |
| 47 | + @override |
| 48 | + def locate_file(self, path: str | os.PathLike[str]) -> SimplePath: |
| 49 | + raise RuntimeError |
| 50 | + |
| 51 | + @property |
| 52 | + @override |
| 53 | + def entry_points(self) -> EntryPoints: |
| 54 | + ep = EntryPoint("ignore", f"{__name__}:_Ignore", "myst_nb.mime_renderers") |
| 55 | + return EntryPoints([ep]) |
| 56 | + |
| 57 | + |
| 58 | +class _IgnoreMimeFinder(MetaPathFinder): |
| 59 | + def find_spec( |
| 60 | + self, |
| 61 | + fullname: str, |
| 62 | + path: Sequence[str] | None, |
| 63 | + target: ModuleType | None = None, |
| 64 | + ) -> ModuleSpec | None: |
| 65 | + return None |
| 66 | + |
| 67 | + def find_distributions( |
| 68 | + self, context: DistributionFinder.Context | None |
| 69 | + ) -> Iterable[Distribution]: |
| 70 | + """Find fake distribution.""" |
| 71 | + yield _IgnoreMimeDist() |
| 72 | + |
| 73 | + |
| 74 | +def setup(app: Sphinx) -> ExtensionMetadata: |
| 75 | + """App setup hook.""" |
| 76 | + global ignore # noqa: PLW0603 |
| 77 | + |
| 78 | + app.add_config_value("myst_ignore_mime_types", [], "env") |
| 79 | + ignore |= set(app.config.myst_ignore_mime_types) |
| 80 | + |
| 81 | + sys.meta_path.append(_IgnoreMimeFinder()) |
| 82 | + |
| 83 | + return ExtensionMetadata(parallel_read_safe=True) |
0 commit comments