Skip to content

Commit b61d4d1

Browse files
authored
refactor: Drop support for MkDocs < 1.4, modernize usages
PR #629: #629
1 parent 370a61d commit b61d4d1

4 files changed

Lines changed: 54 additions & 53 deletions

File tree

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ dependencies = [
3232
"Jinja2>=2.11.1",
3333
"Markdown>=3.3",
3434
"MarkupSafe>=1.1",
35-
"mkdocs>=1.2",
35+
"mkdocs>=1.4",
3636
"mkdocs-autorefs>=0.3.1",
3737
"pymdown-extensions>=6.3",
3838
"importlib-metadata>=4.6; python_version < '3.10'",

src/mkdocstrings/extension.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,7 @@ def __init__(
7272
Arguments:
7373
parser: A `markdown.blockparser.BlockParser` instance.
7474
md: A `markdown.Markdown` instance.
75-
config: The [configuration][mkdocstrings.plugin.MkdocstringsPlugin.config_scheme]
76-
of the `mkdocstrings` plugin.
75+
config: The [configuration][mkdocstrings.plugin.PluginConfig] of the `mkdocstrings` plugin.
7776
handlers: The handlers container.
7877
autorefs: The autorefs plugin instance.
7978
"""

src/mkdocstrings/plugin.py

Lines changed: 49 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222
from typing import TYPE_CHECKING, Any, BinaryIO, Callable, Iterable, List, Mapping, Tuple, TypeVar
2323
from urllib import request
2424

25-
from mkdocs.config.config_options import Type as MkType
26-
from mkdocs.config.config_options import Dir, Optional
25+
from mkdocs.config import Config
26+
from mkdocs.config import config_options as opt
2727
from mkdocs.plugins import BasePlugin
2828
from mkdocs.utils import write_file
2929
from mkdocs_autorefs.plugin import AutorefsPlugin
@@ -34,7 +34,6 @@
3434

3535
if TYPE_CHECKING:
3636
from jinja2.environment import Environment
37-
from mkdocs.config import Config
3837
from mkdocs.config.defaults import MkDocsConfig
3938

4039
if sys.version_info < (3, 10):
@@ -63,38 +62,15 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
6362
return wrapper
6463

6564

66-
class MkdocstringsPlugin(BasePlugin):
67-
"""An `mkdocs` plugin.
68-
69-
This plugin defines the following event hooks:
70-
71-
- `on_config`
72-
- `on_env`
73-
- `on_post_build`
65+
class PluginConfig(Config):
66+
"""The configuration options of `mkdocstrings`, written in `mkdocs.yml`."""
7467

75-
Check the [Developing Plugins](https://www.mkdocs.org/user-guide/plugins/#developing-plugins) page of `mkdocs`
76-
for more information about its plugin system.
77-
"""
78-
79-
config_scheme: tuple[tuple[str, MkType]] = ( # type: ignore[assignment]
80-
("handlers", MkType(dict, default={})),
81-
("default_handler", MkType(str, default="python")),
82-
("custom_templates", Optional(Dir(exists=True))),
83-
("enable_inventory", MkType(bool, default=None)),
84-
("enabled", MkType(bool, default=True)),
85-
)
68+
handlers = opt.Type(dict, default={})
8669
"""
87-
The configuration options of `mkdocstrings`, written in `mkdocs.yml`.
70+
Global configuration of handlers.
8871
89-
Available options are:
90-
91-
- **`handlers`**: Global configuration of handlers. You can set global configuration per handler, applied everywhere,
92-
but overridable in each "autodoc" instruction. Example:
93-
- **`default_handler`**: The default handler to use. The value is the name of the handler module. Default is "python".
94-
- **`custom_templates`**: Location of custom templates to use when rendering API objects. Value should be the path of
95-
a directory relative to the MkDocs configuration file.
96-
- **`enable_inventory`**: Whether to enable object inventory creation.
97-
- **`enabled`**: Whether to enable the plugin. Default is true. If false, *mkdocstrings* will not collect or render anything.
72+
You can set global configuration per handler, applied everywhere,
73+
but overridable in each "autodoc" instruction. Example:
9874
9975
```yaml
10076
plugins:
@@ -110,6 +86,32 @@ class MkdocstringsPlugin(BasePlugin):
11086
```
11187
"""
11288

89+
default_handler = opt.Type(str, default="python")
90+
"""The default handler to use. The value is the name of the handler module. Default is "python"."""
91+
custom_templates = opt.Optional(opt.Dir(exists=True)),
92+
"""Location of custom templates to use when rendering API objects.
93+
94+
Value should be the path of a directory relative to the MkDocs configuration file.
95+
"""
96+
enable_inventory = opt.Optional(opt.Type(bool))
97+
"""Whether to enable object inventory creation."""
98+
enabled = opt.Type(bool, default=True)
99+
"""Whether to enable the plugin. Default is true. If false, *mkdocstrings* will not collect or render anything."""
100+
101+
102+
class MkdocstringsPlugin(BasePlugin[PluginConfig]):
103+
"""An `mkdocs` plugin.
104+
105+
This plugin defines the following event hooks:
106+
107+
- `on_config`
108+
- `on_env`
109+
- `on_post_build`
110+
111+
Check the [Developing Plugins](https://www.mkdocs.org/user-guide/plugins/#developing-plugins) page of `mkdocs`
112+
for more information about its plugin system.
113+
"""
114+
113115
css_filename = "assets/_mkdocstrings.css"
114116

115117
def __init__(self) -> None:
@@ -152,41 +154,41 @@ def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
152154
return config
153155
log.debug("Adding extension to the list")
154156

155-
theme_name = config["theme"].name or os.path.dirname(config["theme"].dirs[0])
157+
theme_name = config.theme.name or os.path.dirname(config.theme.dirs[0])
156158

157159
to_import: InventoryImportType = []
158-
for handler_name, conf in self.config["handlers"].items():
160+
for handler_name, conf in self.config.handlers.items():
159161
for import_item in conf.pop("import", ()):
160162
if isinstance(import_item, str):
161163
import_item = {"url": import_item} # noqa: PLW2901
162164
to_import.append((handler_name, import_item))
163165

164166
extension_config = {
165167
"theme_name": theme_name,
166-
"mdx": config["markdown_extensions"],
167-
"mdx_configs": config["mdx_configs"],
168+
"mdx": config.markdown_extensions,
169+
"mdx_configs": config.mdx_configs,
168170
"mkdocstrings": self.config,
169171
"mkdocs": config,
170172
}
171173
self._handlers = Handlers(extension_config)
172174

173175
try:
174176
# If autorefs plugin is explicitly enabled, just use it.
175-
autorefs = config["plugins"]["autorefs"]
177+
autorefs = config.plugins["autorefs"]
176178
log.debug(f"Picked up existing autorefs instance {autorefs!r}")
177179
except KeyError:
178180
# Otherwise, add a limited instance of it that acts only on what's added through `register_anchor`.
179181
autorefs = AutorefsPlugin()
180182
autorefs.scan_toc = False
181-
config["plugins"]["autorefs"] = autorefs
183+
config.plugins["autorefs"] = autorefs
182184
log.debug(f"Added a subdued autorefs instance {autorefs!r}")
183185
# Add collector-based fallback in either case.
184186
autorefs.get_fallback_anchor = self.handlers.get_anchors
185187

186188
mkdocstrings_extension = MkdocstringsExtension(extension_config, self.handlers, autorefs)
187-
config["markdown_extensions"].append(mkdocstrings_extension)
189+
config.markdown_extensions.append(mkdocstrings_extension)
188190

189-
config["extra_css"].insert(0, self.css_filename) # So that it has lower priority than user files.
191+
config.extra_css.insert(0, self.css_filename) # So that it has lower priority than user files.
190192

191193
self._inv_futures = {}
192194
if to_import:
@@ -210,7 +212,7 @@ def inventory_enabled(self) -> bool:
210212
Returns:
211213
Whether the inventory is enabled.
212214
"""
213-
inventory_enabled = self.config["enable_inventory"]
215+
inventory_enabled = self.config.enable_inventory
214216
if inventory_enabled is None:
215217
inventory_enabled = any(handler.enable_inventory for handler in self.handlers.seen_handlers)
216218
return inventory_enabled
@@ -222,9 +224,9 @@ def plugin_enabled(self) -> bool:
222224
Returns:
223225
Whether the plugin is enabled.
224226
"""
225-
return self.config["enabled"]
227+
return self.config.enabled
226228

227-
def on_env(self, env: Environment, config: Config, *args: Any, **kwargs: Any) -> None: # noqa: ARG002
229+
def on_env(self, env: Environment, config: MkDocsConfig, *args: Any, **kwargs: Any) -> None: # noqa: ARG002
228230
"""Extra actions that need to happen after all Markdown rendering and before HTML rendering.
229231
230232
Hook for the [`on_env` event](https://www.mkdocs.org/user-guide/plugins/#on_env).
@@ -236,12 +238,12 @@ def on_env(self, env: Environment, config: Config, *args: Any, **kwargs: Any) ->
236238
return
237239
if self._handlers:
238240
css_content = "\n".join(handler.extra_css for handler in self.handlers.seen_handlers)
239-
write_file(css_content.encode("utf-8"), os.path.join(config["site_dir"], self.css_filename))
241+
write_file(css_content.encode("utf-8"), os.path.join(config.site_dir, self.css_filename))
240242

241243
if self.inventory_enabled:
242244
log.debug("Creating inventory file objects.inv")
243245
inv_contents = self.handlers.inventory.format_sphinx()
244-
write_file(inv_contents, os.path.join(config["site_dir"], "objects.inv"))
246+
write_file(inv_contents, os.path.join(config.site_dir, "objects.inv"))
245247

246248
if self._inv_futures:
247249
log.debug(f"Waiting for {len(self._inv_futures)} inventory download(s)")
@@ -256,12 +258,12 @@ def on_env(self, env: Environment, config: Config, *args: Any, **kwargs: Any) ->
256258
loader_name = loader.__func__.__qualname__
257259
log.error(f"Couldn't load inventory {import_item} through {loader_name}: {error}") # noqa: TRY400
258260
for page, identifier in results.items():
259-
config["plugins"]["autorefs"].register_url(page, identifier)
261+
config.plugins["autorefs"].register_url(page, identifier)
260262
self._inv_futures = {}
261263

262264
def on_post_build(
263265
self,
264-
config: Config, # noqa: ARG002
266+
config: MkDocsConfig, # noqa: ARG002
265267
**kwargs: Any, # noqa: ARG002
266268
) -> None:
267269
"""Teardown the handlers.

tests/conftest.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import pytest
99
from markdown.core import Markdown
1010
from mkdocs import config
11-
from mkdocs.config.defaults import get_schema
11+
from mkdocs.config.defaults import MkDocsConfig
1212

1313
if TYPE_CHECKING:
1414
from pathlib import Path
@@ -19,7 +19,7 @@
1919
@pytest.fixture(name="mkdocs_conf")
2020
def fixture_mkdocs_conf(request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[config.Config]:
2121
"""Yield a MkDocs configuration object."""
22-
conf = config.Config(schema=get_schema()) # type: ignore[call-arg]
22+
conf = MkDocsConfig()
2323
while hasattr(request, "_parent_request") and hasattr(request._parent_request, "_parent_request"):
2424
request = request._parent_request
2525

@@ -53,6 +53,6 @@ def fixture_plugin(mkdocs_conf: config.Config) -> MkdocstringsPlugin:
5353

5454

5555
@pytest.fixture(name="ext_markdown")
56-
def fixture_ext_markdown(mkdocs_conf: config.Config) -> Markdown:
56+
def fixture_ext_markdown(mkdocs_conf: MkDocsConfig) -> Markdown:
5757
"""Return a Markdown instance with MkdocstringsExtension."""
5858
return Markdown(extensions=mkdocs_conf["markdown_extensions"], extension_configs=mkdocs_conf["mdx_configs"])

0 commit comments

Comments
 (0)