Skip to content

Commit a92e884

Browse files
committed
ci: Quality
1 parent 6a45da8 commit a92e884

6 files changed

Lines changed: 89 additions & 64 deletions

File tree

src/mkdocs_autorefs/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,7 @@
22
33
Automatically link across pages in MkDocs.
44
"""
5+
6+
from __future__ import annotations
7+
8+
__all__: list[str] = []

src/mkdocs_autorefs/plugin.py

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,24 @@
1010
and fixes them using the previously stored identifier-URL mapping.
1111
"""
1212

13+
from __future__ import annotations
14+
1315
import contextlib
1416
import functools
1517
import logging
16-
from typing import Callable, Dict, Optional, Sequence
18+
from typing import TYPE_CHECKING, Any, Callable, Sequence
1719
from urllib.parse import urlsplit
1820

19-
from mkdocs.config import Config
2021
from mkdocs.plugins import BasePlugin
21-
from mkdocs.structure.pages import Page
22-
from mkdocs.structure.toc import AnchorLink
2322
from mkdocs.utils import warning_filter
2423

2524
from mkdocs_autorefs.references import AutorefsExtension, fix_refs, relative_url
2625

26+
if TYPE_CHECKING:
27+
from mkdocs.config import Config
28+
from mkdocs.structure.pages import Page
29+
from mkdocs.structure.toc import AnchorLink
30+
2731
log = logging.getLogger(f"mkdocs.plugins.{__name__}")
2832
log.addFilter(warning_filter)
2933

