Debian Codegraph @

mkdocs/plugins.py

raw
1 """Implements the plugin API for MkDocs."""
2
3 from __future__ import annotations
4
5 import logging
6 import sys
7 from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, MutableMapping, TypeVar, overload
8
9 if sys.version_info >= (3, 10):
10 from importlib.metadata import EntryPoint, entry_points
11 else:
12 from importlib_metadata import EntryPoint, entry_points
13
14 if TYPE_CHECKING:
15 import jinja2.environment
16
17 from mkdocs import utils
18 from mkdocs.config.base import Config, ConfigErrors, ConfigWarnings, LegacyConfig, PlainConfigSchema
19
20 if TYPE_CHECKING:
21 from mkdocs.config.defaults import MkDocsConfig
22 from mkdocs.livereload import LiveReloadServer
23 from mkdocs.structure.files import Files
24 from mkdocs.structure.nav import Navigation
25 from mkdocs.structure.pages import Page
26 from mkdocs.utils.templates import TemplateContext
27
28 if TYPE_CHECKING:
29 from typing_extensions import Concatenate, ParamSpec
30 else:
31 ParamSpec = TypeVar
32
33 P = ParamSpec('P')
34 T = TypeVar('T')
35
36
37 log = logging.getLogger('mkdocs.plugins')
38
39
40 def get_plugins() -> dict[str, EntryPoint]:
41 """Return a dict of all installed Plugins as {name: EntryPoint}."""
42 plugins = entry_points(group='mkdocs.plugins')
43
44 # Allow third-party plugins to override core plugins
45 pluginmap = {}
46 for plugin in plugins:
47 if plugin.name in pluginmap and plugin.value.startswith("mkdocs.contrib."):
48 continue
49
50 pluginmap[plugin.name] = plugin
51
52 return pluginmap
53
54
55 SomeConfig = TypeVar('SomeConfig', bound=Config)
56
57
58 class BasePlugin(Generic[SomeConfig]):
59 """
60 Plugin base class.
61
62 All plugins should subclass this class.
63 """
64
65 config_class: type[SomeConfig] = LegacyConfig # type: ignore[assignment]
66 config_scheme: PlainConfigSchema = ()
67 config: SomeConfig = {} # type: ignore[assignment]
68
69 supports_multiple_instances: bool = False
70 """Set to true in subclasses to declare support for adding the same plugin multiple times."""
71
72 def __class_getitem__(cls, config_class: type[Config]):
73 """Eliminates the need to write `config_class = FooConfig` when subclassing BasePlugin[FooConfig]."""
74 name = f'{cls.__name__}[{config_class.__name__}]'
75 return type(name, (cls,), dict(config_class=config_class))
76
77 def __init_subclass__(cls):
78 if not issubclass(cls.config_class, Config):
79 raise TypeError(
80 f"config_class {cls.config_class} must be a subclass of `mkdocs.config.base.Config`"
81 )
82 if cls.config_class is not LegacyConfig:
83 cls.config_scheme = cls.config_class._schema # For compatibility.
84
85 def load_config(
86 self, options: dict[str, Any], config_file_path: str | None = None
87 ) -> tuple[ConfigErrors, ConfigWarnings]:
88 """Load config from a dict of options. Returns a tuple of (errors, warnings)."""
89 if self.config_class is LegacyConfig:
90 self.config = LegacyConfig(self.config_scheme, config_file_path=config_file_path) # type: ignore
91 else:
92 self.config = self.config_class(config_file_path=config_file_path)
93
94 self.config.load_dict(options)
95
96 return self.config.validate()
97
98 # One-time events
99
100 def on_startup(self, *, command: Literal['build', 'gh-deploy', 'serve'], dirty: bool) -> None:
101 """
102 The `startup` event runs once at the very beginning of an `mkdocs` invocation.
103
104 New in MkDocs 1.4.
105
106 The presence of an `on_startup` method (even if empty) migrates the plugin to the new
107 system where the plugin object is kept across builds within one `mkdocs serve`.
108
109 Note that for initializing variables, the `__init__` method is still preferred.
110 For initializing per-build variables (and whenever in doubt), use the `on_config` event.
111
112 Args:
113 command: the command that MkDocs was invoked with, e.g. "serve" for `mkdocs serve`.
114 dirty: whether `--dirty` flag was passed.
115 """
116
117 def on_shutdown(self) -> None:
118 """
119 The `shutdown` event runs once at the very end of an `mkdocs` invocation, before exiting.
120
121 This event is relevant only for support of `mkdocs serve`, otherwise within a
122 single build it's undistinguishable from `on_post_build`.
123
124 New in MkDocs 1.4.
125
126 The presence of an `on_shutdown` method (even if empty) migrates the plugin to the new
127 system where the plugin object is kept across builds within one `mkdocs serve`.
128
129 Note the `on_post_build` method is still preferred for cleanups, when possible, as it has
130 a much higher chance of actually triggering. `on_shutdown` is "best effort" because it
131 relies on detecting a graceful shutdown of MkDocs.
132 """
133
134 def on_serve(
135 self, server: LiveReloadServer, /, *, config: MkDocsConfig, builder: Callable
136 ) -> LiveReloadServer | None:
137 """
138 The `serve` event is only called when the `serve` command is used during
139 development. It runs only once, after the first build finishes.
140 It is passed the `Server` instance which can be modified before
141 it is activated. For example, additional files or directories could be added
142 to the list of "watched" files for auto-reloading.
143
144 Args:
145 server: `livereload.Server` instance
146 config: global configuration object
147 builder: a callable which gets passed to each call to `server.watch`
148
149 Returns:
150 `livereload.Server` instance
151 """
152 return server
153
154 # Global events
155
156 def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
157 """
158 The `config` event is the first event called on build and is run immediately
159 after the user configuration is loaded and validated. Any alterations to the
160 config should be made here.
161
162 Args:
163 config: global configuration object
164
165 Returns:
166 global configuration object
167 """
168 return config
169
170 def on_pre_build(self, *, config: MkDocsConfig) -> None:
171 """
172 The `pre_build` event does not alter any variables. Use this event to call
173 pre-build scripts.
174
175 Args:
176 config: global configuration object
177 """
178
179 def on_files(self, files: Files, /, *, config: MkDocsConfig) -> Files | None:
180 """
181 The `files` event is called after the files collection is populated from the
182 `docs_dir`. Use this event to add, remove, or alter files in the
183 collection. Note that Page objects have not yet been associated with the
184 file objects in the collection. Use [Page Events](plugins.md#page-events) to manipulate page
185 specific data.
186
187 Args:
188 files: global files collection
189 config: global configuration object
190
191 Returns:
192 global files collection
193 """
194 return files
195
196 def on_nav(
197 self, nav: Navigation, /, *, config: MkDocsConfig, files: Files
198 ) -> Navigation | None:
199 """
200 The `nav` event is called after the site navigation is created and can
201 be used to alter the site navigation.
202
203 Args:
204 nav: global navigation object
205 config: global configuration object
206 files: global files collection
207
208 Returns:
209 global navigation object
210 """
211 return nav
212
213 def on_env(
214 self, env: jinja2.Environment, /, *, config: MkDocsConfig, files: Files
215 ) -> jinja2.Environment | None:
216 """
217 The `env` event is called after the Jinja template environment is created
218 and can be used to alter the
219 [Jinja environment](https://jinja.palletsprojects.com/en/latest/api/#jinja2.Environment).
220
221 Args:
222 env: global Jinja environment
223 config: global configuration object
224 files: global files collection
225
226 Returns:
227 global Jinja Environment
228 """
229 return env
230
231 def on_post_build(self, *, config: MkDocsConfig) -> None:
232 """
233 The `post_build` event does not alter any variables. Use this event to call
234 post-build scripts.
235
236 Args:
237 config: global configuration object
238 """
239
240 def on_build_error(self, *, error: Exception) -> None:
241 """
242 The `build_error` event is called after an exception of any kind
243 is caught by MkDocs during the build process.
244 Use this event to clean things up before MkDocs terminates. Note that any other
245 events which were scheduled to run after the error will have been skipped. See
246 [Handling Errors](plugins.md#handling-errors) for more details.
247
248 Args:
249 error: exception raised
250 """
251
252 # Template events
253
254 def on_pre_template(
255 self, template: jinja2.Template, /, *, template_name: str, config: MkDocsConfig
256 ) -> jinja2.Template | None:
257 """
258 The `pre_template` event is called immediately after the subject template is
259 loaded and can be used to alter the template.
260
261 Args:
262 template: a Jinja2 [Template](https://jinja.palletsprojects.com/en/latest/api/#jinja2.Template) object
263 template_name: string filename of template
264 config: global configuration object
265
266 Returns:
267 a Jinja2 [Template](https://jinja.palletsprojects.com/en/latest/api/#jinja2.Template) object
268 """
269 return template
270
271 def on_template_context(
272 self, context: TemplateContext, /, *, template_name: str, config: MkDocsConfig
273 ) -> TemplateContext | None:
274 """
275 The `template_context` event is called immediately after the context is created
276 for the subject template and can be used to alter the context for that specific
277 template only.
278
279 Args:
280 context: dict of template context variables
281 template_name: string filename of template
282 config: global configuration object
283
284 Returns:
285 dict of template context variables
286 """
287 return context
288
289 def on_post_template(
290 self, output_content: str, /, *, template_name: str, config: MkDocsConfig
291 ) -> str | None:
292 """
293 The `post_template` event is called after the template is rendered, but before
294 it is written to disc and can be used to alter the output of the template.
295 If an empty string is returned, the template is skipped and nothing is is
296 written to disc.
297
298 Args:
299 output_content: output of rendered template as string
300 template_name: string filename of template
301 config: global configuration object
302
303 Returns:
304 output of rendered template as string
305 """
306 return output_content
307
308 # Page events
309
310 def on_pre_page(self, page: Page, /, *, config: MkDocsConfig, files: Files) -> Page | None:
311 """
312 The `pre_page` event is called before any actions are taken on the subject
313 page and can be used to alter the `Page` instance.
314
315 Args:
316 page: `mkdocs.structure.pages.Page` instance
317 config: global configuration object
318 files: global files collection
319
320 Returns:
321 `mkdocs.structure.pages.Page` instance
322 """
323 return page
324
325 def on_page_read_source(self, /, *, page: Page, config: MkDocsConfig) -> str | None:
326 """
327 > DEPRECATED: Instead of this event, prefer one of these alternatives:
328 >
329 > * Since MkDocs 1.6, instead set `content_bytes`/`content_string` of a `File` inside [`on_files`][].
330 > * Usually (although it's not an exact alternative), `on_page_markdown` can serve the same purpose.
331
332 The `on_page_read_source` event can replace the default mechanism to read
333 the contents of a page's source from the filesystem.
334
335 Args:
336 page: `mkdocs.structure.pages.Page` instance
337 config: global configuration object
338
339 Returns:
340 The raw source for a page as unicode string. If `None` is returned, the
341 default loading from a file will be performed.
342 """
343 return None
344
345 def on_page_markdown(
346 self, markdown: str, /, *, page: Page, config: MkDocsConfig, files: Files
347 ) -> str | None:
348 """
349 The `page_markdown` event is called after the page's markdown is loaded
350 from file and can be used to alter the Markdown source text. The meta-
351 data has been stripped off and is available as `page.meta` at this point.
352
353 Args:
354 markdown: Markdown source text of page as string
355 page: `mkdocs.structure.pages.Page` instance
356 config: global configuration object
357 files: global files collection
358
359 Returns:
360 Markdown source text of page as string
361 """
362 return markdown
363
364 def on_page_content(
365 self, html: str, /, *, page: Page, config: MkDocsConfig, files: Files
366 ) -> str | None:
367 """
368 The `page_content` event is called after the Markdown text is rendered to
369 HTML (but before being passed to a template) and can be used to alter the
370 HTML body of the page.
371
372 Args:
373 html: HTML rendered from Markdown source as string
374 page: `mkdocs.structure.pages.Page` instance
375 config: global configuration object
376 files: global files collection
377
378 Returns:
379 HTML rendered from Markdown source as string
380 """
381 return html
382
383 def on_page_context(
384 self, context: TemplateContext, /, *, page: Page, config: MkDocsConfig, nav: Navigation
385 ) -> TemplateContext | None:
386 """
387 The `page_context` event is called after the context for a page is created
388 and can be used to alter the context for that specific page only.
389
390 Args:
391 context: dict of template context variables
392 page: `mkdocs.structure.pages.Page` instance
393 config: global configuration object
394 nav: global navigation object
395
396 Returns:
397 dict of template context variables
398 """
399 return context
400
401 def on_post_page(self, output: str, /, *, page: Page, config: MkDocsConfig) -> str | None:
402 """
403 The `post_page` event is called after the template is rendered, but
404 before it is written to disc and can be used to alter the output of the
405 page. If an empty string is returned, the page is skipped and nothing is
406 written to disc.
407
408 Args:
409 output: output of rendered template as string
410 page: `mkdocs.structure.pages.Page` instance
411 config: global configuration object
412
413 Returns:
414 output of rendered template as string
415 """
416 return output
417
418
419 EVENTS = tuple(k[3:] for k in BasePlugin.__dict__ if k.startswith("on_"))
420
421 # The above definitions were just for docs and type checking, we don't actually want them.
422 for k in EVENTS:
423 delattr(BasePlugin, 'on_' + k)
424
425
426 def event_priority(priority: float) -> Callable[[T], T]:
427 """
428 A decorator to set an event priority for an event handler method.
429
430 Recommended priority values:
431 `100` "first", `50` "early", `0` "default", `-50` "late", `-100` "last".
432 As different plugins discover more precise relations to each other, the values should be further tweaked.
433
434 Usage example:
435
436 ```python
437 @plugins.event_priority(-100) # Wishing to run this after all other plugins' `on_files` events.
438 def on_files(self, files, config, **kwargs):
439 ...
440 ```
441
442 New in MkDocs 1.4.
443 Recommended shim for backwards compatibility:
444
445 ```python
446 try:
447 from mkdocs.plugins import event_priority
448 except ImportError:
449 event_priority = lambda priority: lambda f: f # No-op fallback
450 ```
451 """
452
453 def decorator(event_method):
454 event_method.mkdocs_priority = priority
455 return event_method
456
457 return decorator
458
459
460 class CombinedEvent(Generic[P, T]):
461 """
462 A descriptor that allows defining multiple event handlers and declaring them under one event's name.
463
464 Usage example:
465
466 ```python
467 @plugins.event_priority(100)
468 def _on_page_markdown_1(self, markdown: str, **kwargs):
469 ...
470
471 @plugins.event_priority(-50)
472 def _on_page_markdown_2(self, markdown: str, **kwargs):
473 ...
474
475 on_page_markdown = plugins.CombinedEvent(_on_page_markdown_1, _on_page_markdown_2)
476 ```
477
478 NOTE: The names of the sub-methods **can't** start with `on_`;
479 instead they can start with `_on_` like in the the above example, or anything else.
480 """
481
482 def __init__(self, *methods: Callable[Concatenate[Any, P], T]):
483 self.methods = methods
484
485 # This is only for mypy, so CombinedEvent can be a valid override of the methods in BasePlugin
486 def __call__(self, instance: BasePlugin, *args: P.args, **kwargs: P.kwargs) -> T:
487 raise TypeError(f"{type(self).__name__!r} object is not callable")
488
489 def __get__(self, instance, owner=None):
490 return CombinedEvent(*(f.__get__(instance, owner) for f in self.methods))
491
492
493 class PluginCollection(dict, MutableMapping[str, BasePlugin]):
494 """
495 A collection of plugins.
496
497 In addition to being a dict of Plugin instances, each event method is registered
498 upon being added. All registered methods for a given event can then be run in order
499 by calling `run_event`.
500 """
501
502 _current_plugin: str | None
503
504 def __init__(self, *args, **kwargs) -> None:
505 super().__init__(*args, **kwargs)
506 self.events: dict[str, list[Callable]] = {k: [] for k in EVENTS}
507 self._event_origins: dict[Callable, str] = {}
508
509 def _register_event(
510 self, event_name: str, method: CombinedEvent | Callable, plugin_name: str | None = None
511 ) -> None:
512 """Register a method for an event."""
513 if isinstance(method, CombinedEvent):
514 for sub in method.methods:
515 self._register_event(event_name, sub, plugin_name=plugin_name)
516 else:
517 events = self.events[event_name]
518 if event_name == 'page_read_source' and len(events) == 1:
519 plugin1 = self._event_origins.get(next(iter(events)), '<unknown>')
520 plugin2 = plugin_name or '<unknown>'
521 log.warning(
522 "Multiple 'on_page_read_source' handlers can't work "
523 f"(both plugins '{plugin1}' and '{plugin2}' registered one)."
524 )
525 utils.insort(events, method, key=lambda m: -getattr(m, 'mkdocs_priority', 0))
526 if plugin_name:
527 try:
528 self._event_origins[method] = plugin_name
529 except TypeError: # If the method is somehow not hashable.
530 pass
531
532 def __getitem__(self, key: str) -> BasePlugin:
533 return super().__getitem__(key)
534
535 def __setitem__(self, key: str, value: BasePlugin) -> None:
536 super().__setitem__(key, value)
537 # Register all of the event methods defined for this Plugin.
538 for event_name in (x for x in dir(value) if x.startswith('on_')):
539 method = getattr(value, event_name, None)
540 if callable(method):
541 self._register_event(event_name[3:], method, plugin_name=key)
542
543 @overload
544 def run_event(self, name: str, **kwargs) -> Any:
545 ...
546
547 @overload
548 def run_event(self, name: str, item: T, **kwargs) -> T:
549 ...
550
551 def run_event(self, name: str, item=None, **kwargs):
552 """
553 Run all registered methods of an event.
554
555 `item` is the object to be modified or replaced and returned by the event method.
556 If it isn't given the event method creates a new object to be returned.
557 All other keywords are variables for context, but would not generally
558 be modified by the event method.
559 """
560 pass_item = item is not None
561 for method in self.events[name]:
562 self._current_plugin = self._event_origins.get(method, '<unknown>')
563 if log.getEffectiveLevel() <= logging.DEBUG:
564 log.debug(f"Running `{name}` event from plugin '{self._current_plugin}'")
565 if pass_item:
566 result = method(item, **kwargs)
567 else:
568 result = method(**kwargs)
569 # keep item if method returned `None`
570 if result is not None:
571 item = result
572 self._current_plugin = None
573 return item
574
575 def on_startup(self, *, command: Literal['build', 'gh-deploy', 'serve'], dirty: bool) -> None:
576 return self.run_event('startup', command=command, dirty=dirty)
577
578 def on_shutdown(self) -> None:
579 return self.run_event('shutdown')
580
581 def on_serve(
582 self, server: LiveReloadServer, *, config: MkDocsConfig, builder: Callable
583 ) -> LiveReloadServer:
584 return self.run_event('serve', server, config=config, builder=builder)
585
586 def on_config(self, config: MkDocsConfig) -> MkDocsConfig:
587 return self.run_event('config', config)
588
589 def on_pre_build(self, *, config: MkDocsConfig) -> None:
590 return self.run_event('pre_build', config=config)
591
592 def on_files(self, files: Files, *, config: MkDocsConfig) -> Files:
593 return self.run_event('files', files, config=config)
594
595 def on_nav(self, nav: Navigation, *, config: MkDocsConfig, files: Files) -> Navigation:
596 return self.run_event('nav', nav, config=config, files=files)
597
598 def on_env(self, env: jinja2.Environment, *, config: MkDocsConfig, files: Files):
599 return self.run_event('env', env, config=config, files=files)
600
601 def on_post_build(self, *, config: MkDocsConfig) -> None:
602 return self.run_event('post_build', config=config)
603
604 def on_build_error(self, *, error: Exception) -> None:
605 return self.run_event('build_error', error=error)
606
607 def on_pre_template(
608 self, template: jinja2.Template, *, template_name: str, config: MkDocsConfig
609 ) -> jinja2.Template:
610 return self.run_event('pre_template', template, template_name=template_name, config=config)
611
612 def on_template_context(
613 self, context: TemplateContext, *, template_name: str, config: MkDocsConfig
614 ) -> TemplateContext:
615 return self.run_event(
616 'template_context', context, template_name=template_name, config=config
617 )
618
619 def on_post_template(
620 self, output_content: str, *, template_name: str, config: MkDocsConfig
621 ) -> str:
622 return self.run_event(
623 'post_template', output_content, template_name=template_name, config=config
624 )
625
626 def on_pre_page(self, page: Page, *, config: MkDocsConfig, files: Files) -> Page:
627 return self.run_event('pre_page', page, config=config, files=files)
628
629 def on_page_read_source(self, *, page: Page, config: MkDocsConfig) -> str | None:
630 return self.run_event('page_read_source', page=page, config=config)
631
632 def on_page_markdown(
633 self, markdown: str, *, page: Page, config: MkDocsConfig, files: Files
634 ) -> str:
635 return self.run_event('page_markdown', markdown, page=page, config=config, files=files)
636
637 def on_page_content(self, html: str, *, page: Page, config: MkDocsConfig, files: Files) -> str:
638 return self.run_event('page_content', html, page=page, config=config, files=files)
639
640 def on_page_context(
641 self, context: TemplateContext, *, page: Page, config: MkDocsConfig, nav: Navigation
642 ) -> TemplateContext:
643 return self.run_event('page_context', context, page=page, config=config, nav=nav)
644
645 def on_post_page(self, output: str, *, page: Page, config: MkDocsConfig) -> str:
646 return self.run_event('post_page', output, page=page, config=config)
647
648
649 class PrefixedLogger(logging.LoggerAdapter):
650 """A logger adapter to prefix log messages."""
651
652 def __init__(self, prefix: str, logger: logging.Logger) -> None:
653 """
654 Initialize the logger adapter.
655
656 Arguments:
657 prefix: The string to insert in front of every message.
658 logger: The logger instance.
659 """
660 super().__init__(logger, {})
661 self.prefix = prefix
662
663 def process(self, msg: str, kwargs: MutableMapping[str, Any]) -> tuple[str, Any]:
664 """
665 Process the message.
666
667 Arguments:
668 msg: The message:
669 kwargs: Remaining arguments.
670
671 Returns:
672 The processed message.
673 """
674 return f"{self.prefix}: {msg}", kwargs
675
676
677 def get_plugin_logger(name: str) -> PrefixedLogger:
678 """
679 Return a logger for plugins.
680
681 Arguments:
682 name: The name to use with `logging.getLogger`.
683
684 Returns:
685 A logger configured to work well in MkDocs,
686 prefixing each message with the plugin package name.
687
688 Example:
689 ```python
690 from mkdocs.plugins import get_plugin_logger
691
692 log = get_plugin_logger(__name__)
693 log.info("My plugin message")
694 ```
695 """
696 logger = logging.getLogger(f"mkdocs.plugins.{name}")
697 return PrefixedLogger(name.split(".", 1)[0], logger)