Debian Codegraph @

src/mkdocstrings_handlers/python/_internal/handler.py

raw
1 # This module implements a handler for the Python language.
2
3 from __future__ import annotations
4
5 import glob
6 import inspect
7 import os
8 import posixpath
9 import sys
10 from contextlib import suppress
11 from dataclasses import asdict
12 from pathlib import Path
13 from typing import TYPE_CHECKING, Any, BinaryIO, Callable, ClassVar
14
15 from griffe import (
16 AliasResolutionError,
17 GriffeLoader,
18 LinesCollection,
19 ModulesCollection,
20 Parser,
21 load_extensions,
22 parse_auto,
23 parse_google,
24 parse_numpy,
25 parse_sphinx,
26 patch_loggers,
27 )
28 from mkdocs.exceptions import PluginError
29 from mkdocs_autorefs import BacklinkCrumb
30 from mkdocstrings import BaseHandler, CollectionError, CollectorItem, HandlerOptions, Inventory, get_logger
31
32 from mkdocstrings_handlers.python._internal import rendering
33 from mkdocstrings_handlers.python._internal.config import PythonConfig, PythonOptions
34
35 if TYPE_CHECKING:
36 from collections.abc import Iterable, Iterator, Mapping, MutableMapping, Sequence
37
38 from mkdocs.config.defaults import MkDocsConfig
39 from mkdocs_autorefs import Backlink
40
41
42 # YORE: EOL 3.10: Replace block with line 2.
43 if sys.version_info >= (3, 11):
44 from contextlib import chdir
45 else:
46 from contextlib import contextmanager
47
48 @contextmanager
49 def chdir(path: str) -> Iterator[None]:
50 old_wd = os.getcwd()
51 os.chdir(path)
52 try:
53 yield
54 finally:
55 os.chdir(old_wd)
56
57
58 _logger = get_logger(__name__)
59
60 patch_loggers(get_logger)
61
62 _PARSER_FUNCTIONS: dict[Parser, Callable] = {
63 Parser.auto: parse_auto,
64 Parser.google: parse_google,
65 Parser.numpy: parse_numpy,
66 Parser.sphinx: parse_sphinx,
67 }
68
69
70 def _filter_parser_options(parser: Parser | None, options: dict[str, Any] | None) -> dict[str, Any] | None:
71 """Filter options unsupported by the selected Griffe parser."""
72 if parser is None or options is None:
73 return options
74
75 accepted_options = set(inspect.signature(_PARSER_FUNCTIONS[parser]).parameters) - {"docstring"}
76 filtered_options = {}
77 for name, value in options.items():
78 if name in accepted_options:
79 if parser is Parser.auto and name == "per_style_options":
80 filtered_options[name] = {
81 style: _filter_parser_options(Parser(style), style_options)
82 for style, style_options in value.items()
83 }
84 else:
85 filtered_options[name] = value
86 else:
87 _logger.warning(f"Ignoring unsupported {parser.value} docstring parser option: {name}")
88 return filtered_options
89
90
91 class PythonHandler(BaseHandler):
92 """The Python handler class."""
93
94 name: ClassVar[str] = "python"
95 """The handler's name."""
96
97 domain: ClassVar[str] = "py"
98 """The cross-documentation domain/language for this handler."""
99
100 enable_inventory: ClassVar[bool] = True
101 """Whether this handler is interested in enabling the creation of the `objects.inv` Sphinx inventory file."""
102
103 fallback_theme: ClassVar[str] = "material"
104 """The fallback theme."""
105
106 def __init__(self, config: PythonConfig, base_dir: Path, **kwargs: Any) -> None:
107 """Initialize the handler.
108
109 Parameters:
110 config: The handler configuration.
111 base_dir: The base directory of the project.
112 **kwargs: Arguments passed to the parent constructor.
113 """
114 super().__init__(**kwargs)
115
116 self.config = config
117 """The handler configuration."""
118 self.base_dir = base_dir
119 """The base directory of the project."""
120
121 self.global_options = config.options
122 """The global configuration options (in `mkdocs.yml`)."""
123
124 # Warn if user overrides base templates.
125 if self.custom_templates:
126 for theme_dir in base_dir.joinpath(self.custom_templates, "python").iterdir():
127 if theme_dir.joinpath("_base").is_dir():
128 _logger.warning(
129 f"Overriding base template '{theme_dir.name}/_base/<template>.html.jinja' is not supported, "
130 f"override '{theme_dir.name}/<template>.html.jinja' instead",
131 )
132
133 paths = config.paths or []
134
135 # Expand paths with glob patterns.
136 with chdir(str(base_dir)):
137 resolved_globs = [glob.glob(path) for path in paths]
138 paths = [path for glob_list in resolved_globs for path in glob_list]
139
140 # By default, add the base directory to the search paths.
141 if not paths:
142 paths.append(str(base_dir))
143
144 # Initialize search paths from `sys.path`, eliminating empty paths.
145 search_paths = [path for path in sys.path if path]
146
147 for path in reversed(paths):
148 # If it's not absolute, make path relative to the config file path, then make it absolute.
149 if not os.path.isabs(path):
150 path = os.path.abspath(base_dir / path) # noqa: PLW2901
151 # Remove pre-listed paths.
152 if path in search_paths:
153 search_paths.remove(path)
154 # Give precedence to user-provided paths.
155 search_paths.insert(0, path)
156
157 self._paths = search_paths
158 self._modules_collection: ModulesCollection = ModulesCollection()
159 self._lines_collection: LinesCollection = LinesCollection()
160
161 def get_inventory_urls(self) -> list[tuple[str, dict[str, Any]]]:
162 """Return the URLs of the inventory files to download."""
163 return [(inv.url, inv._config) for inv in self.config.inventories]
164
165 @staticmethod
166 def load_inventory(
167 in_file: BinaryIO,
168 url: str,
169 base_url: str | None = None,
170 domains: list[str] | None = None,
171 **kwargs: Any, # noqa: ARG004
172 ) -> Iterator[tuple[str, str]]:
173 """Yield items and their URLs from an inventory file streamed from `in_file`.
174
175 This implements mkdocstrings' `load_inventory` "protocol" (see [`mkdocstrings.BaseHandler.load_inventory`][]).
176
177 Arguments:
178 in_file: The binary file-like object to read the inventory from.
179 url: The URL that this file is being streamed from (used to guess `base_url`).
180 base_url: The URL that this inventory's sub-paths are relative to.
181 domains: A list of domain strings to filter the inventory by, when not passed, "py" will be used.
182 **kwargs: Ignore additional arguments passed from the config.
183
184 Yields:
185 Tuples of (item identifier, item URL).
186 """
187 domains = domains or ["py"]
188 if base_url is None:
189 base_url = posixpath.dirname(url)
190
191 for item in Inventory.parse_sphinx(in_file, domain_filter=domains).values():
192 yield item.name, posixpath.join(base_url, item.uri)
193
194 def get_options(self, local_options: Mapping[str, Any]) -> HandlerOptions:
195 """Get combined default, global and local options.
196
197 Arguments:
198 local_options: The local options.
199
200 Returns:
201 The combined options.
202 """
203 extra = {**self.global_options.get("extra", {}), **local_options.get("extra", {})}
204 options = {**self.global_options, **local_options, "extra": extra}
205 try:
206 return PythonOptions.from_data(**options)
207 except Exception as error:
208 raise PluginError(f"Invalid options: {error}") from error
209
210 def collect(self, identifier: str, options: PythonOptions) -> CollectorItem:
211 """Collect the documentation for the given identifier.
212
213 Parameters:
214 identifier: The identifier of the object to collect.
215 options: The options to use for the collection.
216
217 Returns:
218 The collected item.
219 """
220 module_name = identifier.split(".", 1)[0]
221 unknown_module = module_name not in self._modules_collection
222 reapply = True
223 if options == {}:
224 if unknown_module:
225 raise CollectionError("Not loading additional modules during fallback")
226 options = self.get_options({})
227 reapply = False
228
229 parser_name = options.docstring_style
230 parser = parser_name and Parser(parser_name)
231 parser_options: dict[str, Any] | None = None
232 if options.docstring_options is not None:
233 parser_options = _filter_parser_options(parser, asdict(options.docstring_options))
234
235 if unknown_module:
236 extensions = self.normalize_extension_paths(options.extensions)
237 loader = GriffeLoader(
238 extensions=load_extensions(*extensions),
239 search_paths=self._paths,
240 docstring_parser=parser,
241 docstring_options=parser_options, # type: ignore[arg-type]
242 modules_collection=self._modules_collection,
243 lines_collection=self._lines_collection,
244 allow_inspection=options.allow_inspection,
245 force_inspection=options.force_inspection,
246 )
247 try:
248 for pre_loaded_module in options.preload_modules:
249 if pre_loaded_module not in self._modules_collection:
250 loader.load(
251 pre_loaded_module,
252 try_relative_path=False,
253 find_stubs_package=options.find_stubs_package,
254 )
255 loader.load(
256 module_name,
257 try_relative_path=False,
258 find_stubs_package=options.find_stubs_package,
259 )
260 except ImportError as error:
261 raise CollectionError(str(error)) from error
262 unresolved, iterations = loader.resolve_aliases(
263 implicit=False,
264 external=self.config.load_external_modules,
265 )
266 if unresolved:
267 _logger.debug(f"{len(unresolved)} aliases were still unresolved after {iterations} iterations")
268 _logger.debug(f"Unresolved aliases: {', '.join(sorted(unresolved))}")
269
270 try:
271 doc_object = self._modules_collection[identifier]
272 except KeyError as error:
273 raise CollectionError(f"{identifier} could not be found") from error
274 except AliasResolutionError as error:
275 raise CollectionError(str(error)) from error
276
277 if not unknown_module and reapply:
278 with suppress(AliasResolutionError):
279 if doc_object.docstring is not None:
280 doc_object.docstring.parser = parser
281 doc_object.docstring.parser_options = parser_options or {}
282
283 return doc_object
284
285 def render(self, data: CollectorItem, options: PythonOptions, locale: str | None = None) -> str:
286 """Render the collected data.
287
288 Parameters:
289 data: The collected data.
290 options: The options to use for rendering.
291 locale: The locale to use for rendering (default is "en").
292
293 Returns:
294 The rendered data (HTML).
295 """
296 template_name = rendering.do_get_template(data)
297 template = self.env.get_template(template_name)
298
299 return template.render(
300 **{
301 "config": options,
302 data.kind.value.replace(" ", "_"): data,
303 # Heading level is a "state" variable, that will change at each step
304 # of the rendering recursion. Therefore, it's easier to use it as a plain value
305 # than as an item in a dictionary.
306 "heading_level": options.heading_level,
307 "root": True,
308 "locale": locale or "en",
309 },
310 )
311
312 def render_backlinks(self, backlinks: Mapping[str, Iterable[Backlink]], *, locale: str | None = None) -> str: # noqa: ARG002
313 """Render the backlinks.
314
315 Parameters:
316 backlinks: The backlinks to render.
317
318 Returns:
319 The rendered backlinks (HTML).
320 """
321 template = self.env.get_template("backlinks.html.jinja")
322 verbose_type = {key: key.capitalize().replace("-by", " by") for key in backlinks.keys()} # noqa: SIM118
323 return template.render(
324 backlinks=backlinks,
325 config=self.get_options({}),
326 verbose_type=verbose_type,
327 default_crumb=BacklinkCrumb(title="", url=""),
328 )
329
330 def update_env(self, config: Any) -> None: # noqa: ARG002
331 """Update the Jinja environment with custom filters and tests.
332
333 Parameters:
334 config: The SSG configuration.
335 """
336 self.env.trim_blocks = True
337 self.env.lstrip_blocks = True
338 self.env.keep_trailing_newline = False
339 self.env.filters["split_path"] = rendering.do_split_path
340 self.env.filters["order_members"] = rendering.do_order_members
341 self.env.filters["format_code"] = rendering.do_format_code
342 self.env.filters["format_signature"] = rendering.do_format_signature
343 self.env.filters["format_attribute"] = rendering.do_format_attribute
344 self.env.filters["format_type_alias"] = rendering.do_format_type_alias
345 self.env.filters["filter_objects"] = rendering.do_filter_objects
346 self.env.filters["stash_crossref"] = rendering.do_stash_crossref
347 self.env.filters["get_template"] = rendering.do_get_template
348 self.env.filters["source_location"] = rendering.do_source_location
349 self.env.filters["as_attributes_section"] = rendering.do_as_attributes_section
350 self.env.filters["as_functions_section"] = rendering.do_as_functions_section
351 self.env.filters["as_classes_section"] = rendering.do_as_classes_section
352 self.env.filters["as_type_aliases_section"] = rendering.do_as_type_aliases_section
353 self.env.filters["as_modules_section"] = rendering.do_as_modules_section
354 self.env.filters["backlink_tree"] = rendering.do_backlink_tree
355 self.env.globals["AutorefsHook"] = rendering.AutorefsHook
356 self.env.tests["existing_template"] = lambda template_name: template_name in self.env.list_templates()
357
358 def get_aliases(self, identifier: str) -> tuple[str, ...]:
359 """Get the aliases for the given identifier.
360
361 Parameters:
362 identifier: The identifier to get the aliases for.
363
364 Returns:
365 The aliases.
366 """
367 if "(" in identifier:
368 identifier, parameter = identifier.split("(", 1)
369 parameter = parameter.removesuffix(")")
370 else:
371 parameter = ""
372 try:
373 data = self._modules_collection[identifier]
374 except (KeyError, AliasResolutionError):
375 return ()
376 aliases = [data.path]
377 try:
378 for alias in [data.canonical_path, *data.aliases]:
379 if alias not in aliases:
380 aliases.append(alias)
381 except AliasResolutionError:
382 pass
383 if parameter:
384 return tuple(f"{alias}({parameter})" for alias in aliases)
385 return tuple(aliases)
386
387 def normalize_extension_paths(self, extensions: Sequence) -> list[str | dict[str, Any]]:
388 """Resolve extension paths relative to config file.
389
390 Parameters:
391 extensions: The extensions (configuration) to normalize.
392
393 Returns:
394 The normalized extensions.
395 """
396 normalized: list[str | dict[str, Any]] = []
397
398 for ext in extensions:
399 if isinstance(ext, dict):
400 pth, options = next(iter(ext.items()))
401 pth = str(pth)
402 else:
403 pth = str(ext)
404 options = None
405
406 if pth.endswith(".py") or ".py:" in pth or "/" in pth or "\\" in pth:
407 # This is a system path. Normalize it, make it absolute relative to config file path.
408 pth = os.path.abspath(self.base_dir / pth)
409
410 if options is not None:
411 normalized.append({pth: options})
412 else:
413 normalized.append(pth)
414
415 return normalized
416
417
418 def get_handler(
419 handler_config: MutableMapping[str, Any],
420 tool_config: MkDocsConfig,
421 **kwargs: Any,
422 ) -> PythonHandler:
423 """Return an instance of `PythonHandler`.
424
425 Parameters:
426 handler_config: The handler configuration.
427 tool_config: The tool (SSG) configuration.
428 **kwargs: Additional arguments to pass to the handler.
429
430 Returns:
431 An instance of `PythonHandler`.
432 """
433 # In rare cases, Griffe hits the recursion limit because of deeply-nested ASTs.
434 # We therefore increase the limit here, once, before Griffe is used to collect or render stuff.
435 sys.setrecursionlimit(max(sys.getrecursionlimit(), 2000))
436
437 base_dir = Path(getattr(tool_config, "config_file_path", None) or "./mkdocs.yml").parent
438 return PythonHandler(
439 config=PythonConfig.from_data(**handler_config),
440 base_dir=base_dir,
441 **kwargs,
442 )