@@ -42,16 +46,16 @@ class AutorefsPlugin(BasePlugin):
4246
"""
4347

4448
scan_toc: bool = True
45-
current_page: Optional[str] = None
49+
current_page: str | None = None
4650

4751
def __init__(self) -> None:
4852
"""Initialize the object."""
4953
super().__init__()
50-
self._url_map: Dict[str, str] = {}
51-
self._abs_url_map: Dict[str, str] = {}
52-
self.get_fallback_anchor: Optional[Callable[[str], Optional[str]]] = None # noqa: WPS234
54+
self._url_map: dict[str, str] = {}
55+
self._abs_url_map: dict[str, str] = {}
56+
self.get_fallback_anchor: Callable[[str], str | None] | None = None
5357

54-
def register_anchor(self, page: str, identifier: str):
58+
def register_anchor(self, page: str, identifier: str) -> None:
5559
"""Register that an anchor corresponding to an identifier was encountered when rendering the page.
5660
5761
Arguments:
@@ -60,7 +64,7 @@ def register_anchor(self, page: str, identifier: str):
6064
"""
6165
self._url_map[identifier] = f"{page}#{identifier}"
6266

63-
def register_url(self, identifier: str, url: str):
67+
def register_url(self, identifier: str, url: str) -> None:
6468
"""Register that the identifier should be turned into a link to this URL.
6569
6670
Arguments:
@@ -69,10 +73,10 @@ def register_url(self, identifier: str, url: str):
6973
"""
7074
self._abs_url_map[identifier] = url
7175

72-
def _get_item_url( # noqa: WPS234
76+
def _get_item_url(
7377
self,
7478
identifier: str,
75-
fallback: Optional[Callable[[str], Sequence[str]]] = None,
79+
fallback: Callable[[str], Sequence[str]] | None = None,
7680
) -> str:
7781
try:
7882
return self._url_map[identifier]
@@ -88,11 +92,11 @@ def _get_item_url( # noqa: WPS234
8892
return url
8993
raise
9094

91-
def get_item_url( # noqa: WPS234
95+
def get_item_url(
9296
self,
9397
identifier: str,
94-
from_url: Optional[str] = None,
95-
fallback: Optional[Callable[[str], Sequence[str]]] = None,
98+
from_url: str | None = None,
99+
fallback: Callable[[str], Sequence[str]] | None = None,
96100
) -> str:
97101
"""Return a site-relative URL with anchor to the identifier, if it's present anywhere.
98102
@@ -111,7 +115,7 @@ def get_item_url( # noqa: WPS234
111115
return relative_url(from_url, url)
112116
return url
113117

114-
def on_config(self, config: Config, **kwargs) -> Config: # noqa: W0613,R0201 (unused arguments, cannot be static)
118+
def on_config(self, config: Config, **kwargs: Any) -> Config: # noqa: ARG002
115119
"""Instantiate our Markdown extension.
116120
117121
Hook for the [`on_config` event](https://www.mkdocs.org/user-guide/plugins/#on_config).
@@ -129,7 +133,7 @@ def on_config(self, config: Config, **kwargs) -> Config: # noqa: W0613,R0201 (u
129133
config["markdown_extensions"].append(AutorefsExtension())
130134
return config
131135

132-
def on_page_markdown(self, markdown: str, page: Page, **kwargs) -> str: # noqa: W0613 (unused arguments)
136+
def on_page_markdown(self, markdown: str, page: Page, **kwargs: Any) -> str: # noqa: ARG002
133137
"""Remember which page is the current one.
134138
135139
Arguments:
@@ -140,10 +144,10 @@ def on_page_markdown(self, markdown: str, page: Page, **kwargs) -> str: # noqa:
140144
Returns:
141145
The same Markdown. We only use this hook to map anchors to URLs.
142146
"""
143-
self.current_page = page.url # noqa: WPS601
147+
self.current_page = page.url
144148
return markdown
145149

146-
def on_page_content(self, html: str, page: Page, **kwargs) -> str: # noqa: W0613 (unused arguments)
150+
def on_page_content(self, html: str, page: Page, **kwargs: Any) -> str: # noqa: ARG002
147151
"""Map anchors to URLs.
148152
149153
Hook for the [`on_page_content` event](https://www.mkdocs.org/user-guide/plugins/#on_page_content).
@@ -178,7 +182,7 @@ def map_urls(self, base_url: str, anchor: AnchorLink) -> None:
178182
for child in anchor.children:
179183
self.map_urls(base_url, child)
180184

181-
def on_post_page(self, output: str, page: Page, **kwargs) -> str: # noqa: W0613 (unused arguments)
185+
def on_post_page(self, output: str, page: Page, **kwargs: Any) -> str: # noqa: ARG002
182186
"""Fix cross-references.
183187
184188
Hook for the [`on_post_page` event](https://www.mkdocs.org/user-guide/plugins/#on_post_page).

src/mkdocs_autorefs/references.py

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
11
"""Cross-references module."""
22

3+
from __future__ import annotations
4+
35
import re
46
from html import escape, unescape
5-
from typing import Any, Callable, List, Match, Tuple, Union
7+
from typing import TYPE_CHECKING, Any, Callable, Match, Tuple
68
from urllib.parse import urlsplit
79
from xml.etree.ElementTree import Element
810

9-
from markdown import Markdown
1011
from markdown.extensions import Extension
1112
from markdown.inlinepatterns import REFERENCE_RE, ReferenceInlineProcessor
1213
from markdown.util import INLINE_PLACEHOLDER_RE
1314

15+
if TYPE_CHECKING:
16+
from markdown import Markdown
17+
1418
AUTO_REF_RE = re.compile(
1519
r"<span data-(?P<kind>autorefs-identifier|autorefs-optional|autorefs-optional-hover)="
16-
r'("?)(?P<identifier>[^"<>]*)\2>(?P<title>.*?)</span>'
20+
r'("?)(?P<identifier>[^"<>]*)\2>(?P<title>.*?)</span>',
1721
)
1822
"""A regular expression to match mkdocs-autorefs' special reference markers
1923
in the [`on_post_page` hook][mkdocs_autorefs.plugin.AutorefsPlugin.on_post_page].
@@ -25,13 +29,13 @@
2529
class AutoRefInlineProcessor(ReferenceInlineProcessor):
2630
"""A Markdown extension."""
2731

28-
def __init__(self, *args, **kwargs): # noqa: D107
32+
def __init__(self, *args: Any, **kwargs: Any) -> None: # noqa: D107
2933
super().__init__(REFERENCE_RE, *args, **kwargs)
3034

3135
# Code based on
3236
# https://github.com/Python-Markdown/markdown/blob/8e7528fa5c98bf4652deb13206d6e6241d61630b/markdown/inlinepatterns.py#L780
3337

34-
def handleMatch(self, m, data) -> Union[Element, EvalIDType]: # type: ignore[override] # noqa: N802,WPS111
38+
def handleMatch(self, m: Match[str], data: Any) -> Element | EvalIDType: # type: ignore[override] # noqa: N802
3539
"""Handle an element that matched.
3640
3741
Arguments:
@@ -71,7 +75,7 @@ def evalId(self, data: str, index: int, text: str) -> EvalIDType: # noqa: N802
7175
Returns:
7276
A tuple containing the identifier, its end position, and whether it matched.
7377
"""
74-
m = self.RE_LINK.match(data, pos=index) # noqa: WPS111
78+
m = self.RE_LINK.match(data, pos=index)
7579
if not m:
7680
return None, index, False
7781

@@ -87,7 +91,7 @@ def evalId(self, data: str, index: int, text: str) -> EvalIDType: # noqa: N802
8791
end = m.end(0)
8892
return identifier, end, True
8993

90-
def makeTag(self, identifier: str, text: str) -> Element: # type: ignore[override] # noqa: N802,W0221
94+
def makeTag(self, identifier: str, text: str) -> Element: # type: ignore[override] # noqa: N802
9195
"""Create a tag that can be matched by `AUTO_REF_RE`.
9296
9397
Arguments:
@@ -124,12 +128,12 @@ def relative_url(url_a: str, url_b: str) -> str:
124128

125129
# go up as many times as remaining a parts' depth
126130
levels = len(parts_a) - 1
127-
parts_relative = [".."] * levels + parts_b # noqa: WPS435
131+
parts_relative = [".."] * levels + parts_b
128132
relative = "/".join(parts_relative)
129133
return f"{relative}#{anchor}"
130134

131135

132-
def fix_ref(url_mapper: Callable[[str], str], unmapped: List[str]) -> Callable: # noqa: WPS212,WPS231
136+
def fix_ref(url_mapper: Callable[[str], str], unmapped: list[str]) -> Callable:
133137
"""Return a `repl` function for [`re.sub`](https://docs.python.org/3/library/re.html#re.sub).
134138
135139
In our context, we match Markdown references and replace them with HTML links.
@@ -148,7 +152,7 @@ def fix_ref(url_mapper: Callable[[str], str], unmapped: List[str]) -> Callable:
148152
and returning the replacement strings.
149153
"""
150154

151-
def inner(match: Match): # noqa: WPS212,WPS430
155+
def inner(match: Match) -> str:
152156
identifier = match["identifier"]
153157
title = match["title"]
154158
kind = match["kind"]
@@ -158,7 +162,7 @@ def inner(match: Match): # noqa: WPS212,WPS430
158162
except KeyError:
159163
if kind == "autorefs-optional":
160164
return title
161-
elif kind == "autorefs-optional-hover":
165+
if kind == "autorefs-optional-hover":
162166
return f'<span title="{identifier}">{title}</span>'
163167
unmapped.append(identifier)
164168
if title == identifier:
@@ -176,7 +180,7 @@ def inner(match: Match): # noqa: WPS212,WPS430
176180
return inner
177181

178182

179-
def fix_refs(html: str, url_mapper: Callable[[str], str]) -> Tuple[str, List[str]]:
183+
def fix_refs(html: str, url_mapper: Callable[[str], str]) -> tuple[str, list[str]]:
180184
"""Fix all references in the given HTML text.
181185
182186
Arguments:
@@ -187,7 +191,7 @@ def fix_refs(html: str, url_mapper: Callable[[str], str]) -> Tuple[str, List[str
187191
Returns:
188192
The fixed HTML.
189193
"""
190-
unmapped = [] # type: ignore
194+
unmapped: list[str] = []
191195
html = AUTO_REF_RE.sub(fix_ref(url_mapper, unmapped), html)
192196
return html, unmapped
193197

@@ -206,5 +210,5 @@ def extendMarkdown(self, md: Markdown) -> None: # noqa: N802 (casing: parent me
206210
md.inlinePatterns.register(
207211
AutoRefInlineProcessor(md),
208212
"mkdocs-autorefs",
209-
priority=168, # noqa: WPS432 # Right after markdown.inlinepatterns.ReferenceInlineProcessor
213+
priority=168, # Right after markdown.inlinepatterns.ReferenceInlineProcessor
210214
)

tests/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""Tests for the mkdocs-autorefs package."""

tests/test_plugin.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
"""Tests for the plugin module."""
2+
3+
from __future__ import annotations
4+
25
import pytest
36

47
from mkdocs_autorefs.plugin import AutorefsPlugin
58

69

7-
def test_url_registration():
10+
def test_url_registration() -> None:
811
"""Check that URLs can be registered, then obtained."""
912
plugin = AutorefsPlugin()
1013
plugin.register_anchor(identifier="foo", page="foo1.html")
@@ -16,7 +19,7 @@ def test_url_registration():
1619
plugin.get_item_url("baz")
1720

1821

19-
def test_url_registration_with_from_url():
22+
def test_url_registration_with_from_url() -> None:
2023
"""Check that URLs can be registered, then obtained, relative to a page."""
2124
plugin = AutorefsPlugin()
2225
plugin.register_anchor(identifier="foo", page="foo1.html")
@@ -28,7 +31,7 @@ def test_url_registration_with_from_url():
2831
plugin.get_item_url("baz", from_url="a/b.html")
2932

3033

31-
def test_url_registration_with_fallback():
34+
def test_url_registration_with_fallback() -> None:
3235
"""Check that URLs can be registered, then obtained through a fallback."""
3336
plugin = AutorefsPlugin()
3437
plugin.register_anchor(identifier="foo", page="foo1.html")
@@ -47,7 +50,7 @@ def test_url_registration_with_fallback():
4750
plugin.get_item_url("foobar", fallback=lambda _: ())
4851

4952

50-
def test_dont_make_relative_urls_relative_again():
53+
def test_dont_make_relative_urls_relative_again() -> None:
5154
"""Check that URLs are not made relative more than once."""
5255
plugin = AutorefsPlugin()
5356
plugin.register_anchor(identifier="foo.bar.baz", page="foo/bar/baz.html")

0 commit comments

Comments
 (0)