| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import logging |
| 4 |
import os |
| 5 |
import warnings |
| 6 |
from typing import Any, Collection, MutableMapping |
| 7 |
|
| 8 |
import jinja2 |
| 9 |
import yaml |
| 10 |
|
| 11 |
try: |
| 12 |
from yaml import CSafeLoader as SafeLoader |
| 13 |
except ImportError: # pragma: no cover |
| 14 |
from yaml import SafeLoader # type: ignore |
| 15 |
|
| 16 |
from mkdocs import localization, utils |
| 17 |
from mkdocs.config.base import ValidationError |
| 18 |
from mkdocs.utils import templates |
| 19 |
|
| 20 |
log = logging.getLogger(__name__) |
| 21 |
|
| 22 |
|
| 23 |
class Theme(MutableMapping[str, Any]): |
| 24 |
""" |
| 25 |
A Theme object. |
| 26 |
|
| 27 |
Args: |
| 28 |
name: The name of the theme as defined by its entrypoint. |
| 29 |
custom_dir: User defined directory for custom templates. |
| 30 |
static_templates: A list of templates to render as static pages. |
| 31 |
|
| 32 |
All other keywords are passed as-is and made available as a key/value mapping. |
| 33 |
""" |
| 34 |
|
| 35 |
def __init__( |
| 36 |
self, |
| 37 |
name: str | None = None, |
| 38 |
*, |
| 39 |
custom_dir: str | None = None, |
| 40 |
static_templates: Collection[str] = (), |
| 41 |
locale: str | None = None, |
| 42 |
**user_config, |
| 43 |
) -> None: |
| 44 |
self.name = name |
| 45 |
self._custom_dir = custom_dir |
| 46 |
_vars: dict[str, Any] = {'name': name, 'locale': 'en'} |
| 47 |
self.__vars = _vars |
| 48 |
|
| 49 |
# MkDocs provided static templates are always included |
| 50 |
package_dir = os.path.abspath(os.path.dirname(__file__)) |
| 51 |
mkdocs_templates = os.path.join(package_dir, 'templates') |
| 52 |
self.static_templates = set(os.listdir(mkdocs_templates)) |
| 53 |
|
| 54 |
# Build self.dirs from various sources in order of precedence |
| 55 |
self.dirs = [] |
| 56 |
|
| 57 |
if custom_dir is not None: |
| 58 |
self.dirs.append(custom_dir) |
| 59 |
|
| 60 |
if name: |
| 61 |
self._load_theme_config(name) |
| 62 |
|
| 63 |
# Include templates provided directly by MkDocs (outside any theme) |
| 64 |
self.dirs.append(mkdocs_templates) |
| 65 |
|
| 66 |
# Handle remaining user configs. Override theme configs (if set) |
| 67 |
self.static_templates.update(static_templates) |
| 68 |
_vars.update(user_config) |
| 69 |
|
| 70 |
# Validate locale and convert to Locale object |
| 71 |
if locale is None: |
| 72 |
locale = _vars['locale'] |
| 73 |
_vars['locale'] = localization.parse_locale(locale) |
| 74 |
|
| 75 |
name: str | None |
| 76 |
|
| 77 |
@property |
| 78 |
def locale(self) -> localization.Locale: |
| 79 |
return self['locale'] |
| 80 |
|
| 81 |
@property |
| 82 |
def custom_dir(self) -> str | None: |
| 83 |
return self._custom_dir |
| 84 |
|
| 85 |
@property |
| 86 |
def _vars(self) -> dict[str, Any]: |
| 87 |
warnings.warn( |
| 88 |
"Do not access Theme._vars, instead access the keys of Theme directly.", |
| 89 |
DeprecationWarning, |
| 90 |
) |
| 91 |
return self.__vars |
| 92 |
|
| 93 |
dirs: list[str] |
| 94 |
|
| 95 |
static_templates: set[str] |
| 96 |
|
| 97 |
def __repr__(self) -> str: |
| 98 |
return "{}(name={!r}, dirs={!r}, static_templates={!r}, {})".format( |
| 99 |
self.__class__.__name__, |
| 100 |
self.name, |
| 101 |
self.dirs, |
| 102 |
self.static_templates, |
| 103 |
', '.join(f'{k}={v!r}' for k, v in self.items()), |
| 104 |
) |
| 105 |
|
| 106 |
def __getitem__(self, key: str) -> Any: |
| 107 |
return self.__vars[key] |
| 108 |
|
| 109 |
def __setitem__(self, key: str, value): |
| 110 |
self.__vars[key] = value |
| 111 |
|
| 112 |
def __delitem__(self, key: str): |
| 113 |
del self.__vars[key] |
| 114 |
|
| 115 |
def __contains__(self, item: object) -> bool: |
| 116 |
return item in self.__vars |
| 117 |
|
| 118 |
def __len__(self): |
| 119 |
return len(self.__vars) |
| 120 |
|
| 121 |
def __iter__(self): |
| 122 |
return iter(self.__vars) |
| 123 |
|
| 124 |
def _load_theme_config(self, name: str) -> None: |
| 125 |
"""Recursively load theme and any parent themes.""" |
| 126 |
theme_dir = utils.get_theme_dir(name) |
| 127 |
utils.get_themes.cache_clear() |
| 128 |
self.dirs.append(theme_dir) |
| 129 |
|
| 130 |
try: |
| 131 |
file_path = os.path.join(theme_dir, 'mkdocs_theme.yml') |
| 132 |
with open(file_path, 'rb') as f: |
| 133 |
theme_config = yaml.load(f, SafeLoader) |
| 134 |
except OSError as e: |
| 135 |
log.debug(e) |
| 136 |
raise ValidationError( |
| 137 |
f"The theme '{name}' does not appear to have a configuration file. " |
| 138 |
f"Please upgrade to a current version of the theme." |
| 139 |
) |
| 140 |
|
| 141 |
if theme_config is None: |
| 142 |
theme_config = {} |
| 143 |
|
| 144 |
log.debug(f"Loaded theme configuration for '{name}' from '{file_path}': {theme_config}") |
| 145 |
|
| 146 |
if parent_theme := theme_config.pop('extends', None): |
| 147 |
themes = utils.get_theme_names() |
| 148 |
if parent_theme not in themes: |
| 149 |
raise ValidationError( |
| 150 |
f"The theme '{name}' inherits from '{parent_theme}', which does not appear to be installed. " |
| 151 |
f"The available installed themes are: {', '.join(themes)}" |
| 152 |
) |
| 153 |
self._load_theme_config(parent_theme) |
| 154 |
|
| 155 |
self.static_templates.update(theme_config.pop('static_templates', [])) |
| 156 |
self.__vars.update(theme_config) |
| 157 |
|
| 158 |
def get_env(self) -> jinja2.Environment: |
| 159 |
"""Return a Jinja environment for the theme.""" |
| 160 |
loader = jinja2.FileSystemLoader(self.dirs) |
| 161 |
# No autoreload because editing a template in the middle of a build is not useful. |
| 162 |
env = jinja2.Environment(loader=loader, auto_reload=False) |
| 163 |
env.filters['url'] = templates.url_filter |
| 164 |
env.filters['script_tag'] = templates.script_tag_filter |
| 165 |
localization.install_translations(env, self.locale, self.dirs) |
| 166 |
return env |