Debian Codegraph @

mkdocs/utils/yaml.py

raw
1 from __future__ import annotations
2
3 import functools
4 import logging
5 import os
6 import os.path
7 from typing import IO, TYPE_CHECKING, Any
8
9 import mergedeep # type: ignore
10 import yaml
11 import yaml.constructor
12 import yaml_env_tag # type: ignore
13
14 from mkdocs import exceptions
15
16 if TYPE_CHECKING:
17 from mkdocs.config.defaults import MkDocsConfig
18
19 log = logging.getLogger(__name__)
20
21
22 def _construct_dir_placeholder(
23 config: MkDocsConfig, loader: yaml.BaseLoader, node: yaml.ScalarNode
24 ) -> _DirPlaceholder:
25 loader.construct_scalar(node)
26
27 value: str = (node and node.value) or ''
28 prefix, _, suffix = value.partition('/')
29 if prefix.startswith('$'):
30 if prefix == '$config_dir':
31 return ConfigDirPlaceholder(config, suffix)
32 elif prefix == '$docs_dir':
33 return DocsDirPlaceholder(config, suffix)
34 else:
35 raise exceptions.ConfigurationError(
36 f"Unknown prefix {prefix!r} in {node.tag} {node.value!r}"
37 )
38 else:
39 return RelativeDirPlaceholder(config, value)
40
41
42 class _DirPlaceholder(os.PathLike):
43 def __init__(self, config: MkDocsConfig, suffix: str = ''):
44 self.config = config
45 self.suffix = suffix
46
47 def value(self) -> str:
48 raise NotImplementedError
49
50 def __fspath__(self) -> str:
51 """Can be used as a path."""
52 return os.path.join(self.value(), self.suffix)
53
54 def __str__(self) -> str:
55 """Can be converted to a string to obtain the current class."""
56 return self.__fspath__()
57
58
59 class ConfigDirPlaceholder(_DirPlaceholder):
60 """
61 A placeholder object that gets resolved to the directory of the config file when used as a path.
62
63 The suffix can be an additional sub-path that is always appended to this path.
64
65 This is the implementation of the `!relative $config_dir/suffix` tag, but can also be passed programmatically.
66 """
67
68 def value(self) -> str:
69 return os.path.dirname(self.config.config_file_path)
70
71
72 class DocsDirPlaceholder(_DirPlaceholder):
73 """
74 A placeholder object that gets resolved to the docs dir when used as a path.
75
76 The suffix can be an additional sub-path that is always appended to this path.
77
78 This is the implementation of the `!relative $docs_dir/suffix` tag, but can also be passed programmatically.
79 """
80
81 def value(self) -> str:
82 return self.config.docs_dir
83
84
85 class RelativeDirPlaceholder(_DirPlaceholder):
86 """
87 A placeholder object that gets resolved to the directory of the Markdown file currently being rendered.
88
89 This is the implementation of the `!relative` tag, but can also be passed programmatically.
90 """
91
92 def __init__(self, config: MkDocsConfig, suffix: str = ''):
93 if suffix:
94 raise exceptions.ConfigurationError(
95 f"'!relative' tag does not expect any value; received {suffix!r}"
96 )
97 super().__init__(config, suffix)
98
99 def value(self) -> str:
100 current_page = self.config._current_page
101 if current_page is None:
102 raise exceptions.ConfigurationError(
103 "The current file is not set for the '!relative' tag. "
104 "It cannot be used in this context; the intended usage is within `markdown_extensions`."
105 )
106 return os.path.dirname(os.path.join(self.config.docs_dir, current_page.file.src_path))
107
108
109 def get_yaml_loader(loader=yaml.Loader, config: MkDocsConfig | None = None):
110 """Wrap PyYaml's loader so we can extend it to suit our needs."""
111
112 class Loader(loader):
113 """
114 Define a custom loader derived from the global loader to leave the
115 global loader unaltered.
116 """
117
118 # Attach Environment Variable constructor.
119 # See https://github.com/waylan/pyyaml-env-tag
120 Loader.add_constructor('!ENV', yaml_env_tag.construct_env_tag)
121
122 if config is not None:
123 Loader.add_constructor('!relative', functools.partial(_construct_dir_placeholder, config))
124
125 return Loader
126
127
128 def yaml_load(source: IO | str, loader: type[yaml.BaseLoader] | None = None) -> dict[str, Any]:
129 """Return dict of source YAML file using loader, recursively deep merging inherited parent."""
130 loader = loader or get_yaml_loader()
131 try:
132 result = yaml.load(source, Loader=loader)
133 except yaml.YAMLError as e:
134 raise exceptions.ConfigurationError(
135 f"MkDocs encountered an error parsing the configuration file: {e}"
136 )
137 if result is None:
138 return {}
139 if 'INHERIT' in result and not isinstance(source, str):
140 relpath = result.pop('INHERIT')
141 abspath = os.path.normpath(os.path.join(os.path.dirname(source.name), relpath))
142 if not os.path.exists(abspath):
143 raise exceptions.ConfigurationError(
144 f"Inherited config file '{relpath}' does not exist at '{abspath}'."
145 )
146 log.debug(f"Loading inherited configuration file: {abspath}")
147 with open(abspath, 'rb') as fd:
148 parent = yaml_load(fd, loader)
149 result = mergedeep.merge(parent, result)
150 return result