| 1 |
""" |
| 2 |
Standalone file utils. |
| 3 |
|
| 4 |
Nothing in this module should have an knowledge of config or the layout |
| 5 |
and structure of the site and pages in the site. |
| 6 |
""" |
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import functools |
| 10 |
import logging |
| 11 |
import os |
| 12 |
import posixpath |
| 13 |
import re |
| 14 |
import shutil |
| 15 |
import sys |
| 16 |
import warnings |
| 17 |
from collections import defaultdict |
| 18 |
from datetime import datetime, timezone |
| 19 |
from pathlib import PurePath |
| 20 |
from typing import TYPE_CHECKING, Collection, Iterable, MutableSequence, TypeVar |
| 21 |
from urllib.parse import urlsplit |
| 22 |
|
| 23 |
if sys.version_info >= (3, 10): |
| 24 |
from importlib.metadata import EntryPoint, entry_points |
| 25 |
else: |
| 26 |
from importlib_metadata import EntryPoint, entry_points |
| 27 |
|
| 28 |
from mkdocs import exceptions |
| 29 |
from mkdocs.utils.yaml import get_yaml_loader, yaml_load # noqa: F401 - legacy re-export |
| 30 |
|
| 31 |
if TYPE_CHECKING: |
| 32 |
from mkdocs.structure.pages import Page |
| 33 |
|
| 34 |
T = TypeVar('T') |
| 35 |
|
| 36 |
log = logging.getLogger(__name__) |
| 37 |
|
| 38 |
markdown_extensions = ( |
| 39 |
'.markdown', |
| 40 |
'.mdown', |
| 41 |
'.mkdn', |
| 42 |
'.mkd', |
| 43 |
'.md', |
| 44 |
) |
| 45 |
|
| 46 |
|
| 47 |
def get_build_timestamp(*, pages: Collection[Page] | None = None) -> int: |
| 48 |
""" |
| 49 |
Returns the number of seconds since the epoch for the latest updated page. |
| 50 |
|
| 51 |
In reality this is just today's date because that's how pages' update time is populated. |
| 52 |
""" |
| 53 |
if pages: |
| 54 |
# Lexicographic comparison is OK for ISO date. |
| 55 |
date_string = max(p.update_date for p in pages) |
| 56 |
dt = datetime.fromisoformat(date_string).replace(tzinfo=timezone.utc) |
| 57 |
else: |
| 58 |
dt = get_build_datetime() |
| 59 |
return int(dt.timestamp()) |
| 60 |
|
| 61 |
|
| 62 |
def get_build_datetime() -> datetime: |
| 63 |
""" |
| 64 |
Returns an aware datetime object. |
| 65 |
|
| 66 |
Support SOURCE_DATE_EPOCH environment variable for reproducible builds. |
| 67 |
See https://reproducible-builds.org/specs/source-date-epoch/ |
| 68 |
""" |
| 69 |
source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH') |
| 70 |
if source_date_epoch is None: |
| 71 |
return datetime.now(timezone.utc) |
| 72 |
|
| 73 |
return datetime.fromtimestamp(int(source_date_epoch), timezone.utc) |
| 74 |
|
| 75 |
|
| 76 |
def get_build_date() -> str: |
| 77 |
""" |
| 78 |
Returns the displayable date string. |
| 79 |
|
| 80 |
Support SOURCE_DATE_EPOCH environment variable for reproducible builds. |
| 81 |
See https://reproducible-builds.org/specs/source-date-epoch/ |
| 82 |
""" |
| 83 |
return get_build_datetime().strftime('%Y-%m-%d') |
| 84 |
|
| 85 |
|
| 86 |
if sys.version_info >= (3, 9): |
| 87 |
_removesuffix = str.removesuffix |
| 88 |
else: |
| 89 |
|
| 90 |
def _removesuffix(s: str, suffix: str) -> str: |
| 91 |
if suffix and s.endswith(suffix): |
| 92 |
return s[: -len(suffix)] |
| 93 |
return s |
| 94 |
|
| 95 |
|
| 96 |
def reduce_list(data_set: Iterable[T]) -> list[T]: |
| 97 |
"""Reduce duplicate items in a list and preserve order.""" |
| 98 |
return list(dict.fromkeys(data_set)) |
| 99 |
|
| 100 |
|
| 101 |
if sys.version_info >= (3, 10): |
| 102 |
from bisect import insort |
| 103 |
else: |
| 104 |
|
| 105 |
def insort(a: MutableSequence[T], x: T, *, key=lambda v: v) -> None: |
| 106 |
kx = key(x) |
| 107 |
i = len(a) |
| 108 |
while i > 0 and kx < key(a[i - 1]): |
| 109 |
i -= 1 |
| 110 |
a.insert(i, x) |
| 111 |
|
| 112 |
|
| 113 |
def copy_file(source_path: str, output_path: str) -> None: |
| 114 |
""" |
| 115 |
Copy source_path to output_path, making sure any parent directories exist. |
| 116 |
|
| 117 |
The output_path may be a directory. |
| 118 |
""" |
| 119 |
output_dir = os.path.dirname(output_path) |
| 120 |
os.makedirs(output_dir, exist_ok=True) |
| 121 |
if os.path.isdir(output_path): |
| 122 |
output_path = os.path.join(output_path, os.path.basename(source_path)) |
| 123 |
shutil.copyfile(source_path, output_path) |
| 124 |
|
| 125 |
|
| 126 |
def write_file(content: bytes, output_path: str) -> None: |
| 127 |
"""Write content to output_path, making sure any parent directories exist.""" |
| 128 |
output_dir = os.path.dirname(output_path) |
| 129 |
os.makedirs(output_dir, exist_ok=True) |
| 130 |
with open(output_path, 'wb') as f: |
| 131 |
f.write(content) |
| 132 |
|
| 133 |
|
| 134 |
def clean_directory(directory: str) -> None: |
| 135 |
"""Remove the content of a directory recursively but not the directory itself.""" |
| 136 |
if not os.path.exists(directory): |
| 137 |
return |
| 138 |
|
| 139 |
for entry in os.listdir(directory): |
| 140 |
# Don't remove hidden files from the directory. We never copy files |
| 141 |
# that are hidden, so we shouldn't delete them either. |
| 142 |
if entry.startswith('.'): |
| 143 |
continue |
| 144 |
|
| 145 |
path = os.path.join(directory, entry) |
| 146 |
if os.path.isdir(path): |
| 147 |
shutil.rmtree(path, True) |
| 148 |
else: |
| 149 |
os.unlink(path) |
| 150 |
|
| 151 |
|
| 152 |
def is_markdown_file(path: str) -> bool: |
| 153 |
""" |
| 154 |
Return True if the given file path is a Markdown file. |
| 155 |
|
| 156 |
https://superuser.com/questions/249436/file-extension-for-markdown-files |
| 157 |
""" |
| 158 |
return path.endswith(markdown_extensions) |
| 159 |
|
| 160 |
|
| 161 |
_ERROR_TEMPLATE_RE = re.compile(r'^\d{3}\.html?$') |
| 162 |
|
| 163 |
|
| 164 |
def is_error_template(path: str) -> bool: |
| 165 |
"""Return True if the given file path is an HTTP error template.""" |
| 166 |
return bool(_ERROR_TEMPLATE_RE.match(path)) |
| 167 |
|
| 168 |
|
| 169 |
@functools.lru_cache(maxsize=None) |
| 170 |
def _norm_parts(path: str) -> list[str]: |
| 171 |
if not path.startswith('/'): |
| 172 |
path = '/' + path |
| 173 |
path = posixpath.normpath(path)[1:] |
| 174 |
return path.split('/') if path else [] |
| 175 |
|
| 176 |
|
| 177 |
def get_relative_url(url: str, other: str) -> str: |
| 178 |
""" |
| 179 |
Return given url relative to other. |
| 180 |
|
| 181 |
Both are operated as slash-separated paths, similarly to the 'path' part of a URL. |
| 182 |
The last component of `other` is skipped if it contains a dot (considered a file). |
| 183 |
Actual URLs (with schemas etc.) aren't supported. The leading slash is ignored. |
| 184 |
Paths are normalized ('..' works as parent directory), but going higher than the |
| 185 |
root has no effect ('foo/../../bar' ends up just as 'bar'). |
| 186 |
""" |
| 187 |
# Remove filename from other url if it has one. |
| 188 |
dirname, _, basename = other.rpartition('/') |
| 189 |
if '.' in basename: |
| 190 |
other = dirname |
| 191 |
|
| 192 |
other_parts = _norm_parts(other) |
| 193 |
dest_parts = _norm_parts(url) |
| 194 |
common = 0 |
| 195 |
for a, b in zip(other_parts, dest_parts): |
| 196 |
if a != b: |
| 197 |
break |
| 198 |
common += 1 |
| 199 |
|
| 200 |
rel_parts = ['..'] * (len(other_parts) - common) + dest_parts[common:] |
| 201 |
relurl = '/'.join(rel_parts) or '.' |
| 202 |
return relurl + '/' if url.endswith('/') else relurl |
| 203 |
|
| 204 |
|
| 205 |
def normalize_url(path: str, page: Page | None = None, base: str = '') -> str: |
| 206 |
"""Return a URL relative to the given page or using the base.""" |
| 207 |
path, relative_level = _get_norm_url(path) |
| 208 |
if relative_level == -1: |
| 209 |
return path |
| 210 |
if page is not None: |
| 211 |
result = get_relative_url(path, page.url) |
| 212 |
if relative_level > 0: |
| 213 |
result = '../' * relative_level + result |
| 214 |
return result |
| 215 |
|
| 216 |
return posixpath.join(base, path) |
| 217 |
|
| 218 |
|
| 219 |
@functools.lru_cache(maxsize=None) |
| 220 |
def _get_norm_url(path: str) -> tuple[str, int]: |
| 221 |
if not path: |
| 222 |
path = '.' |
| 223 |
elif '\\' in path: |
| 224 |
log.warning( |
| 225 |
f"Path '{path}' uses OS-specific separator '\\'. " |
| 226 |
f"That will be unsupported in a future release. Please change it to '/'." |
| 227 |
) |
| 228 |
path = path.replace('\\', '/') |
| 229 |
# Allow links to be fully qualified URLs |
| 230 |
parsed = urlsplit(path) |
| 231 |
if parsed.scheme or parsed.netloc or path.startswith(('/', '#')): |
| 232 |
return path, -1 |
| 233 |
|
| 234 |
# Relative path - preserve information about it |
| 235 |
norm = posixpath.normpath(path) + '/' |
| 236 |
relative_level = 0 |
| 237 |
while norm.startswith('../', relative_level * 3): |
| 238 |
relative_level += 1 |
| 239 |
return path, relative_level |
| 240 |
|
| 241 |
|
| 242 |
def create_media_urls( |
| 243 |
path_list: Iterable[str], page: Page | None = None, base: str = '' |
| 244 |
) -> list[str]: |
| 245 |
"""Soft-deprecated, do not use.""" |
| 246 |
return [normalize_url(path, page, base) for path in path_list] |
| 247 |
|
| 248 |
|
| 249 |
def path_to_url(path): |
| 250 |
warnings.warn( |
| 251 |
"path_to_url is never used in MkDocs and will be removed soon.", DeprecationWarning |
| 252 |
) |
| 253 |
return path.replace('\\', '/') |
| 254 |
|
| 255 |
|
| 256 |
def get_theme_dir(name: str) -> str: |
| 257 |
"""Return the directory of an installed theme by name.""" |
| 258 |
theme = get_themes()[name] |
| 259 |
return os.path.dirname(os.path.abspath(theme.load().__file__)) |
| 260 |
|
| 261 |
|
| 262 |
@functools.lru_cache(maxsize=None) |
| 263 |
def get_themes() -> dict[str, EntryPoint]: |
| 264 |
"""Return a dict of all installed themes as {name: EntryPoint}.""" |
| 265 |
themes: dict[str, EntryPoint] = {} |
| 266 |
eps: dict[EntryPoint, None] = dict.fromkeys(entry_points(group='mkdocs.themes')) |
| 267 |
builtins = {ep.name for ep in eps if ep.dist is not None and ep.dist.name == 'mkdocs'} |
| 268 |
|
| 269 |
for theme in eps: |
| 270 |
assert theme.dist is not None |
| 271 |
|
| 272 |
if theme.name in builtins and theme.dist.name != 'mkdocs': |
| 273 |
raise exceptions.ConfigurationError( |
| 274 |
f"The theme '{theme.name}' is a builtin theme but the package '{theme.dist.name}' " |
| 275 |
"attempts to provide a theme with the same name." |
| 276 |
) |
| 277 |
elif theme.name in themes: |
| 278 |
other_dist = themes[theme.name].dist |
| 279 |
assert other_dist is not None |
| 280 |
log.warning( |
| 281 |
f"A theme named '{theme.name}' is provided by the Python packages '{theme.dist.name}' " |
| 282 |
f"and '{other_dist.name}'. The one in '{theme.dist.name}' will be used." |
| 283 |
) |
| 284 |
|
| 285 |
themes[theme.name] = theme |
| 286 |
|
| 287 |
return themes |
| 288 |
|
| 289 |
|
| 290 |
def get_theme_names() -> Collection[str]: |
| 291 |
"""Return a list of all installed themes by name.""" |
| 292 |
return get_themes().keys() |
| 293 |
|
| 294 |
|
| 295 |
def dirname_to_title(dirname: str) -> str: |
| 296 |
"""Return a page tile obtained from a directory name.""" |
| 297 |
title = dirname |
| 298 |
title = title.replace('-', ' ').replace('_', ' ') |
| 299 |
# Capitalize if the dirname was all lowercase, otherwise leave it as-is. |
| 300 |
if title.lower() == title: |
| 301 |
title = title.capitalize() |
| 302 |
|
| 303 |
return title |
| 304 |
|
| 305 |
|
| 306 |
def get_markdown_title(markdown_src: str) -> str | None: |
| 307 |
"""Soft-deprecated, do not use.""" |
| 308 |
lines = markdown_src.replace('\r\n', '\n').replace('\r', '\n').split('\n') |
| 309 |
while lines: |
| 310 |
line = lines.pop(0).strip() |
| 311 |
if not line.strip(): |
| 312 |
continue |
| 313 |
if not line.startswith('# '): |
| 314 |
return None |
| 315 |
return line.lstrip('# ') |
| 316 |
return None |
| 317 |
|
| 318 |
|
| 319 |
def find_or_create_node(branch, key): |
| 320 |
""" |
| 321 |
Given a list, look for dictionary with a key matching key and return it's |
| 322 |
value. If it doesn't exist, create it with the value of an empty list and |
| 323 |
return that. |
| 324 |
""" |
| 325 |
for node in branch: |
| 326 |
if not isinstance(node, dict): |
| 327 |
continue |
| 328 |
|
| 329 |
if key in node: |
| 330 |
return node[key] |
| 331 |
|
| 332 |
new_branch = [] |
| 333 |
node = {key: new_branch} |
| 334 |
branch.append(node) |
| 335 |
return new_branch |
| 336 |
|
| 337 |
|
| 338 |
def nest_paths(paths): |
| 339 |
""" |
| 340 |
Given a list of paths, convert them into a nested structure that will match |
| 341 |
the pages config. |
| 342 |
""" |
| 343 |
nested = [] |
| 344 |
|
| 345 |
for path in paths: |
| 346 |
parts = PurePath(path).parent.parts |
| 347 |
|
| 348 |
branch = nested |
| 349 |
for part in parts: |
| 350 |
part = dirname_to_title(part) |
| 351 |
branch = find_or_create_node(branch, part) |
| 352 |
|
| 353 |
branch.append(path) |
| 354 |
|
| 355 |
return nested |
| 356 |
|
| 357 |
|
| 358 |
class DuplicateFilter: |
| 359 |
"""Avoid logging duplicate messages.""" |
| 360 |
|
| 361 |
def __init__(self) -> None: |
| 362 |
self.msgs: set[str] = set() |
| 363 |
|
| 364 |
def __call__(self, record: logging.LogRecord) -> bool: |
| 365 |
rv = record.msg not in self.msgs |
| 366 |
self.msgs.add(record.msg) |
| 367 |
return rv |
| 368 |
|
| 369 |
|
| 370 |
class CountHandler(logging.NullHandler): |
| 371 |
"""Counts all logged messages >= level.""" |
| 372 |
|
| 373 |
def __init__(self, **kwargs) -> None: |
| 374 |
self.counts: dict[int, int] = defaultdict(int) |
| 375 |
super().__init__(**kwargs) |
| 376 |
|
| 377 |
def handle(self, record): |
| 378 |
rv = self.filter(record) |
| 379 |
if rv: |
| 380 |
# Use levelno for keys so they can be sorted later |
| 381 |
self.counts[record.levelno] += 1 |
| 382 |
return rv |
| 383 |
|
| 384 |
def get_counts(self) -> list[tuple[str, int]]: |
| 385 |
return [(logging.getLevelName(k), v) for k, v in sorted(self.counts.items(), reverse=True)] |
| 386 |
|
| 387 |
|
| 388 |
class weak_property: |
| 389 |
"""Same as a read-only property, but allows overwriting the field for good.""" |
| 390 |
|
| 391 |
def __init__(self, func): |
| 392 |
self.func = func |
| 393 |
self.__doc__ = func.__doc__ |
| 394 |
|
| 395 |
def __get__(self, instance, owner=None): |
| 396 |
if instance is None: |
| 397 |
return self |
| 398 |
return self.func(instance) |
| 399 |
|
| 400 |
|
| 401 |
def __getattr__(name: str): |
| 402 |
if name == 'warning_filter': |
| 403 |
warnings.warn( |
| 404 |
"warning_filter doesn't do anything since MkDocs 1.2 and will be removed soon. " |
| 405 |
"All messages on the `mkdocs` logger get counted automatically.", |
| 406 |
DeprecationWarning, |
| 407 |
) |
| 408 |
return logging.Filter() |
| 409 |
|
| 410 |
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") |