This commit is contained in:
CreaRobotics committed 2026-03-02 11:34:40 +01:00
1 parent 6ccab0347b
commit 954a2fd6d6
18684 files changed
+601012 -190

No files matched your search

@@ -0,0 +1,410 @@
"""
Standalone file utils.
Nothing in this module should have an knowledge of config or the layout
and structure of the site and pages in the site.
"""
from __future__ import annotations
import functools
import logging
import os
import posixpath
import re
import shutil
import sys
import warnings
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import PurePath
from typing import TYPE_CHECKING, Collection, Iterable, MutableSequence, TypeVar
from urllib.parse import urlsplit
if sys.version_info >= (3, 10):
from importlib.metadata import EntryPoint, entry_points
else:
from importlib_metadata import EntryPoint, entry_points
from mkdocs import exceptions
from mkdocs.utils.yaml import get_yaml_loader, yaml_load # noqa: F401 - legacy re-export
if TYPE_CHECKING:
from mkdocs.structure.pages import Page
T = TypeVar('T')
log = logging.getLogger(__name__)
markdown_extensions = (
'.markdown',
'.mdown',
'.mkdn',
'.mkd',
'.md',
)
def get_build_timestamp(*, pages: Collection[Page] | None = None) -> int:
"""
Returns the number of seconds since the epoch for the latest updated page.
In reality this is just today's date because that's how pages' update time is populated.
"""
if pages:
# Lexicographic comparison is OK for ISO date.
date_string = max(p.update_date for p in pages)
dt = datetime.fromisoformat(date_string).replace(tzinfo=timezone.utc)
else:
dt = get_build_datetime()
return int(dt.timestamp())
def get_build_datetime() -> datetime:
"""
Returns an aware datetime object.
Support SOURCE_DATE_EPOCH environment variable for reproducible builds.
See https://reproducible-builds.org/specs/source-date-epoch/
"""
source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
if source_date_epoch is None:
return datetime.now(timezone.utc)
return datetime.fromtimestamp(int(source_date_epoch), timezone.utc)
def get_build_date() -> str:
"""
Returns the displayable date string.
Support SOURCE_DATE_EPOCH environment variable for reproducible builds.
See https://reproducible-builds.org/specs/source-date-epoch/
"""
return get_build_datetime().strftime('%Y-%m-%d')
if sys.version_info >= (3, 9):
_removesuffix = str.removesuffix
else:
def _removesuffix(s: str, suffix: str) -> str:
if suffix and s.endswith(suffix):
return s[: -len(suffix)]
return s
def reduce_list(data_set: Iterable[T]) -> list[T]:
"""Reduce duplicate items in a list and preserve order."""
return list(dict.fromkeys(data_set))
if sys.version_info >= (3, 10):
from bisect import insort
else:
def insort(a: MutableSequence[T], x: T, *, key=lambda v: v) -> None:
kx = key(x)
i = len(a)
while i > 0 and kx < key(a[i - 1]):
i -= 1
a.insert(i, x)
def copy_file(source_path: str, output_path: str) -> None:
"""
Copy source_path to output_path, making sure any parent directories exist.
The output_path may be a directory.
"""
output_dir = os.path.dirname(output_path)
os.makedirs(output_dir, exist_ok=True)
if os.path.isdir(output_path):
output_path = os.path.join(output_path, os.path.basename(source_path))
shutil.copyfile(source_path, output_path)
def write_file(content: bytes, output_path: str) -> None:
"""Write content to output_path, making sure any parent directories exist."""
output_dir = os.path.dirname(output_path)
os.makedirs(output_dir, exist_ok=True)
with open(output_path, 'wb') as f:
f.write(content)
def clean_directory(directory: str) -> None:
"""Remove the content of a directory recursively but not the directory itself."""
if not os.path.exists(directory):
return
for entry in os.listdir(directory):
# Don't remove hidden files from the directory. We never copy files
# that are hidden, so we shouldn't delete them either.
if entry.startswith('.'):
continue
path = os.path.join(directory, entry)
if os.path.isdir(path):
shutil.rmtree(path, True)
else:
os.unlink(path)
def is_markdown_file(path: str) -> bool:
"""
Return True if the given file path is a Markdown file.
https://superuser.com/questions/249436/file-extension-for-markdown-files
"""
return path.endswith(markdown_extensions)
_ERROR_TEMPLATE_RE = re.compile(r'^\d{3}\.html?$')
def is_error_template(path: str) -> bool:
"""Return True if the given file path is an HTTP error template."""
return bool(_ERROR_TEMPLATE_RE.match(path))
@functools.lru_cache(maxsize=None)
def _norm_parts(path: str) -> list[str]:
if not path.startswith('/'):
path = '/' + path
path = posixpath.normpath(path)[1:]
return path.split('/') if path else []
def get_relative_url(url: str, other: str) -> str:
"""
Return given url relative to other.
Both are operated as slash-separated paths, similarly to the 'path' part of a URL.
The last component of `other` is skipped if it contains a dot (considered a file).
Actual URLs (with schemas etc.) aren't supported. The leading slash is ignored.
Paths are normalized ('..' works as parent directory), but going higher than the
root has no effect ('foo/../../bar' ends up just as 'bar').
"""
# Remove filename from other url if it has one.
dirname, _, basename = other.rpartition('/')
if '.' in basename:
other = dirname
other_parts = _norm_parts(other)
dest_parts = _norm_parts(url)
common = 0
for a, b in zip(other_parts, dest_parts):
if a != b:
break
common += 1
rel_parts = ['..'] * (len(other_parts) - common) + dest_parts[common:]
relurl = '/'.join(rel_parts) or '.'
return relurl + '/' if url.endswith('/') else relurl
def normalize_url(path: str, page: Page | None = None, base: str = '') -> str:
"""Return a URL relative to the given page or using the base."""
path, relative_level = _get_norm_url(path)
if relative_level == -1:
return path
if page is not None:
result = get_relative_url(path, page.url)
if relative_level > 0:
result = '../' * relative_level + result
return result
return posixpath.join(base, path)
@functools.lru_cache(maxsize=None)
def _get_norm_url(path: str) -> tuple[str, int]:
if not path:
path = '.'
elif '\\' in path:
log.warning(
f"Path '{path}' uses OS-specific separator '\\'. "
f"That will be unsupported in a future release. Please change it to '/'."
)
path = path.replace('\\', '/')
# Allow links to be fully qualified URLs
parsed = urlsplit(path)
if parsed.scheme or parsed.netloc or path.startswith(('/', '#')):
return path, -1
# Relative path - preserve information about it
norm = posixpath.normpath(path) + '/'
relative_level = 0
while norm.startswith('../', relative_level * 3):
relative_level += 1
return path, relative_level
def create_media_urls(
path_list: Iterable[str], page: Page | None = None, base: str = ''
) -> list[str]:
"""Soft-deprecated, do not use."""
return [normalize_url(path, page, base) for path in path_list]
def path_to_url(path):
warnings.warn(
"path_to_url is never used in MkDocs and will be removed soon.", DeprecationWarning
)
return path.replace('\\', '/')
def get_theme_dir(name: str) -> str:
"""Return the directory of an installed theme by name."""
theme = get_themes()[name]
return os.path.dirname(os.path.abspath(theme.load().__file__))
@functools.lru_cache(maxsize=None)
def get_themes() -> dict[str, EntryPoint]:
"""Return a dict of all installed themes as {name: EntryPoint}."""
themes: dict[str, EntryPoint] = {}
eps: dict[EntryPoint, None] = dict.fromkeys(entry_points(group='mkdocs.themes'))
builtins = {ep.name for ep in eps if ep.dist is not None and ep.dist.name == 'mkdocs'}
for theme in eps:
assert theme.dist is not None
if theme.name in builtins and theme.dist.name != 'mkdocs':
raise exceptions.ConfigurationError(
f"The theme '{theme.name}' is a builtin theme but the package '{theme.dist.name}' "
"attempts to provide a theme with the same name."
)
elif theme.name in themes:
other_dist = themes[theme.name].dist
assert other_dist is not None
log.warning(
f"A theme named '{theme.name}' is provided by the Python packages '{theme.dist.name}' "
f"and '{other_dist.name}'. The one in '{theme.dist.name}' will be used."
)
themes[theme.name] = theme
return themes
def get_theme_names() -> Collection[str]:
"""Return a list of all installed themes by name."""
return get_themes().keys()
def dirname_to_title(dirname: str) -> str:
"""Return a page tile obtained from a directory name."""
title = dirname
title = title.replace('-', ' ').replace('_', ' ')
# Capitalize if the dirname was all lowercase, otherwise leave it as-is.
if title.lower() == title:
title = title.capitalize()
return title
def get_markdown_title(markdown_src: str) -> str | None:
"""Soft-deprecated, do not use."""
lines = markdown_src.replace('\r\n', '\n').replace('\r', '\n').split('\n')
while lines:
line = lines.pop(0).strip()
if not line.strip():
continue
if not line.startswith('# '):
return None
return line.lstrip('# ')
return None
def find_or_create_node(branch, key):
"""
Given a list, look for dictionary with a key matching key and return it's
value. If it doesn't exist, create it with the value of an empty list and
return that.
"""
for node in branch:
if not isinstance(node, dict):
continue
if key in node:
return node[key]
new_branch = []
node = {key: new_branch}
branch.append(node)
return new_branch
def nest_paths(paths):
"""
Given a list of paths, convert them into a nested structure that will match
the pages config.
"""
nested = []
for path in paths:
parts = PurePath(path).parent.parts
branch = nested
for part in parts:
part = dirname_to_title(part)
branch = find_or_create_node(branch, part)
branch.append(path)
return nested
class DuplicateFilter:
"""Avoid logging duplicate messages."""
def __init__(self) -> None:
self.msgs: set[str] = set()
def __call__(self, record: logging.LogRecord) -> bool:
rv = record.msg not in self.msgs
self.msgs.add(record.msg)
return rv
class CountHandler(logging.NullHandler):
"""Counts all logged messages >= level."""
def __init__(self, **kwargs) -> None:
self.counts: dict[int, int] = defaultdict(int)
super().__init__(**kwargs)
def handle(self, record):
rv = self.filter(record)
if rv:
# Use levelno for keys so they can be sorted later
self.counts[record.levelno] += 1
return rv
def get_counts(self) -> list[tuple[str, int]]:
return [(logging.getLevelName(k), v) for k, v in sorted(self.counts.items(), reverse=True)]
class weak_property:
"""Same as a read-only property, but allows overwriting the field for good."""
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __get__(self, instance, owner=None):
if instance is None:
return self
return self.func(instance)
def __getattr__(name: str):
if name == 'warning_filter':
warnings.warn(
"warning_filter doesn't do anything since MkDocs 1.2 and will be removed soon. "
"All messages on the `mkdocs` logger get counted automatically.",
DeprecationWarning,
)
return logging.Filter()
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,29 @@
from __future__ import annotations
from string import ascii_letters
from typing import NamedTuple
class UnknownLocaleError(Exception):
pass
class Locale(NamedTuple):
language: str
territory: str = ''
def __str__(self):
if self.territory:
return f'{self.language}_{self.territory}'
return self.language
@classmethod
def parse(cls, identifier, sep):
if not isinstance(identifier, str):
raise TypeError(f"Unexpected value for identifier: '{identifier}'")
locale = cls(*identifier.split(sep, 1))
if not all(x in ascii_letters for x in locale.language):
raise ValueError(f"expected only letters, got '{locale.language}'")
if len(locale.language) != 2:
raise UnknownLocaleError(f"unknown locale '{locale.language}'")
return locale
@@ -0,0 +1,36 @@
import datetime
import urllib.request
from typing import Callable
import mkdocs_get_deps.cache
import mkdocs
def download_url(url: str) -> bytes:
req = urllib.request.Request(url, headers={"User-Agent": f"mkdocs/{mkdocs.__version__}"})
with urllib.request.urlopen(req) as resp:
return resp.read()
def download_and_cache_url(
url: str,
cache_duration: datetime.timedelta,
*,
download: Callable[[str], bytes] = download_url,
comment: bytes = b"# ",
) -> bytes:
"""
Downloads a file from the URL, stores it under ~/.cache/, and returns its content.
For tracking the age of the content, a prefix is inserted into the stored file, rather than relying on mtime.
Args:
url: URL to use.
download: Callback that will accept the URL and actually perform the download.
cache_duration: How long to consider the URL content cached.
comment: The appropriate comment prefix for this file format.
"""
return mkdocs_get_deps.cache.download_and_cache_url(
url=url, cache_duration=cache_duration, download=download, comment=comment
)
@@ -0,0 +1 @@
from .templates import url_filter # noqa: F401 - legacy re-export
@@ -0,0 +1,100 @@
"""
Copyright (c) 2015, Waylan Limberg
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
MultiMarkdown Meta-Data
Extracts, parses and transforms MultiMarkdown style data from documents.
"""
from __future__ import annotations
import re
from typing import Any
import yaml
try:
from yaml import CSafeLoader as SafeLoader
except ImportError: # pragma: no cover
from yaml import SafeLoader # type: ignore
#####################################################################
# Data Parser #
#####################################################################
YAML_RE = re.compile(r'^-{3}[ \t]*\n(.*?\n)(?:\.{3}|-{3})[ \t]*\n', re.UNICODE | re.DOTALL)
META_RE = re.compile(r'^[ ]{0,3}(?P<key>[A-Za-z0-9_-]+):\s*(?P<value>.*)')
META_MORE_RE = re.compile(r'^([ ]{4}|\t)(\s*)(?P<value>.*)')
def get_data(doc: str) -> tuple[str, dict[str, Any]]:
"""
Extract meta-data from a text document.
Returns a tuple of document and a data dict.
"""
data = {}
# First try YAML
if m := YAML_RE.match(doc):
try:
data = yaml.load(m.group(1), SafeLoader)
if isinstance(data, dict):
doc = doc[m.end() :].lstrip('\n')
else:
data = {} # type: ignore[unreachable]
except Exception:
pass
return doc, data
# No YAML delimiters. Try MultiMarkdown style
lines = doc.replace('\r\n', '\n').replace('\r', '\n').split('\n')
key = None
while lines:
line = lines.pop(0)
if line.strip() == '':
break # blank line - done
if m1 := META_RE.match(line):
key = m1.group('key').lower().strip()
value = m1.group('value').strip()
if key in data:
data[key] += f' {value}'
else:
data[key] = value
else:
m2 = META_MORE_RE.match(line)
if m2 and key:
# Add another line to existing key
data[key] += ' {}'.format(m2.group('value').strip())
else:
lines.insert(0, line)
break # no meta data - done
return '\n'.join(lines).lstrip('\n'), data
@@ -0,0 +1,104 @@
from __future__ import annotations
import copy
from typing import TYPE_CHECKING, Callable
import markdown
import markdown.treeprocessors
if TYPE_CHECKING:
from xml.etree import ElementTree as etree
# TODO: This will become unnecessary after min-versions have Markdown >=3.4
_unescape: Callable[[str], str]
try:
_unescape = markdown.treeprocessors.UnescapeTreeprocessor().unescape
except AttributeError:
_unescape = lambda s: s
# TODO: Most of this file will become unnecessary after https://github.com/Python-Markdown/markdown/pull/1441
def get_heading_text(el: etree.Element, md: markdown.Markdown) -> str:
el = copy.deepcopy(el)
_remove_anchorlink(el)
_remove_fnrefs(el)
_extract_alt_texts(el)
return _strip_tags(_render_inner_html(el, md))
def _strip_tags(text: str) -> str:
"""Strip HTML tags and return plain text. Note: HTML entities are unaffected."""
# A comment could contain a tag, so strip comments first
while (start := text.find('<!--')) != -1 and (end := text.find('-->', start)) != -1:
text = text[:start] + text[end + 3 :]
while (start := text.find('<')) != -1 and (end := text.find('>', start)) != -1:
text = text[:start] + text[end + 1 :]
# Collapse whitespace
text = ' '.join(text.split())
return text
def _render_inner_html(el: etree.Element, md: markdown.Markdown) -> str:
# The `UnescapeTreeprocessor` runs after `toc` extension so run here.
text = md.serializer(el)
text = _unescape(text)
# Strip parent tag
start = text.index('>') + 1
end = text.rindex('<')
text = text[start:end].strip()
for pp in md.postprocessors:
text = pp.run(text)
return text
def _remove_anchorlink(el: etree.Element) -> None:
"""Drop anchorlink from the element, if present."""
if len(el) > 0 and el[-1].tag == 'a' and el[-1].get('class') == 'headerlink':
del el[-1]
def _remove_fnrefs(root: etree.Element) -> None:
"""Remove footnote references from the element, if any are present."""
for parent in root.findall('.//sup[@id]/..'):
_replace_elements_with_text(parent, _predicate_for_fnrefs)
def _predicate_for_fnrefs(el: etree.Element) -> str | None:
if el.tag == 'sup' and el.get('id', '').startswith('fnref'):
return ''
return None
def _extract_alt_texts(root: etree.Element) -> None:
"""For images that have an `alt` attribute, replace them with this content."""
for parent in root.findall('.//img[@alt]/..'):
_replace_elements_with_text(parent, _predicate_for_alt_texts)
def _predicate_for_alt_texts(el: etree.Element) -> str | None:
if el.tag == 'img' and (alt := el.get('alt')):
return alt
return None
def _replace_elements_with_text(
parent: etree.Element, predicate: Callable[[etree.Element], str | None]
) -> None:
"""For each child element, if matched, replace it with the text returned from the predicate."""
carry_text = ""
for child in reversed(parent): # Reversed for the ability to mutate during iteration.
# Remove matching elements but carry any `tail` text to preceding elements.
new_text = predicate(child)
if new_text is not None:
carry_text = new_text + (child.tail or "") + carry_text
parent.remove(child)
elif carry_text:
child.tail = (child.tail or "") + carry_text
carry_text = ""
if carry_text:
parent.text = (parent.text or "") + carry_text
@@ -0,0 +1,55 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Sequence, TypedDict
if TYPE_CHECKING:
import datetime
from markupsafe import Markup
try:
from jinja2 import pass_context as contextfilter # type: ignore
except ImportError:
from jinja2 import contextfilter # type: ignore
from mkdocs.utils import normalize_url
if TYPE_CHECKING:
from mkdocs.config.config_options import ExtraScriptValue
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import File
from mkdocs.structure.nav import Navigation
from mkdocs.structure.pages import Page
class TemplateContext(TypedDict):
nav: Navigation
pages: Sequence[File]
base_url: str
extra_css: Sequence[str] # Do not use, prefer `config.extra_css`.
extra_javascript: Sequence[str] # Do not use, prefer `config.extra_javascript`.
mkdocs_version: str
build_date_utc: datetime.datetime
config: MkDocsConfig
page: Page | None
@contextfilter
def url_filter(context: TemplateContext, value: str) -> str:
"""A Template filter to normalize URLs."""
return normalize_url(str(value), page=context['page'], base=context['base_url'])
@contextfilter
def script_tag_filter(context: TemplateContext, extra_script: ExtraScriptValue) -> str:
"""Converts an ExtraScript value to an HTML <script> tag line."""
html = '<script src="{0}"'
if not isinstance(extra_script, str):
if extra_script.type:
html += ' type="{1.type}"'
if extra_script.defer:
html += ' defer'
if extra_script.async_:
html += ' async'
html += '></script>'
return Markup(html).format(url_filter(context, str(extra_script)), extra_script)
@@ -0,0 +1,150 @@
from __future__ import annotations
import functools
import logging
import os
import os.path
from typing import IO, TYPE_CHECKING, Any
import mergedeep # type: ignore
import yaml
import yaml.constructor
import yaml_env_tag # type: ignore
from mkdocs import exceptions
if TYPE_CHECKING:
from mkdocs.config.defaults import MkDocsConfig
log = logging.getLogger(__name__)
def _construct_dir_placeholder(
config: MkDocsConfig, loader: yaml.BaseLoader, node: yaml.ScalarNode
) -> _DirPlaceholder:
loader.construct_scalar(node)
value: str = (node and node.value) or ''
prefix, _, suffix = value.partition('/')
if prefix.startswith('$'):
if prefix == '$config_dir':
return ConfigDirPlaceholder(config, suffix)
elif prefix == '$docs_dir':
return DocsDirPlaceholder(config, suffix)
else:
raise exceptions.ConfigurationError(
f"Unknown prefix {prefix!r} in {node.tag} {node.value!r}"
)
else:
return RelativeDirPlaceholder(config, value)
class _DirPlaceholder(os.PathLike):
def __init__(self, config: MkDocsConfig, suffix: str = ''):
self.config = config
self.suffix = suffix
def value(self) -> str:
raise NotImplementedError
def __fspath__(self) -> str:
"""Can be used as a path."""
return os.path.join(self.value(), self.suffix)
def __str__(self) -> str:
"""Can be converted to a string to obtain the current class."""
return self.__fspath__()
class ConfigDirPlaceholder(_DirPlaceholder):
"""
A placeholder object that gets resolved to the directory of the config file when used as a path.
The suffix can be an additional sub-path that is always appended to this path.
This is the implementation of the `!relative $config_dir/suffix` tag, but can also be passed programmatically.
"""
def value(self) -> str:
return os.path.dirname(self.config.config_file_path)
class DocsDirPlaceholder(_DirPlaceholder):
"""
A placeholder object that gets resolved to the docs dir when used as a path.
The suffix can be an additional sub-path that is always appended to this path.
This is the implementation of the `!relative $docs_dir/suffix` tag, but can also be passed programmatically.
"""
def value(self) -> str:
return self.config.docs_dir
class RelativeDirPlaceholder(_DirPlaceholder):
"""
A placeholder object that gets resolved to the directory of the Markdown file currently being rendered.
This is the implementation of the `!relative` tag, but can also be passed programmatically.
"""
def __init__(self, config: MkDocsConfig, suffix: str = ''):
if suffix:
raise exceptions.ConfigurationError(
f"'!relative' tag does not expect any value; received {suffix!r}"
)
super().__init__(config, suffix)
def value(self) -> str:
current_page = self.config._current_page
if current_page is None:
raise exceptions.ConfigurationError(
"The current file is not set for the '!relative' tag. "
"It cannot be used in this context; the intended usage is within `markdown_extensions`."
)
return os.path.dirname(os.path.join(self.config.docs_dir, current_page.file.src_path))
def get_yaml_loader(loader=yaml.Loader, config: MkDocsConfig | None = None):
"""Wrap PyYaml's loader so we can extend it to suit our needs."""
class Loader(loader):
"""
Define a custom loader derived from the global loader to leave the
global loader unaltered.
"""
# Attach Environment Variable constructor.
# See https://github.com/waylan/pyyaml-env-tag
Loader.add_constructor('!ENV', yaml_env_tag.construct_env_tag)
if config is not None:
Loader.add_constructor('!relative', functools.partial(_construct_dir_placeholder, config))
return Loader
def yaml_load(source: IO | str, loader: type[yaml.BaseLoader] | None = None) -> dict[str, Any]:
"""Return dict of source YAML file using loader, recursively deep merging inherited parent."""
loader = loader or get_yaml_loader()
try:
result = yaml.load(source, Loader=loader)
except yaml.YAMLError as e:
raise exceptions.ConfigurationError(
f"MkDocs encountered an error parsing the configuration file: {e}"
)
if result is None:
return {}
if 'INHERIT' in result and not isinstance(source, str):
relpath = result.pop('INHERIT')
abspath = os.path.normpath(os.path.join(os.path.dirname(source.name), relpath))
if not os.path.exists(abspath):
raise exceptions.ConfigurationError(
f"Inherited config file '{relpath}' does not exist at '{abspath}'."
)
log.debug(f"Loading inherited configuration file: {abspath}")
with open(abspath, 'rb') as fd:
parent = yaml_load(fd, loader)
result = mergedeep.merge(parent, result)
return result