Debian Codegraph @

mkdocs/config/base.py

raw
1 from __future__ import annotations
2
3 import functools
4 import logging
5 import os
6 import sys
7 import warnings
8 from collections import UserDict
9 from contextlib import contextmanager
10 from typing import (
11 IO,
12 TYPE_CHECKING,
13 Any,
14 Generic,
15 Iterator,
16 List,
17 Mapping,
18 Sequence,
19 Tuple,
20 TypeVar,
21 overload,
22 )
23
24 from mkdocs import exceptions, utils
25 from mkdocs.utils import weak_property
26
27 if TYPE_CHECKING:
28 from mkdocs.config.defaults import MkDocsConfig
29
30
31 log = logging.getLogger('mkdocs.config')
32
33
34 T = TypeVar('T')
35
36
37 class BaseConfigOption(Generic[T]):
38 def __init__(self) -> None:
39 self.warnings: list[str] = []
40 self.default = None
41
42 @property
43 def default(self):
44 try:
45 # ensure no mutable values are assigned
46 return self._default.copy()
47 except AttributeError:
48 return self._default
49
50 @default.setter
51 def default(self, value):
52 self._default = value
53
54 def validate(self, value: object, /) -> T:
55 return self.run_validation(value)
56
57 def reset_warnings(self) -> None:
58 self.warnings = []
59
60 def pre_validation(self, config: Config, key_name: str) -> None:
61 """
62 Before all options are validated, perform a pre-validation process.
63
64 The pre-validation process method should be implemented by subclasses.
65 """
66
67 def run_validation(self, value: object, /):
68 """
69 Perform validation for a value.
70
71 The run_validation method should be implemented by subclasses.
72 """
73 return value
74
75 def post_validation(self, config: Config, key_name: str) -> None:
76 """
77 After all options have passed validation, perform a post-validation
78 process to do any additional changes dependent on other config values.
79
80 The post-validation process method should be implemented by subclasses.
81 """
82
83 def __set_name__(self, owner, name):
84 if name.endswith('_') and not name.startswith('_'):
85 name = name[:-1]
86 self._name = name
87
88 @overload
89 def __get__(self, obj: Config, type=None) -> T:
90 ...
91
92 @overload
93 def __get__(self, obj, type=None) -> BaseConfigOption:
94 ...
95
96 def __get__(self, obj, type=None):
97 if not isinstance(obj, Config):
98 return self
99 return obj[self._name]
100
101 def __set__(self, obj, value: T):
102 if not isinstance(obj, Config):
103 raise AttributeError(
104 f"can't set attribute ({self._name}) because the parent is a {type(obj)} not a {Config}"
105 )
106 obj[self._name] = value
107
108
109 class ValidationError(Exception):
110 """Raised during the validation process of the config on errors."""
111
112 def __eq__(self, other):
113 return type(self) is type(other) and str(self) == str(other)
114
115
116 PlainConfigSchemaItem = Tuple[str, BaseConfigOption]
117 PlainConfigSchema = Sequence[PlainConfigSchemaItem]
118
119 ConfigErrors = List[Tuple[str, Exception]]
120 ConfigWarnings = List[Tuple[str, str]]
121
122
123 class Config(UserDict):
124 """
125 Base class for MkDocs configuration, plugin configuration (and sub-configuration) objects.
126
127 It should be subclassed and have `ConfigOption`s defined as attributes.
128 For examples, see mkdocs/contrib/search/__init__.py and mkdocs/config/defaults.py.
129
130 Behavior as it was prior to MkDocs 1.4 is now handled by LegacyConfig.
131 """
132
133 _schema: PlainConfigSchema
134 config_file_path: str
135
136 def __init_subclass__(cls):
137 schema = dict(getattr(cls, '_schema', ()))
138 for attr_name, attr in cls.__dict__.items():
139 if isinstance(attr, BaseConfigOption):
140 schema[getattr(attr, '_name', attr_name)] = attr
141 cls._schema = tuple(schema.items())
142
143 for attr_name, attr in cls._schema:
144 attr.required = True
145 if getattr(attr, '_legacy_required', None) is not None:
146 raise TypeError(
147 f"{cls.__name__}.{attr_name}: "
148 "Setting 'required' is unsupported in class-based configs. "
149 "All values are required, or can be wrapped into config_options.Optional"
150 )
151
152 def __new__(cls, *args, **kwargs) -> Config:
153 """Compatibility: allow referring to `LegacyConfig(...)` constructor as `Config(...)`."""
154 if cls is Config:
155 return LegacyConfig(*args, **kwargs)
156 return super().__new__(cls)
157
158 def __init__(self, config_file_path: str | bytes | None = None):
159 super().__init__()
160 self.__user_configs: list[dict] = []
161 self.set_defaults()
162
163 self._schema_keys = {k for k, v in self._schema}
164 # Ensure config_file_path is a Unicode string
165 if config_file_path is not None and not isinstance(config_file_path, str):
166 try:
167 # Assume config_file_path is encoded with the file system encoding.
168 config_file_path = config_file_path.decode(encoding=sys.getfilesystemencoding())
169 except UnicodeDecodeError:
170 raise ValidationError("config_file_path is not a Unicode string.")
171 self.config_file_path = config_file_path or ''
172
173 def set_defaults(self) -> None:
174 """
175 Set the base config by going through each validator and getting the
176 default if it has one.
177 """
178 for key, config_option in self._schema:
179 self[key] = config_option.default
180
181 def _validate(self) -> tuple[ConfigErrors, ConfigWarnings]:
182 failed: ConfigErrors = []
183 warnings: ConfigWarnings = []
184
185 for key, config_option in self._schema:
186 try:
187 value = self.get(key)
188 self[key] = config_option.validate(value)
189 warnings.extend((key, w) for w in config_option.warnings)
190 config_option.reset_warnings()
191 except ValidationError as e:
192 failed.append((key, e))
193 break
194
195 for key in set(self.keys()) - self._schema_keys:
196 warnings.append((key, f"Unrecognised configuration name: {key}"))
197
198 return failed, warnings
199
200 def _pre_validate(self) -> tuple[ConfigErrors, ConfigWarnings]:
201 failed: ConfigErrors = []
202 warnings: ConfigWarnings = []
203
204 for key, config_option in self._schema:
205 try:
206 config_option.pre_validation(self, key_name=key)
207 warnings.extend((key, w) for w in config_option.warnings)
208 config_option.reset_warnings()
209 except ValidationError as e:
210 failed.append((key, e))
211
212 return failed, warnings
213
214 def _post_validate(self) -> tuple[ConfigErrors, ConfigWarnings]:
215 failed: ConfigErrors = []
216 warnings: ConfigWarnings = []
217
218 for key, config_option in self._schema:
219 try:
220 config_option.post_validation(self, key_name=key)
221 warnings.extend((key, w) for w in config_option.warnings)
222 config_option.reset_warnings()
223 except ValidationError as e:
224 failed.append((key, e))
225
226 return failed, warnings
227
228 def validate(self) -> tuple[ConfigErrors, ConfigWarnings]:
229 failed, warnings = self._pre_validate()
230
231 run_failed, run_warnings = self._validate()
232
233 failed.extend(run_failed)
234 warnings.extend(run_warnings)
235
236 # Only run the post validation steps if there are no failures, warnings
237 # are okay.
238 if len(failed) == 0:
239 post_failed, post_warnings = self._post_validate()
240 failed.extend(post_failed)
241 warnings.extend(post_warnings)
242
243 return failed, warnings
244
245 def load_dict(self, patch: dict) -> None:
246 """Load config options from a dictionary."""
247 if not isinstance(patch, dict):
248 raise exceptions.ConfigurationError(
249 "The configuration is invalid. Expected a key-"
250 f"value mapping (dict) but received: {type(patch)}"
251 )
252
253 self.__user_configs.append(patch)
254 self.update(patch)
255
256 def load_file(self, config_file: IO) -> None:
257 """Load config options from the open file descriptor of a YAML file."""
258 warnings.warn(
259 "Config.load_file is not used since MkDocs 1.5 and will be removed soon. "
260 "Use MkDocsConfig.load_file instead",
261 DeprecationWarning,
262 )
263 return self.load_dict(utils.yaml_load(config_file))
264
265 @weak_property
266 def user_configs(self) -> Sequence[Mapping[str, Any]]:
267 warnings.warn(
268 "user_configs is never used in MkDocs and will be removed soon.", DeprecationWarning
269 )
270 return self.__user_configs
271
272
273 @functools.lru_cache(maxsize=None)
274 def get_schema(cls: type) -> PlainConfigSchema:
275 """Extract ConfigOptions defined in a class (used just as a container) and put them into a schema tuple."""
276 if issubclass(cls, Config):
277 return cls._schema
278 return tuple((k, v) for k, v in cls.__dict__.items() if isinstance(v, BaseConfigOption))
279
280
281 class LegacyConfig(Config):
282 """A configuration object for plugins, as just a dict without type-safe attribute access."""
283
284 def __init__(self, schema: PlainConfigSchema, config_file_path: str | None = None):
285 self._schema = tuple((k, v) for k, v in schema) # Re-create just for validation
286 super().__init__(config_file_path)
287
288
289 @contextmanager
290 def _open_config_file(config_file: str | IO | None) -> Iterator[IO]:
291 """
292 A context manager which yields an open file descriptor ready to be read.
293
294 Accepts a filename as a string, an open or closed file descriptor, or None.
295 When None, it defaults to `mkdocs.yml` in the CWD. If a closed file descriptor
296 is received, a new file descriptor is opened for the same file.
297
298 The file descriptor is automatically closed when the context manager block is existed.
299 """
300 # Default to the standard config filename.
301 if config_file is None:
302 paths_to_try = ['mkdocs.yml', 'mkdocs.yaml']
303 # If it is a string, we can assume it is a path and attempt to open it.
304 elif isinstance(config_file, str):
305 paths_to_try = [config_file]
306 # If closed file descriptor, get file path to reopen later.
307 elif getattr(config_file, 'closed', False):
308 paths_to_try = [config_file.name]
309 else:
310 result_config_file = config_file
311 paths_to_try = None
312
313 if paths_to_try:
314 # config_file is not a file descriptor, so open it as a path.
315 for path in paths_to_try:
316 path = os.path.abspath(path)
317 log.debug(f"Loading configuration file: {path}")
318 try:
319 result_config_file = open(path, 'rb')
320 break
321 except FileNotFoundError:
322 continue
323 else:
324 raise exceptions.ConfigurationError(f"Config file '{paths_to_try[0]}' does not exist.")
325 else:
326 log.debug(f"Loading configuration file: {result_config_file}")
327 # Ensure file descriptor is at beginning
328 try:
329 result_config_file.seek(0)
330 except OSError:
331 pass
332
333 try:
334 yield result_config_file
335 finally:
336 if hasattr(result_config_file, 'close'):
337 result_config_file.close()
338
339
340 def load_config(
341 config_file: str | IO | None = None, *, config_file_path: str | None = None, **kwargs
342 ) -> MkDocsConfig:
343 """
344 Load the configuration for a given file object or name.
345
346 The config_file can either be a file object, string or None. If it is None
347 the default `mkdocs.yml` filename will loaded.
348
349 Extra kwargs are passed to the configuration to replace any default values
350 unless they themselves are None.
351 """
352 options = kwargs.copy()
353
354 # Filter None values from the options. This usually happens with optional
355 # parameters from Click.
356 for key, value in options.copy().items():
357 if value is None:
358 options.pop(key)
359
360 with _open_config_file(config_file) as fd:
361 # Initialize the config with the default schema.
362 from mkdocs.config.defaults import MkDocsConfig
363
364 if config_file_path is None:
365 if sys.stdin and fd is not sys.stdin.buffer:
366 config_file_path = getattr(fd, 'name', None)
367 cfg = MkDocsConfig(config_file_path=config_file_path)
368 # load the config file
369 cfg.load_file(fd)
370
371 # Then load the options to overwrite anything in the config.
372 cfg.load_dict(options)
373
374 errors, warnings = cfg.validate()
375
376 for config_name, warning in warnings:
377 log.warning(f"Config value '{config_name}': {warning}")
378
379 for config_name, error in errors:
380 log.error(f"Config value '{config_name}': {error}")
381
382 for key, value in cfg.items():
383 log.debug(f"Config value '{key}' = {value!r}")
384
385 if len(errors) > 0:
386 raise exceptions.Abort("Aborted with a configuration error!")
387 elif cfg.strict and len(warnings) > 0:
388 raise exceptions.Abort(
389 f"Aborted with {len(warnings)} configuration warnings in 'strict' mode!"
390 )
391
392 return cfg