| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import functools |
| 4 |
import ipaddress |
| 5 |
import logging |
| 6 |
import os |
| 7 |
import string |
| 8 |
import sys |
| 9 |
import traceback |
| 10 |
import types |
| 11 |
import warnings |
| 12 |
from collections import Counter, UserString |
| 13 |
from types import SimpleNamespace |
| 14 |
from typing import ( |
| 15 |
Any, |
| 16 |
Callable, |
| 17 |
Collection, |
| 18 |
Dict, |
| 19 |
Generic, |
| 20 |
Iterator, |
| 21 |
List, |
| 22 |
Mapping, |
| 23 |
MutableMapping, |
| 24 |
NamedTuple, |
| 25 |
TypeVar, |
| 26 |
Union, |
| 27 |
overload, |
| 28 |
) |
| 29 |
from urllib.parse import quote as urlquote |
| 30 |
from urllib.parse import urlsplit, urlunsplit |
| 31 |
|
| 32 |
import markdown |
| 33 |
import pathspec |
| 34 |
import pathspec.gitignore |
| 35 |
|
| 36 |
from mkdocs import plugins, theme, utils |
| 37 |
from mkdocs.config.base import ( |
| 38 |
BaseConfigOption, |
| 39 |
Config, |
| 40 |
LegacyConfig, |
| 41 |
PlainConfigSchemaItem, |
| 42 |
ValidationError, |
| 43 |
) |
| 44 |
from mkdocs.exceptions import ConfigurationError |
| 45 |
|
| 46 |
T = TypeVar('T') |
| 47 |
SomeConfig = TypeVar('SomeConfig', bound=Config) |
| 48 |
|
| 49 |
log = logging.getLogger(__name__) |
| 50 |
|
| 51 |
|
| 52 |
class SubConfig(Generic[SomeConfig], BaseConfigOption[SomeConfig]): |
| 53 |
""" |
| 54 |
Subconfig Config Option. |
| 55 |
|
| 56 |
New: If targeting MkDocs 1.4+, please pass a subclass of Config to the |
| 57 |
constructor, instead of the old style of a sequence of ConfigOption instances. |
| 58 |
Validation is then enabled by default. |
| 59 |
|
| 60 |
A set of `config_options` grouped under a single config option. |
| 61 |
By default, validation errors and warnings resulting from validating |
| 62 |
`config_options` are ignored (`validate=False`). Users should typically |
| 63 |
enable validation with `validate=True`. |
| 64 |
""" |
| 65 |
|
| 66 |
_config_file_path: str | None = None |
| 67 |
config_class: type[SomeConfig] |
| 68 |
|
| 69 |
@overload |
| 70 |
def __init__( |
| 71 |
self: SubConfig[SomeConfig], config_class: type[SomeConfig], /, *, validate: bool = True |
| 72 |
): |
| 73 |
"""Create a sub-config in a type-safe way, using fields defined in a Config subclass.""" |
| 74 |
|
| 75 |
@overload |
| 76 |
def __init__( |
| 77 |
self: SubConfig[LegacyConfig], |
| 78 |
*config_options: PlainConfigSchemaItem, |
| 79 |
validate: bool = False, |
| 80 |
): |
| 81 |
"""Create an untyped sub-config, using directly passed fields.""" |
| 82 |
|
| 83 |
def __init__(self, *config_options, validate=None): |
| 84 |
super().__init__() |
| 85 |
self.default = {} |
| 86 |
self._do_validation = True if validate is None else validate |
| 87 |
if type(self) is SubConfig: |
| 88 |
if ( |
| 89 |
len(config_options) == 1 |
| 90 |
and isinstance(config_options[0], type) |
| 91 |
and issubclass(config_options[0], Config) |
| 92 |
): |
| 93 |
(self.config_class,) = config_options |
| 94 |
else: |
| 95 |
self.config_class = functools.partial(LegacyConfig, config_options) |
| 96 |
self._do_validation = False if validate is None else validate |
| 97 |
|
| 98 |
def __class_getitem__(cls, config_class: type[Config]): |
| 99 |
"""Eliminates the need to write `config_class = FooConfig` when subclassing SubConfig[FooConfig].""" |
| 100 |
name = f'{cls.__name__}[{config_class.__name__}]' |
| 101 |
return type(name, (cls,), dict(config_class=config_class)) |
| 102 |
|
| 103 |
def pre_validation(self, config: Config, key_name: str): |
| 104 |
self._config_file_path = config.config_file_path |
| 105 |
|
| 106 |
def run_validation(self, value: object) -> SomeConfig: |
| 107 |
config = self.config_class(config_file_path=self._config_file_path) |
| 108 |
try: |
| 109 |
config.load_dict(value) # type: ignore |
| 110 |
failed, warnings = config.validate() |
| 111 |
except ConfigurationError as e: |
| 112 |
raise ValidationError(str(e)) |
| 113 |
|
| 114 |
if self._do_validation: |
| 115 |
# Capture errors and warnings |
| 116 |
self.warnings.extend(f"Sub-option '{key}': {msg}" for key, msg in warnings) |
| 117 |
if failed: |
| 118 |
# Get the first failing one |
| 119 |
key, err = failed[0] |
| 120 |
raise ValidationError(f"Sub-option '{key}': {err}") |
| 121 |
|
| 122 |
return config |
| 123 |
|
| 124 |
|
| 125 |
class PropagatingSubConfig(SubConfig[SomeConfig], Generic[SomeConfig]): |
| 126 |
""" |
| 127 |
A SubConfig that must consist of SubConfigs with defined schemas. |
| 128 |
|
| 129 |
Any value set on the top config gets moved to sub-configs with matching keys. |
| 130 |
""" |
| 131 |
|
| 132 |
def run_validation(self, value: object): |
| 133 |
if isinstance(value, dict): |
| 134 |
to_discard = set() |
| 135 |
for k1, v1 in self.config_class._schema: |
| 136 |
if isinstance(v1, SubConfig): |
| 137 |
for k2, _ in v1.config_class._schema: |
| 138 |
if k2 in value: |
| 139 |
subdict = value.setdefault(k1, {}) |
| 140 |
if isinstance(subdict, dict): |
| 141 |
to_discard.add(k2) |
| 142 |
subdict.setdefault(k2, value[k2]) |
| 143 |
for k in to_discard: |
| 144 |
del value[k] |
| 145 |
return super().run_validation(value) |
| 146 |
|
| 147 |
|
| 148 |
class OptionallyRequired(Generic[T], BaseConfigOption[T]): |
| 149 |
""" |
| 150 |
Soft-deprecated, do not use. |
| 151 |
|
| 152 |
A subclass of BaseConfigOption that adds support for default values and |
| 153 |
required values. It is a base class for config options. |
| 154 |
""" |
| 155 |
|
| 156 |
@overload |
| 157 |
def __init__(self, default=None): |
| 158 |
... |
| 159 |
|
| 160 |
@overload |
| 161 |
def __init__(self, default=None, *, required: bool): |
| 162 |
... |
| 163 |
|
| 164 |
def __init__(self, default=None, required=None): |
| 165 |
super().__init__() |
| 166 |
self.default = default |
| 167 |
self._legacy_required = required |
| 168 |
self.required = bool(required) |
| 169 |
|
| 170 |
def validate(self, value): |
| 171 |
""" |
| 172 |
Perform some initial validation. |
| 173 |
|
| 174 |
If the option is empty (None) and isn't required, leave it as such. If |
| 175 |
it is empty but has a default, use that. Finally, call the |
| 176 |
run_validation method on the subclass unless. |
| 177 |
""" |
| 178 |
if value is None: |
| 179 |
if self.default is not None: |
| 180 |
value = self.default |
| 181 |
elif not self.required: |
| 182 |
return None |
| 183 |
elif self.required: |
| 184 |
raise ValidationError("Required configuration not provided.") |
| 185 |
|
| 186 |
return self.run_validation(value) |
| 187 |
|
| 188 |
|
| 189 |
class ListOfItems(Generic[T], BaseConfigOption[List[T]]): |
| 190 |
""" |
| 191 |
Validates a homogeneous list of items. |
| 192 |
|
| 193 |
E.g. for `config_options.ListOfItems(config_options.Type(int))` a valid item is `[1, 2, 3]`. |
| 194 |
""" |
| 195 |
|
| 196 |
required: bool | None = None # Only for subclasses to set. |
| 197 |
|
| 198 |
def __init__(self, option_type: BaseConfigOption[T], default=None) -> None: |
| 199 |
super().__init__() |
| 200 |
self.default = default |
| 201 |
self.option_type = option_type |
| 202 |
self.option_type.warnings = self.warnings |
| 203 |
|
| 204 |
def __repr__(self) -> str: |
| 205 |
return f'{type(self).__name__}: {self.option_type}' |
| 206 |
|
| 207 |
def pre_validation(self, config: Config, key_name: str): |
| 208 |
self._config = config |
| 209 |
self._key_name = key_name |
| 210 |
|
| 211 |
def run_validation(self, value: object) -> list[T]: |
| 212 |
if value is None: |
| 213 |
if self.required or self.default is None: |
| 214 |
raise ValidationError("Required configuration not provided.") |
| 215 |
value = self.default |
| 216 |
if not isinstance(value, list): |
| 217 |
raise ValidationError(f'Expected a list of items, but a {type(value)} was given.') |
| 218 |
if not value: # Optimization for empty list |
| 219 |
return value |
| 220 |
|
| 221 |
fake_config = LegacyConfig(()) |
| 222 |
try: |
| 223 |
fake_config.config_file_path = self._config.config_file_path |
| 224 |
except AttributeError: |
| 225 |
pass |
| 226 |
|
| 227 |
# Emulate a config-like environment for pre_validation and post_validation. |
| 228 |
parent_key_name = getattr(self, '_key_name', '') |
| 229 |
fake_keys = [f'{parent_key_name}[{i}]' for i in range(len(value))] |
| 230 |
fake_config.data = dict(zip(fake_keys, value)) |
| 231 |
|
| 232 |
self.option_type.warnings = self.warnings |
| 233 |
for key_name in fake_config: |
| 234 |
self.option_type.pre_validation(fake_config, key_name) |
| 235 |
for key_name in fake_config: |
| 236 |
# Specifically not running `validate` to avoid the OptionallyRequired effect. |
| 237 |
fake_config[key_name] = self.option_type.run_validation(fake_config[key_name]) |
| 238 |
for key_name in fake_config: |
| 239 |
self.option_type.post_validation(fake_config, key_name) |
| 240 |
|
| 241 |
return [fake_config[k] for k in fake_keys] |
| 242 |
|
| 243 |
|
| 244 |
class DictOfItems(Generic[T], BaseConfigOption[Dict[str, T]]): |
| 245 |
""" |
| 246 |
Validates a dict of items. Keys are always strings. |
| 247 |
|
| 248 |
E.g. for `config_options.DictOfItems(config_options.Type(int))` a valid item is `{"a": 1, "b": 2}`. |
| 249 |
""" |
| 250 |
|
| 251 |
required: bool | None = None # Only for subclasses to set. |
| 252 |
|
| 253 |
def __init__(self, option_type: BaseConfigOption[T], default=None) -> None: |
| 254 |
super().__init__() |
| 255 |
self.default = default |
| 256 |
self.option_type = option_type |
| 257 |
self.option_type.warnings = self.warnings |
| 258 |
|
| 259 |
def __repr__(self) -> str: |
| 260 |
return f"{type(self).__name__}: {self.option_type}" |
| 261 |
|
| 262 |
def pre_validation(self, config: Config, key_name: str): |
| 263 |
self._config = config |
| 264 |
self._key_name = key_name |
| 265 |
|
| 266 |
def run_validation(self, value: object) -> dict[str, T]: |
| 267 |
if value is None: |
| 268 |
if self.required or self.default is None: |
| 269 |
raise ValidationError("Required configuration not provided.") |
| 270 |
value = self.default |
| 271 |
if not isinstance(value, dict): |
| 272 |
raise ValidationError(f"Expected a dict of items, but a {type(value)} was given.") |
| 273 |
if not value: # Optimization for empty list |
| 274 |
return value |
| 275 |
|
| 276 |
fake_config = LegacyConfig(()) |
| 277 |
try: |
| 278 |
fake_config.config_file_path = self._config.config_file_path |
| 279 |
except AttributeError: |
| 280 |
pass |
| 281 |
|
| 282 |
# Emulate a config-like environment for pre_validation and post_validation. |
| 283 |
fake_config.data = value |
| 284 |
|
| 285 |
for key in fake_config: |
| 286 |
self.option_type.pre_validation(fake_config, key) |
| 287 |
for key in fake_config: |
| 288 |
if not isinstance(key, str): |
| 289 |
raise ValidationError( |
| 290 |
f"Expected type: {str} for keys, but received: {type(key)} (key={key})" |
| 291 |
) |
| 292 |
for key in fake_config: |
| 293 |
# Specifically not running `validate` to avoid the OptionallyRequired effect. |
| 294 |
fake_config[key] = self.option_type.run_validation(fake_config[key]) |
| 295 |
for key in fake_config: |
| 296 |
self.option_type.post_validation(fake_config, key) |
| 297 |
|
| 298 |
return value |
| 299 |
|
| 300 |
|
| 301 |
class ConfigItems(ListOfItems[LegacyConfig]): |
| 302 |
""" |
| 303 |
Deprecated: Use `ListOfItems(SubConfig(...))` instead of `ConfigItems(...)`. |
| 304 |
|
| 305 |
Validates a list of mappings that all must match the same set of |
| 306 |
options. |
| 307 |
""" |
| 308 |
|
| 309 |
@overload |
| 310 |
def __init__(self, *config_options: PlainConfigSchemaItem): |
| 311 |
... |
| 312 |
|
| 313 |
@overload |
| 314 |
def __init__(self, *config_options: PlainConfigSchemaItem, required: bool): |
| 315 |
... |
| 316 |
|
| 317 |
def __init__(self, *config_options: PlainConfigSchemaItem, required=None) -> None: |
| 318 |
super().__init__(SubConfig(*config_options), default=[]) |
| 319 |
self._legacy_required = required |
| 320 |
self.required = bool(required) |
| 321 |
|
| 322 |
|
| 323 |
class Type(Generic[T], OptionallyRequired[T]): |
| 324 |
""" |
| 325 |
Type Config Option. |
| 326 |
|
| 327 |
Validate the type of a config option against a given Python type. |
| 328 |
""" |
| 329 |
|
| 330 |
@overload |
| 331 |
def __init__(self, type_: type[T], /, length: int | None = None, **kwargs): |
| 332 |
... |
| 333 |
|
| 334 |
@overload |
| 335 |
def __init__(self, type_: tuple[type[T], ...], /, length: int | None = None, **kwargs): |
| 336 |
... |
| 337 |
|
| 338 |
def __init__(self, type_, /, length=None, **kwargs) -> None: |
| 339 |
super().__init__(**kwargs) |
| 340 |
self._type = type_ |
| 341 |
self.length = length |
| 342 |
|
| 343 |
def run_validation(self, value: object) -> T: |
| 344 |
if not isinstance(value, self._type): |
| 345 |
msg = f"Expected type: {self._type} but received: {type(value)}" |
| 346 |
elif self.length is not None and len(value) != self.length: |
| 347 |
msg = ( |
| 348 |
f"Expected type: {self._type} with length {self.length}" |
| 349 |
f" but received: {value!r} with length {len(value)}" |
| 350 |
) |
| 351 |
else: |
| 352 |
return value |
| 353 |
|
| 354 |
raise ValidationError(msg) |
| 355 |
|
| 356 |
|
| 357 |
class Choice(Generic[T], OptionallyRequired[T]): |
| 358 |
""" |
| 359 |
Choice Config Option. |
| 360 |
|
| 361 |
Validate the config option against a strict set of values. |
| 362 |
""" |
| 363 |
|
| 364 |
def __init__(self, choices: Collection[T], default: T | None = None, **kwargs) -> None: |
| 365 |
super().__init__(default=default, **kwargs) |
| 366 |
try: |
| 367 |
length = len(choices) |
| 368 |
except TypeError: |
| 369 |
length = 0 |
| 370 |
|
| 371 |
if not length or isinstance(choices, str): |
| 372 |
raise ValueError(f'Expected iterable of choices, got {choices}') |
| 373 |
if default is not None and default not in choices: |
| 374 |
raise ValueError(f'{default!r} is not one of {choices!r}') |
| 375 |
|
| 376 |
self.choices = choices |
| 377 |
|
| 378 |
def run_validation(self, value: object) -> T: |
| 379 |
if value not in self.choices: |
| 380 |
raise ValidationError(f"Expected one of: {self.choices} but received: {value!r}") |
| 381 |
return value # type: ignore |
| 382 |
|
| 383 |
|
| 384 |
class Deprecated(BaseConfigOption): |
| 385 |
""" |
| 386 |
Deprecated Config Option. |
| 387 |
|
| 388 |
Raises a warning as the option is deprecated. Uses `message` for the |
| 389 |
warning. If `move_to` is set to the name of a new config option, the value |
| 390 |
is moved to the new option on pre_validation. If `option_type` is set to a |
| 391 |
ConfigOption instance, then the value is validated against that type. |
| 392 |
""" |
| 393 |
|
| 394 |
def __init__( |
| 395 |
self, |
| 396 |
moved_to: str | None = None, |
| 397 |
message: str | None = None, |
| 398 |
removed: bool = False, |
| 399 |
option_type: BaseConfigOption | None = None, |
| 400 |
) -> None: |
| 401 |
super().__init__() |
| 402 |
self.default = None |
| 403 |
self.moved_to = moved_to |
| 404 |
if not message: |
| 405 |
if removed: |
| 406 |
message = "The configuration option '{}' was removed from MkDocs." |
| 407 |
else: |
| 408 |
message = ( |
| 409 |
"The configuration option '{}' has been deprecated and " |
| 410 |
"will be removed in a future release." |
| 411 |
) |
| 412 |
if moved_to: |
| 413 |
message += f" Use '{moved_to}' instead." |
| 414 |
|
| 415 |
self.message = message |
| 416 |
self.removed = removed |
| 417 |
self.option = option_type or BaseConfigOption() |
| 418 |
|
| 419 |
self.warnings = self.option.warnings |
| 420 |
|
| 421 |
def pre_validation(self, config: Config, key_name: str): |
| 422 |
self.option.pre_validation(config, key_name) |
| 423 |
|
| 424 |
if config.get(key_name) is not None: |
| 425 |
if self.removed: |
| 426 |
raise ValidationError(self.message.format(key_name)) |
| 427 |
self.warnings.append(self.message.format(key_name)) |
| 428 |
|
| 429 |
if self.moved_to is not None: |
| 430 |
*parent_keys, target_key = self.moved_to.split('.') |
| 431 |
target: Any = config |
| 432 |
|
| 433 |
for key in parent_keys: |
| 434 |
if target.get(key) is None: |
| 435 |
target[key] = {} |
| 436 |
target = target[key] |
| 437 |
|
| 438 |
if not isinstance(target, dict): |
| 439 |
# We can't move it for the user |
| 440 |
return |
| 441 |
|
| 442 |
target[target_key] = config.pop(key_name) |
| 443 |
|
| 444 |
def validate(self, value): |
| 445 |
return self.option.validate(value) |
| 446 |
|
| 447 |
def post_validation(self, config: Config, key_name: str): |
| 448 |
self.option.post_validation(config, key_name) |
| 449 |
|
| 450 |
def reset_warnings(self): |
| 451 |
self.option.reset_warnings() |
| 452 |
self.warnings = self.option.warnings |
| 453 |
|
| 454 |
|
| 455 |
class _IpAddressValue(NamedTuple): |
| 456 |
host: str |
| 457 |
port: int |
| 458 |
|
| 459 |
def __str__(self) -> str: |
| 460 |
return f'{self.host}:{self.port}' |
| 461 |
|
| 462 |
|
| 463 |
class IpAddress(OptionallyRequired[_IpAddressValue]): |
| 464 |
""" |
| 465 |
IpAddress Config Option. |
| 466 |
|
| 467 |
Validate that an IP address is in an appropriate format |
| 468 |
""" |
| 469 |
|
| 470 |
def run_validation(self, value: object) -> _IpAddressValue: |
| 471 |
if not isinstance(value, str) or ':' not in value: |
| 472 |
raise ValidationError("Must be a string of format 'IP:PORT'") |
| 473 |
host, port_str = value.rsplit(':', 1) |
| 474 |
|
| 475 |
if host != 'localhost': |
| 476 |
if host.startswith('[') and host.endswith(']'): |
| 477 |
host = host[1:-1] |
| 478 |
try: |
| 479 |
# Validate and normalize IP Address |
| 480 |
host = str(ipaddress.ip_address(host)) |
| 481 |
except ValueError as e: |
| 482 |
raise ValidationError(e) |
| 483 |
|
| 484 |
try: |
| 485 |
port = int(port_str) |
| 486 |
except Exception: |
| 487 |
raise ValidationError(f"'{port_str}' is not a valid port") |
| 488 |
|
| 489 |
return _IpAddressValue(host, port) |
| 490 |
|
| 491 |
|
| 492 |
class URL(OptionallyRequired[str]): |
| 493 |
""" |
| 494 |
URL Config Option. |
| 495 |
|
| 496 |
Validate a URL by requiring a scheme is present. |
| 497 |
""" |
| 498 |
|
| 499 |
@overload |
| 500 |
def __init__(self, default=None, *, is_dir: bool = False): |
| 501 |
... |
| 502 |
|
| 503 |
@overload |
| 504 |
def __init__(self, default=None, *, required: bool, is_dir: bool = False): |
| 505 |
... |
| 506 |
|
| 507 |
def __init__(self, default=None, required=None, is_dir: bool = False) -> None: |
| 508 |
self.is_dir = is_dir |
| 509 |
super().__init__(default, required=required) |
| 510 |
|
| 511 |
def run_validation(self, value: object) -> str: |
| 512 |
if not isinstance(value, str): |
| 513 |
raise ValidationError(f"Expected a string, got {type(value)}") |
| 514 |
if value == '': |
| 515 |
return value |
| 516 |
try: |
| 517 |
parsed_url = urlsplit(value) |
| 518 |
except (AttributeError, TypeError): |
| 519 |
raise ValidationError("Unable to parse the URL.") |
| 520 |
|
| 521 |
if parsed_url.scheme and parsed_url.netloc: |
| 522 |
if self.is_dir and not parsed_url.path.endswith('/'): |
| 523 |
parsed_url = parsed_url._replace(path=f'{parsed_url.path}/') |
| 524 |
return urlunsplit(parsed_url) |
| 525 |
|
| 526 |
raise ValidationError("The URL isn't valid, it should include the http:// (scheme)") |
| 527 |
|
| 528 |
|
| 529 |
class Optional(Generic[T], BaseConfigOption[Union[T, None]]): |
| 530 |
""" |
| 531 |
Wraps a field and makes a None value possible for it when no value is set. |
| 532 |
|
| 533 |
E.g. `my_field = config_options.Optional(config_options.Type(str))` |
| 534 |
""" |
| 535 |
|
| 536 |
def __init__(self, config_option: BaseConfigOption[T]) -> None: |
| 537 |
if config_option.default is not None: |
| 538 |
raise ValueError( |
| 539 |
f"This option already has a default ({config_option.default!r}) " |
| 540 |
f"and doesn't need to be wrapped into Optional" |
| 541 |
) |
| 542 |
super().__init__() |
| 543 |
self.option = config_option |
| 544 |
self.warnings = config_option.warnings |
| 545 |
|
| 546 |
def __getattr__(self, key): |
| 547 |
if key in ('option', 'warnings'): |
| 548 |
raise AttributeError |
| 549 |
return getattr(self.option, key) |
| 550 |
|
| 551 |
def pre_validation(self, config: Config, key_name: str): |
| 552 |
return self.option.pre_validation(config, key_name) |
| 553 |
|
| 554 |
def run_validation(self, value: object) -> T | None: |
| 555 |
if value is None: |
| 556 |
return None |
| 557 |
return self.option.validate(value) |
| 558 |
|
| 559 |
def post_validation(self, config: Config, key_name: str): |
| 560 |
result = self.option.post_validation(config, key_name) # type: ignore |
| 561 |
self.warnings = self.option.warnings |
| 562 |
return result |
| 563 |
|
| 564 |
def reset_warnings(self): |
| 565 |
self.option.reset_warnings() |
| 566 |
self.warnings = self.option.warnings |
| 567 |
|
| 568 |
|
| 569 |
class RepoURL(URL): |
| 570 |
def __init__(self, *args, **kwargs): |
| 571 |
warnings.warn( |
| 572 |
"RepoURL is no longer used in MkDocs and will be removed.", DeprecationWarning |
| 573 |
) |
| 574 |
super().__init__(*args, **kwargs) |
| 575 |
|
| 576 |
def post_validation(self, config: Config, key_name: str): |
| 577 |
repo_host = urlsplit(config['repo_url']).netloc.lower() |
| 578 |
edit_uri = config.get('edit_uri') |
| 579 |
|
| 580 |
# derive repo_name from repo_url if unset |
| 581 |
if config['repo_url'] is not None and config.get('repo_name') is None: |
| 582 |
if repo_host == 'github.com': |
| 583 |
config['repo_name'] = 'GitHub' |
| 584 |
elif repo_host == 'bitbucket.org': |
| 585 |
config['repo_name'] = 'Bitbucket' |
| 586 |
elif repo_host == 'gitlab.com': |
| 587 |
config['repo_name'] = 'GitLab' |
| 588 |
else: |
| 589 |
config['repo_name'] = repo_host.split('.')[0].title() |
| 590 |
|
| 591 |
# derive edit_uri from repo_name if unset |
| 592 |
if config['repo_url'] is not None and edit_uri is None: |
| 593 |
if repo_host == 'github.com' or repo_host == 'gitlab.com': |
| 594 |
edit_uri = 'edit/master/docs/' |
| 595 |
elif repo_host == 'bitbucket.org': |
| 596 |
edit_uri = 'src/default/docs/' |
| 597 |
else: |
| 598 |
edit_uri = '' |
| 599 |
|
| 600 |
# ensure a well-formed edit_uri |
| 601 |
if edit_uri and not edit_uri.endswith('/'): |
| 602 |
edit_uri += '/' |
| 603 |
|
| 604 |
config['edit_uri'] = edit_uri |
| 605 |
|
| 606 |
|
| 607 |
class EditURI(Type[str]): |
| 608 |
def __init__(self, repo_url_key: str) -> None: |
| 609 |
super().__init__(str) |
| 610 |
self.repo_url_key = repo_url_key |
| 611 |
|
| 612 |
def post_validation(self, config: Config, key_name: str): |
| 613 |
edit_uri = config.get(key_name) |
| 614 |
repo_url = config.get(self.repo_url_key) |
| 615 |
|
| 616 |
if edit_uri is None and repo_url is not None: |
| 617 |
repo_host = urlsplit(repo_url).netloc.lower() |
| 618 |
if repo_host == 'github.com' or repo_host == 'gitlab.com': |
| 619 |
edit_uri = 'edit/master/docs/' |
| 620 |
elif repo_host == 'bitbucket.org': |
| 621 |
edit_uri = 'src/default/docs/' |
| 622 |
|
| 623 |
# ensure a well-formed edit_uri |
| 624 |
if edit_uri and not edit_uri.endswith('/'): |
| 625 |
edit_uri += '/' |
| 626 |
|
| 627 |
config[key_name] = edit_uri |
| 628 |
|
| 629 |
|
| 630 |
class EditURITemplate(BaseConfigOption[str]): |
| 631 |
class Formatter(string.Formatter): |
| 632 |
def convert_field(self, value, conversion): |
| 633 |
if conversion == 'q': |
| 634 |
return urlquote(value, safe='') |
| 635 |
return super().convert_field(value, conversion) |
| 636 |
|
| 637 |
class Template(UserString): |
| 638 |
def __init__(self, formatter, data) -> None: |
| 639 |
super().__init__(data) |
| 640 |
self.formatter = formatter |
| 641 |
try: |
| 642 |
self.format('', '') |
| 643 |
except KeyError as e: |
| 644 |
raise ValueError(f"Unknown template substitute: {e}") |
| 645 |
|
| 646 |
def format(self, path, path_noext): |
| 647 |
return self.formatter.format(self.data, path=path, path_noext=path_noext) |
| 648 |
|
| 649 |
def __init__(self, edit_uri_key: str | None = None) -> None: |
| 650 |
super().__init__() |
| 651 |
self.edit_uri_key = edit_uri_key |
| 652 |
|
| 653 |
def run_validation(self, value: object): |
| 654 |
try: |
| 655 |
return self.Template(self.Formatter(), value) |
| 656 |
except Exception as e: |
| 657 |
raise ValidationError(e) |
| 658 |
|
| 659 |
def post_validation(self, config: Config, key_name: str): |
| 660 |
if self.edit_uri_key and config.get(key_name) and config.get(self.edit_uri_key): |
| 661 |
self.warnings.append( |
| 662 |
f"The option '{self.edit_uri_key}' has no effect when '{key_name}' is set." |
| 663 |
) |
| 664 |
|
| 665 |
|
| 666 |
class RepoName(Type[str]): |
| 667 |
def __init__(self, repo_url_key: str) -> None: |
| 668 |
super().__init__(str) |
| 669 |
self.repo_url_key = repo_url_key |
| 670 |
|
| 671 |
def post_validation(self, config: Config, key_name: str): |
| 672 |
repo_name = config.get(key_name) |
| 673 |
repo_url = config.get(self.repo_url_key) |
| 674 |
|
| 675 |
# derive repo_name from repo_url if unset |
| 676 |
if repo_url is not None and repo_name is None: |
| 677 |
repo_host = urlsplit(config['repo_url']).netloc.lower() |
| 678 |
if repo_host == 'github.com': |
| 679 |
repo_name = 'GitHub' |
| 680 |
elif repo_host == 'bitbucket.org': |
| 681 |
repo_name = 'Bitbucket' |
| 682 |
elif repo_host == 'gitlab.com': |
| 683 |
repo_name = 'GitLab' |
| 684 |
else: |
| 685 |
repo_name = repo_host.split('.')[0].title() |
| 686 |
config[key_name] = repo_name |
| 687 |
|
| 688 |
|
| 689 |
class FilesystemObject(Type[str]): |
| 690 |
"""Base class for options that point to filesystem objects.""" |
| 691 |
|
| 692 |
existence_test: Callable[[str], bool] = staticmethod(os.path.exists) |
| 693 |
name = 'file or directory' |
| 694 |
|
| 695 |
def __init__(self, exists: bool = False, **kwargs) -> None: |
| 696 |
super().__init__(str, **kwargs) |
| 697 |
self.exists = exists |
| 698 |
self.config_dir: str | None = None |
| 699 |
|
| 700 |
def pre_validation(self, config: Config, key_name: str): |
| 701 |
self.config_dir = ( |
| 702 |
os.path.dirname(config.config_file_path) if config.config_file_path else None |
| 703 |
) |
| 704 |
|
| 705 |
def run_validation(self, value: object) -> str: |
| 706 |
value = super().run_validation(value) |
| 707 |
if self.config_dir and not os.path.isabs(value): |
| 708 |
value = os.path.join(self.config_dir, value) |
| 709 |
if self.exists and not self.existence_test(value): |
| 710 |
raise ValidationError(f"The path '{value}' isn't an existing {self.name}.") |
| 711 |
return os.path.abspath(value) |
| 712 |
|
| 713 |
|
| 714 |
class Dir(FilesystemObject): |
| 715 |
""" |
| 716 |
Dir Config Option. |
| 717 |
|
| 718 |
Validate a path to a directory, optionally verifying that it exists. |
| 719 |
""" |
| 720 |
|
| 721 |
existence_test = staticmethod(os.path.isdir) |
| 722 |
name = 'directory' |
| 723 |
|
| 724 |
|
| 725 |
class DocsDir(Dir): |
| 726 |
def post_validation(self, config: Config, key_name: str): |
| 727 |
if not config.config_file_path: |
| 728 |
return |
| 729 |
|
| 730 |
# Validate that the dir is not the parent dir of the config file. |
| 731 |
if os.path.dirname(config.config_file_path) == config[key_name]: |
| 732 |
raise ValidationError( |
| 733 |
f"The '{key_name}' should not be the parent directory of the" |
| 734 |
f" config file. Use a child directory instead so that the" |
| 735 |
f" '{key_name}' is a sibling of the config file." |
| 736 |
) |
| 737 |
|
| 738 |
|
| 739 |
class File(FilesystemObject): |
| 740 |
""" |
| 741 |
File Config Option. |
| 742 |
|
| 743 |
Validate a path to a file, optionally verifying that it exists. |
| 744 |
""" |
| 745 |
|
| 746 |
existence_test = staticmethod(os.path.isfile) |
| 747 |
name = 'file' |
| 748 |
|
| 749 |
|
| 750 |
class ListOfPaths(ListOfItems[str]): |
| 751 |
""" |
| 752 |
List of Paths Config Option. |
| 753 |
|
| 754 |
A list of file system paths. Raises an error if one of the paths does not exist. |
| 755 |
|
| 756 |
For greater flexibility, prefer ListOfItems, e.g. to require files specifically: |
| 757 |
|
| 758 |
config_options.ListOfItems(config_options.File(exists=True)) |
| 759 |
""" |
| 760 |
|
| 761 |
@overload |
| 762 |
def __init__(self, default=[]): |
| 763 |
... |
| 764 |
|
| 765 |
@overload |
| 766 |
def __init__(self, default=[], *, required: bool): |
| 767 |
... |
| 768 |
|
| 769 |
def __init__(self, default=[], required=None) -> None: |
| 770 |
super().__init__(FilesystemObject(exists=True), default) |
| 771 |
self.required = required |
| 772 |
|
| 773 |
|
| 774 |
class SiteDir(Dir): |
| 775 |
""" |
| 776 |
SiteDir Config Option. |
| 777 |
|
| 778 |
Validates the site_dir and docs_dir directories do not contain each other. |
| 779 |
""" |
| 780 |
|
| 781 |
def post_validation(self, config: Config, key_name: str): |
| 782 |
super().post_validation(config, key_name) |
| 783 |
docs_dir = config['docs_dir'] |
| 784 |
site_dir = config['site_dir'] |
| 785 |
|
| 786 |
# Validate that the docs_dir and site_dir don't contain the |
| 787 |
# other as this will lead to copying back and forth on each |
| 788 |
# and eventually make a deep nested mess. |
| 789 |
if (docs_dir + os.sep).startswith(site_dir.rstrip(os.sep) + os.sep): |
| 790 |
raise ValidationError( |
| 791 |
f"The 'docs_dir' should not be within the 'site_dir' as this " |
| 792 |
f"can mean the source files are overwritten by the output or " |
| 793 |
f"it will be deleted if --clean is passed to mkdocs build. " |
| 794 |
f"(site_dir: '{site_dir}', docs_dir: '{docs_dir}')" |
| 795 |
) |
| 796 |
elif (site_dir + os.sep).startswith(docs_dir.rstrip(os.sep) + os.sep): |
| 797 |
raise ValidationError( |
| 798 |
f"The 'site_dir' should not be within the 'docs_dir' as this " |
| 799 |
f"leads to the build directory being copied into itself and " |
| 800 |
f"duplicate nested files in the 'site_dir'. " |
| 801 |
f"(site_dir: '{site_dir}', docs_dir: '{docs_dir}')" |
| 802 |
) |
| 803 |
|
| 804 |
|
| 805 |
class Theme(BaseConfigOption[theme.Theme]): |
| 806 |
""" |
| 807 |
Theme Config Option. |
| 808 |
|
| 809 |
Validate that the theme exists and build Theme instance. |
| 810 |
""" |
| 811 |
|
| 812 |
def __init__(self, default=None) -> None: |
| 813 |
super().__init__() |
| 814 |
self.default = default |
| 815 |
|
| 816 |
def pre_validation(self, config: Config, key_name: str): |
| 817 |
self.config_file_path = config.config_file_path |
| 818 |
|
| 819 |
def run_validation(self, value: object) -> theme.Theme: |
| 820 |
if value is None and self.default is not None: |
| 821 |
theme_config = {'name': self.default} |
| 822 |
elif isinstance(value, str): |
| 823 |
theme_config = {'name': value} |
| 824 |
elif isinstance(value, dict): |
| 825 |
if 'name' not in value: |
| 826 |
raise ValidationError("No theme name set.") |
| 827 |
theme_config = value |
| 828 |
else: |
| 829 |
raise ValidationError( |
| 830 |
f'Invalid type {type(value)}. Expected a string or key/value pairs.' |
| 831 |
) |
| 832 |
|
| 833 |
themes = utils.get_theme_names() |
| 834 |
if theme_config['name'] is not None and theme_config['name'] not in themes: |
| 835 |
raise ValidationError( |
| 836 |
f"Unrecognised theme name: '{theme_config['name']}'. " |
| 837 |
f"The available installed themes are: {', '.join(themes)}" |
| 838 |
) |
| 839 |
|
| 840 |
if not theme_config['name'] and 'custom_dir' not in theme_config: |
| 841 |
raise ValidationError("At least one of 'name' or 'custom_dir' must be defined.") |
| 842 |
|
| 843 |
# Ensure custom_dir is an absolute path |
| 844 |
if 'custom_dir' in theme_config and not os.path.isabs(theme_config['custom_dir']): |
| 845 |
config_dir = os.path.dirname(self.config_file_path) |
| 846 |
theme_config['custom_dir'] = os.path.join(config_dir, theme_config['custom_dir']) |
| 847 |
|
| 848 |
if 'custom_dir' in theme_config and not os.path.isdir(theme_config['custom_dir']): |
| 849 |
raise ValidationError( |
| 850 |
"The path set in custom_dir ('{path}') does not exist.".format( |
| 851 |
path=theme_config['custom_dir'] |
| 852 |
) |
| 853 |
) |
| 854 |
|
| 855 |
if 'locale' in theme_config and not isinstance(theme_config['locale'], str): |
| 856 |
raise ValidationError("'locale' must be a string.") |
| 857 |
|
| 858 |
return theme.Theme(**theme_config) |
| 859 |
|
| 860 |
|
| 861 |
class Nav(OptionallyRequired): |
| 862 |
""" |
| 863 |
Nav Config Option. |
| 864 |
|
| 865 |
Validate the Nav config. |
| 866 |
""" |
| 867 |
|
| 868 |
def run_validation(self, value: object, *, top=True): |
| 869 |
if isinstance(value, list): |
| 870 |
for subitem in value: |
| 871 |
self._validate_nav_item(subitem) |
| 872 |
if top and not value: |
| 873 |
value = None |
| 874 |
elif isinstance(value, dict) and value and not top: |
| 875 |
# TODO: this should be an error. |
| 876 |
self.warnings.append(f"Expected nav to be a list, got {self._repr_item(value)}") |
| 877 |
for subitem in value.values(): |
| 878 |
self.run_validation(subitem, top=False) |
| 879 |
elif isinstance(value, str) and not top: |
| 880 |
pass |
| 881 |
else: |
| 882 |
raise ValidationError(f"Expected nav to be a list, got {self._repr_item(value)}") |
| 883 |
return value |
| 884 |
|
| 885 |
def _validate_nav_item(self, value): |
| 886 |
if isinstance(value, str): |
| 887 |
pass |
| 888 |
elif isinstance(value, dict): |
| 889 |
if len(value) != 1: |
| 890 |
raise ValidationError( |
| 891 |
f"Expected nav item to be a dict of size 1, got {self._repr_item(value)}" |
| 892 |
) |
| 893 |
for subnav in value.values(): |
| 894 |
self.run_validation(subnav, top=False) |
| 895 |
else: |
| 896 |
raise ValidationError( |
| 897 |
f"Expected nav item to be a string or dict, got {self._repr_item(value)}" |
| 898 |
) |
| 899 |
|
| 900 |
@classmethod |
| 901 |
def _repr_item(cls, value) -> str: |
| 902 |
if isinstance(value, dict) and value: |
| 903 |
return f"dict with keys {tuple(value.keys())}" |
| 904 |
elif isinstance(value, (str, type(None))): |
| 905 |
return repr(value) |
| 906 |
else: |
| 907 |
return f"a {type(value).__name__}: {value!r}" |
| 908 |
|
| 909 |
|
| 910 |
class Private(Generic[T], BaseConfigOption[T]): |
| 911 |
"""A config option that can only be populated programmatically. Raises an error if set by the user.""" |
| 912 |
|
| 913 |
def run_validation(self, value: object) -> None: |
| 914 |
if value is not None: |
| 915 |
raise ValidationError('For internal use only.') |
| 916 |
|
| 917 |
|
| 918 |
class ExtraScriptValue(Config): |
| 919 |
"""An extra script to be added to the page. The `extra_javascript` config is a list of these.""" |
| 920 |
|
| 921 |
path = Type(str) |
| 922 |
"""The value of the `src` tag of the script.""" |
| 923 |
type = Type(str, default='') |
| 924 |
"""The value of the `type` tag of the script.""" |
| 925 |
defer = Type(bool, default=False) |
| 926 |
"""Whether to add the `defer` tag to the script.""" |
| 927 |
async_ = Type(bool, default=False) |
| 928 |
"""Whether to add the `async` tag to the script.""" |
| 929 |
|
| 930 |
def __init__(self, path: str = '', config_file_path=None): |
| 931 |
super().__init__(config_file_path=config_file_path) |
| 932 |
self.path = path |
| 933 |
|
| 934 |
def __str__(self): |
| 935 |
return self.path |
| 936 |
|
| 937 |
def __fspath__(self): |
| 938 |
return self.path |
| 939 |
|
| 940 |
|
| 941 |
class ExtraScript(BaseConfigOption[Union[ExtraScriptValue, str]]): |
| 942 |
def __init__(self): |
| 943 |
super().__init__() |
| 944 |
self.option_type = SubConfig[ExtraScriptValue]() |
| 945 |
|
| 946 |
def run_validation(self, value: object) -> ExtraScriptValue | str: |
| 947 |
self.option_type.warnings = self.warnings |
| 948 |
if isinstance(value, str): |
| 949 |
if value.endswith('.mjs'): |
| 950 |
return self.option_type.run_validation({'path': value, 'type': 'module'}) |
| 951 |
return value |
| 952 |
return self.option_type.run_validation(value) |
| 953 |
|
| 954 |
|
| 955 |
class MarkdownExtensions(OptionallyRequired[List[str]]): |
| 956 |
""" |
| 957 |
Markdown Extensions Config Option. |
| 958 |
|
| 959 |
A list or dict of extensions. Each list item may contain either a string or a one item dict. |
| 960 |
A string must be a valid Markdown extension name with no config options defined. The key of |
| 961 |
a dict item must be a valid Markdown extension name and the value must be a dict of config |
| 962 |
options for that extension. Extension configs are set on the private setting passed to |
| 963 |
`configkey`. The `builtins` keyword accepts a list of extensions which cannot be overridden by |
| 964 |
the user. However, builtins can be duplicated to define config options for them if desired. |
| 965 |
""" |
| 966 |
|
| 967 |
def __init__( |
| 968 |
self, |
| 969 |
builtins: list[str] | None = None, |
| 970 |
configkey: str = 'mdx_configs', |
| 971 |
default: list[str] = [], |
| 972 |
**kwargs, |
| 973 |
) -> None: |
| 974 |
super().__init__(default=default, **kwargs) |
| 975 |
self.builtins = builtins or [] |
| 976 |
self.configkey = configkey |
| 977 |
|
| 978 |
def validate_ext_cfg(self, ext: object, cfg: object) -> None: |
| 979 |
if not isinstance(ext, str): |
| 980 |
raise ValidationError(f"'{ext}' is not a valid Markdown Extension name.") |
| 981 |
if not cfg: |
| 982 |
return |
| 983 |
if not isinstance(cfg, dict): |
| 984 |
raise ValidationError(f"Invalid config options for Markdown Extension '{ext}'.") |
| 985 |
self.configdata[ext] = cfg |
| 986 |
|
| 987 |
def pre_validation(self, config, key_name): |
| 988 |
# To appease validation in case it involves the `!relative` tag. |
| 989 |
config._current_page = current_page = SimpleNamespace() # type: ignore[attr-defined] |
| 990 |
current_page.file = SimpleNamespace() |
| 991 |
current_page.file.src_path = '' |
| 992 |
|
| 993 |
def run_validation(self, value: object) -> list[str]: |
| 994 |
self.configdata: dict[str, dict] = {} |
| 995 |
if not isinstance(value, (list, tuple, dict)): |
| 996 |
raise ValidationError('Invalid Markdown Extensions configuration') |
| 997 |
extensions = [] |
| 998 |
if isinstance(value, dict): |
| 999 |
for ext, cfg in value.items(): |
| 1000 |
self.validate_ext_cfg(ext, cfg) |
| 1001 |
extensions.append(ext) |
| 1002 |
else: |
| 1003 |
for item in value: |
| 1004 |
if isinstance(item, dict): |
| 1005 |
if len(item) > 1: |
| 1006 |
raise ValidationError('Invalid Markdown Extensions configuration') |
| 1007 |
ext, cfg = item.popitem() |
| 1008 |
self.validate_ext_cfg(ext, cfg) |
| 1009 |
extensions.append(ext) |
| 1010 |
elif isinstance(item, str): |
| 1011 |
extensions.append(item) |
| 1012 |
else: |
| 1013 |
raise ValidationError('Invalid Markdown Extensions configuration') |
| 1014 |
|
| 1015 |
extensions = utils.reduce_list(self.builtins + extensions) |
| 1016 |
|
| 1017 |
# Confirm that Markdown considers extensions to be valid |
| 1018 |
md = markdown.Markdown() |
| 1019 |
for ext in extensions: |
| 1020 |
try: |
| 1021 |
md.registerExtensions((ext,), self.configdata) |
| 1022 |
except Exception as e: |
| 1023 |
stack: list = [] |
| 1024 |
for frame in reversed(traceback.extract_tb(sys.exc_info()[2])): |
| 1025 |
if not frame.line: # Ignore frames before <frozen importlib._bootstrap> |
| 1026 |
break |
| 1027 |
stack.insert(0, frame) |
| 1028 |
tb = ''.join(traceback.format_list(stack)) |
| 1029 |
|
| 1030 |
raise ValidationError( |
| 1031 |
f"Failed to load extension '{ext}'.\n{tb}{type(e).__name__}: {e}" |
| 1032 |
) |
| 1033 |
|
| 1034 |
return extensions |
| 1035 |
|
| 1036 |
def post_validation(self, config: Config, key_name: str): |
| 1037 |
config._current_page = None # type: ignore[attr-defined] |
| 1038 |
config[self.configkey] = self.configdata |
| 1039 |
|
| 1040 |
|
| 1041 |
class Plugins(OptionallyRequired[plugins.PluginCollection]): |
| 1042 |
""" |
| 1043 |
Plugins config option. |
| 1044 |
|
| 1045 |
A list or dict of plugins. If a plugin defines config options those are used when |
| 1046 |
initializing the plugin class. |
| 1047 |
""" |
| 1048 |
|
| 1049 |
def __init__(self, theme_key: str | None = None, **kwargs) -> None: |
| 1050 |
super().__init__(**kwargs) |
| 1051 |
self.installed_plugins = plugins.get_plugins() |
| 1052 |
self.theme_key = theme_key |
| 1053 |
self._config: Config | None = None |
| 1054 |
self.plugin_cache: dict[str, plugins.BasePlugin] = {} |
| 1055 |
|
| 1056 |
def pre_validation(self, config, key_name): |
| 1057 |
self._config = config |
| 1058 |
|
| 1059 |
def run_validation(self, value: object) -> plugins.PluginCollection: |
| 1060 |
if not isinstance(value, (list, tuple, dict)): |
| 1061 |
raise ValidationError('Invalid Plugins configuration. Expected a list or dict.') |
| 1062 |
self.plugins = plugins.PluginCollection() |
| 1063 |
self._instance_counter: MutableMapping[str, int] = Counter() |
| 1064 |
for name, cfg in self._parse_configs(value): |
| 1065 |
self.load_plugin_with_namespace(name, cfg) |
| 1066 |
return self.plugins |
| 1067 |
|
| 1068 |
@classmethod |
| 1069 |
def _parse_configs(cls, value: list | tuple | dict) -> Iterator[tuple[str, dict]]: |
| 1070 |
if isinstance(value, dict): |
| 1071 |
for name, cfg in value.items(): |
| 1072 |
if not isinstance(name, str): |
| 1073 |
raise ValidationError(f"'{name}' is not a valid plugin name.") |
| 1074 |
yield name, cfg |
| 1075 |
else: |
| 1076 |
for item in value: |
| 1077 |
if isinstance(item, dict): |
| 1078 |
if len(item) != 1: |
| 1079 |
raise ValidationError('Invalid Plugins configuration') |
| 1080 |
name, cfg = item.popitem() |
| 1081 |
else: |
| 1082 |
name = item |
| 1083 |
cfg = {} |
| 1084 |
if not isinstance(name, str): |
| 1085 |
raise ValidationError(f"'{name}' is not a valid plugin name.") |
| 1086 |
yield name, cfg |
| 1087 |
|
| 1088 |
def load_plugin_with_namespace(self, name: str, config) -> tuple[str, plugins.BasePlugin]: |
| 1089 |
if '/' in name: # It's already specified with a namespace. |
| 1090 |
# Special case: allow to explicitly skip namespaced loading: |
| 1091 |
if name.startswith('/'): |
| 1092 |
name = name[1:] |
| 1093 |
else: |
| 1094 |
# Attempt to load with prepended namespace for the current theme. |
| 1095 |
if self.theme_key and self._config: |
| 1096 |
current_theme = self._config[self.theme_key] |
| 1097 |
if not isinstance(current_theme, str): |
| 1098 |
current_theme = current_theme['name'] |
| 1099 |
if current_theme: |
| 1100 |
expanded_name = f'{current_theme}/{name}' |
| 1101 |
if expanded_name in self.installed_plugins: |
| 1102 |
name = expanded_name |
| 1103 |
return (name, self.load_plugin(name, config)) |
| 1104 |
|
| 1105 |
def load_plugin(self, name: str, config) -> plugins.BasePlugin: |
| 1106 |
if name not in self.installed_plugins: |
| 1107 |
raise ValidationError(f'The "{name}" plugin is not installed') |
| 1108 |
|
| 1109 |
config = config or {} # Users may define a null (None) config |
| 1110 |
if not isinstance(config, dict): |
| 1111 |
raise ValidationError(f"Invalid config options for the '{name}' plugin.") |
| 1112 |
|
| 1113 |
self._instance_counter[name] += 1 |
| 1114 |
inst_number = self._instance_counter[name] |
| 1115 |
inst_name = name |
| 1116 |
if inst_number > 1: |
| 1117 |
inst_name += f' #{inst_number}' |
| 1118 |
|
| 1119 |
plugin = self.plugin_cache.get(inst_name) |
| 1120 |
if plugin is None: |
| 1121 |
plugin_cls = self.installed_plugins[name].load() |
| 1122 |
|
| 1123 |
if not issubclass(plugin_cls, plugins.BasePlugin): |
| 1124 |
raise ValidationError( |
| 1125 |
f'{plugin_cls.__module__}.{plugin_cls.__name__} must be a subclass of' |
| 1126 |
f' {plugins.BasePlugin.__module__}.{plugins.BasePlugin.__name__}' |
| 1127 |
) |
| 1128 |
|
| 1129 |
plugin = plugin_cls() |
| 1130 |
|
| 1131 |
if hasattr(plugin, 'on_startup') or hasattr(plugin, 'on_shutdown'): |
| 1132 |
self.plugin_cache[inst_name] = plugin |
| 1133 |
|
| 1134 |
if inst_number > 1 and not getattr(plugin, 'supports_multiple_instances', False): |
| 1135 |
self.warnings.append( |
| 1136 |
f"Plugin '{name}' was specified multiple times - this is likely a mistake, " |
| 1137 |
"because the plugin doesn't declare `supports_multiple_instances`." |
| 1138 |
) |
| 1139 |
|
| 1140 |
# Only if the plugin doesn't have its own "enabled" config, apply a generic one. |
| 1141 |
if 'enabled' in config and not any(pair[0] == 'enabled' for pair in plugin.config_scheme): |
| 1142 |
enabled = config.pop('enabled') |
| 1143 |
if not isinstance(enabled, bool): |
| 1144 |
raise ValidationError( |
| 1145 |
f"Plugin '{name}' option 'enabled': Expected boolean but received: {type(enabled)}" |
| 1146 |
) |
| 1147 |
if not enabled: |
| 1148 |
log.debug(f"Plugin '{inst_name}' is disabled in the config, skipping.") |
| 1149 |
return plugin |
| 1150 |
|
| 1151 |
errors, warns = plugin.load_config( |
| 1152 |
config, self._config.config_file_path if self._config else None |
| 1153 |
) |
| 1154 |
for warning in warns: |
| 1155 |
if isinstance(warning, str): |
| 1156 |
self.warnings.append(f"Plugin '{inst_name}': {warning}") |
| 1157 |
else: |
| 1158 |
key, msg = warning |
| 1159 |
self.warnings.append(f"Plugin '{inst_name}' option '{key}': {msg}") |
| 1160 |
|
| 1161 |
errors_message = '\n'.join(f"Plugin '{name}' option '{key}': {msg}" for key, msg in errors) |
| 1162 |
if errors_message: |
| 1163 |
raise ValidationError(errors_message) |
| 1164 |
self.plugins[inst_name] = plugin |
| 1165 |
return plugin |
| 1166 |
|
| 1167 |
|
| 1168 |
class Hooks(BaseConfigOption[List[types.ModuleType]]): |
| 1169 |
"""A list of Python scripts to be treated as instances of plugins.""" |
| 1170 |
|
| 1171 |
def __init__(self, plugins_key: str) -> None: |
| 1172 |
super().__init__() |
| 1173 |
self.default = [] |
| 1174 |
self.plugins_key = plugins_key |
| 1175 |
|
| 1176 |
def pre_validation(self, config: Config, key_name: str): |
| 1177 |
self._base_option = ListOfItems(File(exists=True)) |
| 1178 |
self._base_option.pre_validation(config, key_name) |
| 1179 |
|
| 1180 |
def run_validation(self, value: object) -> Mapping[str, Any]: |
| 1181 |
paths = self._base_option.validate(value) |
| 1182 |
self.warnings.extend(self._base_option.warnings) |
| 1183 |
assert isinstance(value, list) |
| 1184 |
|
| 1185 |
hooks = {} |
| 1186 |
for name, path in zip(value, paths): |
| 1187 |
hooks[name] = self._load_hook(name, path) |
| 1188 |
return hooks |
| 1189 |
|
| 1190 |
@functools.lru_cache(maxsize=None) |
| 1191 |
def _load_hook(self, name, path): |
| 1192 |
import importlib.util |
| 1193 |
|
| 1194 |
spec = importlib.util.spec_from_file_location(name, path) |
| 1195 |
if spec is None: |
| 1196 |
raise ValidationError(f"Cannot import path '{path}' as a Python module") |
| 1197 |
module = importlib.util.module_from_spec(spec) |
| 1198 |
sys.modules[name] = module |
| 1199 |
if spec.loader is None: |
| 1200 |
raise ValidationError(f"Cannot import path '{path}' as a Python module") |
| 1201 |
|
| 1202 |
old_sys_path = sys.path.copy() |
| 1203 |
sys.path.insert(0, os.path.dirname(path)) |
| 1204 |
try: |
| 1205 |
spec.loader.exec_module(module) |
| 1206 |
finally: |
| 1207 |
sys.path[:] = old_sys_path |
| 1208 |
|
| 1209 |
return module |
| 1210 |
|
| 1211 |
def post_validation(self, config: Config, key_name: str): |
| 1212 |
plugins = config[self.plugins_key] |
| 1213 |
for name, hook in config[key_name].items(): |
| 1214 |
plugins[name] = hook |
| 1215 |
|
| 1216 |
|
| 1217 |
class PathSpec(BaseConfigOption[pathspec.gitignore.GitIgnoreSpec]): |
| 1218 |
"""A path pattern based on gitignore-like syntax.""" |
| 1219 |
|
| 1220 |
def run_validation(self, value: object) -> pathspec.gitignore.GitIgnoreSpec: |
| 1221 |
if not isinstance(value, str): |
| 1222 |
raise ValidationError(f'Expected a multiline string, but a {type(value)} was given.') |
| 1223 |
try: |
| 1224 |
return pathspec.gitignore.GitIgnoreSpec.from_lines(lines=value.splitlines()) |
| 1225 |
except ValueError as e: |
| 1226 |
raise ValidationError(str(e)) |