Skip to content

Commit

Permalink
ci: Some typing fixes/ignore
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed Nov 12, 2023
1 parent b1b185b commit 43fda6f
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 14 deletions.
19 changes: 10 additions & 9 deletions src/mkdocstrings/handlers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
import importlib
import sys
from pathlib import Path
from typing import Any, BinaryIO, ClassVar, Iterable, Iterator, Mapping, MutableMapping, Sequence
from typing import Any, BinaryIO, ClassVar, Iterable, Iterator, Mapping, MutableMapping, Sequence, cast
from xml.etree.ElementTree import Element, tostring

from jinja2 import Environment, FileSystemLoader
from markdown import Markdown
from markdown.extensions.toc import TocTreeprocessor
from markupsafe import Markup

from mkdocstrings.handlers.rendering import (
Expand Down Expand Up @@ -268,15 +269,15 @@ def do_convert_markdown(
An HTML string.
"""
treeprocessors = self._md.treeprocessors
treeprocessors[HeadingShiftingTreeprocessor.name].shift_by = heading_level
treeprocessors[IdPrependingTreeprocessor.name].id_prefix = html_id and html_id + "--"
treeprocessors[ParagraphStrippingTreeprocessor.name].strip = strip_paragraph
treeprocessors[HeadingShiftingTreeprocessor.name].shift_by = heading_level # type: ignore[attr-defined]
treeprocessors[IdPrependingTreeprocessor.name].id_prefix = html_id and html_id + "--" # type: ignore[attr-defined]
treeprocessors[ParagraphStrippingTreeprocessor.name].strip = strip_paragraph # type: ignore[attr-defined]
try:
return Markup(self._md.convert(text))
finally:
treeprocessors[HeadingShiftingTreeprocessor.name].shift_by = 0
treeprocessors[IdPrependingTreeprocessor.name].id_prefix = ""
treeprocessors[ParagraphStrippingTreeprocessor.name].strip = False
treeprocessors[HeadingShiftingTreeprocessor.name].shift_by = 0 # type: ignore[attr-defined]
treeprocessors[IdPrependingTreeprocessor.name].id_prefix = "" # type: ignore[attr-defined]
treeprocessors[ParagraphStrippingTreeprocessor.name].strip = False # type: ignore[attr-defined]
self._md.reset()

def do_heading(
Expand Down Expand Up @@ -319,7 +320,7 @@ def do_heading(
el = Element(f"h{heading_level}", attributes)
el.append(Element("mkdocstrings-placeholder"))
# Tell the 'toc' extension to make its additions if configured so.
toc = self._md.treeprocessors["toc"]
toc = cast(TocTreeprocessor, self._md.treeprocessors["toc"])
if toc.use_anchors:
toc.add_anchor(el, attributes["id"])
if toc.use_permalinks:
Expand Down Expand Up @@ -388,7 +389,7 @@ def __init__(self, config: dict) -> None:
self._handlers: dict[str, BaseHandler] = {}
self.inventory: Inventory = Inventory(project=self._config["mkdocs"]["site_name"])

def get_anchors(self, identifier: str) -> tuple[str, ...] | set[str]:
def get_anchors(self, identifier: str) -> tuple[str, ...]:
"""Return the canonical HTML anchor for the identifier, if any of the seen handlers can collect it.
Arguments:
Expand Down
3 changes: 2 additions & 1 deletion src/mkdocstrings/handlers/rendering.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,13 @@ def __init__(self, md: Markdown, headings: list[Element]):
self.headings = headings

def run(self, root: Element) -> None:
permalink_class = self.md.treeprocessors["toc"].permalink_class # type: ignore[attr-defined]
for el in root.iter():
if self.regex.fullmatch(el.tag):
el = copy.copy(el) # noqa: PLW2901
# 'toc' extension's first pass (which we require to build heading stubs/ids) also edits the HTML.
# Undo the permalink edit so we can pass this heading to the outer pass of the 'toc' extension.
if len(el) > 0 and el[-1].get("class") == self.md.treeprocessors["toc"].permalink_class:
if len(el) > 0 and el[-1].get("class") == permalink_class:
del el[-1]
self.headings.append(el)

Expand Down
7 changes: 4 additions & 3 deletions src/mkdocstrings/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,10 @@ def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
}
self._handlers = Handlers(extension_config)

autorefs: AutorefsPlugin
try:
# If autorefs plugin is explicitly enabled, just use it.
autorefs = config.plugins["autorefs"]
autorefs = config.plugins["autorefs"] # type: ignore[assignment]
log.debug(f"Picked up existing autorefs instance {autorefs!r}")
except KeyError:
# Otherwise, add a limited instance of it that acts only on what's added through `register_anchor`.
Expand All @@ -186,7 +187,7 @@ def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
autorefs.get_fallback_anchor = self.handlers.get_anchors

mkdocstrings_extension = MkdocstringsExtension(extension_config, self.handlers, autorefs)
config.markdown_extensions.append(mkdocstrings_extension)
config.markdown_extensions.append(mkdocstrings_extension) # type: ignore[arg-type]

config.extra_css.insert(0, self.css_filename) # So that it has lower priority than user files.

Expand Down Expand Up @@ -258,7 +259,7 @@ def on_env(self, env: Environment, config: MkDocsConfig, *args: Any, **kwargs: A
loader_name = loader.__func__.__qualname__
log.error(f"Couldn't load inventory {import_item} through {loader_name}: {error}") # noqa: TRY400
for page, identifier in results.items():
config.plugins["autorefs"].register_url(page, identifier)
config.plugins["autorefs"].register_url(page, identifier) # type: ignore[attr-defined]
self._inv_futures = {}

def on_post_build(
Expand Down
2 changes: 1 addition & 1 deletion tests/test_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def test_dont_register_every_identifier_as_anchor(plugin: MkdocstringsPlugin, ex
ids = ("id1", "id2", "id3")
handler.get_anchors = lambda _: ids # type: ignore[method-assign]
ext_markdown.convert("::: tests.fixtures.headings")
autorefs = ext_markdown.parser.blockprocessors["mkdocstrings"]._autorefs
autorefs = ext_markdown.parser.blockprocessors["mkdocstrings"]._autorefs # type: ignore[attr-defined]
for identifier in ids:
assert identifier not in autorefs._url_map
assert identifier not in autorefs._abs_url_map
Expand Down

0 comments on commit 43fda6f

Please sign in to comment.