-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhandler.py
More file actions
143 lines (122 loc) · 5.34 KB
/
handler.py
File metadata and controls
143 lines (122 loc) · 5.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# Copyright (c) 2022-2026. Analog Devices Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Implementation of python_xref handler
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field, fields
from functools import partial
from pathlib import Path
from typing import Any, ClassVar, Mapping, MutableMapping, Optional
from warnings import warn
from mkdocs.config.defaults import MkDocsConfig
from mkdocstrings import CollectorItem, get_logger
from mkdocstrings_handlers.python import PythonHandler, PythonOptions, PythonConfig
from .crossref import substitute_relative_crossrefs
__all__ = [
'PythonRelXRefHandler'
]
logger = get_logger(__name__)
@dataclass(frozen=True, kw_only=True)
class PythonRelXRefOptions(PythonOptions):
check_crossrefs: bool = True
check_crossrefs_exclude: list[str | re.Pattern] = field(default_factory=list)
class PythonRelXRefHandler(PythonHandler):
"""Extended version of mkdocstrings Python handler
* Converts relative cross-references into full references
* Checks cross-references early in order to produce errors with source location
"""
name: ClassVar[str] = "python_xref"
"""Override the handler name"""
def __init__(self, config: PythonConfig, base_dir: Path, **kwargs: Any) -> None:
"""Initialize the handler.
Parameters:
config: The handler configuration.
base_dir: The base directory of the project.
**kwargs: Arguments passed to the parent constructor.
"""
self.check_crossrefs = config.options.pop('check_crossrefs', True)
exclude = config.options.pop('check_crossrefs_exclude', [])
self.check_crossrefs_exclude = [re.compile(p) for p in exclude]
super().__init__(config, base_dir, **kwargs)
def get_options(self, local_options: Mapping[str, Any]) -> PythonRelXRefOptions:
local_options = dict(local_options)
check_crossrefs = local_options.pop(
'check_crossrefs', self.check_crossrefs)
check_crossrefs_exclude = local_options.pop(
'check_crossrefs_exclude', self.check_crossrefs_exclude)
_opts = super().get_options(local_options)
opts = PythonRelXRefOptions(
check_crossrefs=check_crossrefs,
check_crossrefs_exclude=check_crossrefs_exclude,
**{field.name: getattr(_opts, field.name) for field in fields(_opts)}
)
return opts
def render(self, data: CollectorItem, options: PythonOptions, locale: str | None = None) -> str:
if options.relative_crossrefs:
if isinstance(options, PythonRelXRefOptions) and options.check_crossrefs:
checkref = partial(
self._check_ref, exclude=options.check_crossrefs_exclude)
else:
checkref = None
substitute_relative_crossrefs(data, checkref=checkref)
try:
return super().render(data, options, locale=locale)
except Exception: # pragma: no cover
print(f"{data.path=}")
raise
def get_templates_dir(self, handler: Optional[str] = None) -> Path:
"""See [render][.barf]"""
# use same templates as standard python handler
if handler == self.name:
handler = 'python'
return super().get_templates_dir(handler)
def get_extended_templates_dirs(self, handler: str) -> list[Path]:
# use same templates as standard python handler
if handler == self.name:
handler = 'python'
return super().get_extended_templates_dirs(handler)
def _check_ref(self, ref : str, exclude: list[str | re.Pattern] = []) -> bool:
"""Check for existence of reference"""
for ex in exclude:
if re.match(ex, ref):
return True
try:
self.collect(ref, PythonOptions())
return True
except Exception: # pylint: disable=broad-except
# Only expect a CollectionError but we may as well catch everything.
return False
def get_handler(
handler_config: MutableMapping[str, Any],
tool_config: MkDocsConfig,
**kwargs: Any,
) -> PythonHandler:
"""Simply return an instance of `PythonRelXRefHandler`.
Arguments:
handler_config: The handler configuration.
tool_config: The tool (SSG) configuration.
Returns:
An instance of `PythonRelXRefHandler`.
"""
base_dir = Path(tool_config.config_file_path or "./mkdocs.yml").parent
if "inventories" not in handler_config and "import" in handler_config:
warn("The 'import' key is renamed 'inventories' for the Python handler", FutureWarning, stacklevel=1)
handler_config["inventories"] = handler_config.pop("import", [])
return PythonRelXRefHandler(
config=PythonConfig.from_data(**handler_config),
base_dir=base_dir,
**kwargs,
)