Debian Codegraph @

mkdocs/structure/files.py

raw
1 from __future__ import annotations
2
3 import enum
4 import fnmatch
5 import logging
6 import os
7 import posixpath
8 import shutil
9 import warnings
10 from functools import cached_property
11 from pathlib import PurePath, PurePosixPath
12 from typing import TYPE_CHECKING, Callable, Iterable, Iterator, Mapping, Sequence, overload
13 from urllib.parse import quote as urlquote
14
15 import pathspec
16 import pathspec.gitignore
17 import pathspec.util
18
19 from mkdocs import utils
20
21 if TYPE_CHECKING:
22 import jinja2.environment
23
24 from mkdocs.config.defaults import MkDocsConfig
25 from mkdocs.structure.pages import Page
26
27
28 log = logging.getLogger(__name__)
29
30
31 class InclusionLevel(enum.Enum):
32 EXCLUDED = -3
33 """The file is excluded and will not be processed."""
34 DRAFT = -2
35 """The file is excluded from the final site, but will still be populated during `mkdocs serve`."""
36 NOT_IN_NAV = -1
37 """The file is part of the site, but doesn't produce nav warnings."""
38 UNDEFINED = 0
39 """Still needs to be computed based on the config. If the config doesn't kick in, acts the same as `included`."""
40 INCLUDED = 1
41 """The file is part of the site. Documentation pages that are omitted from the nav will produce warnings."""
42
43 def all(self):
44 return True
45
46 def is_included(self):
47 return self.value > self.DRAFT.value
48
49 def is_excluded(self):
50 return self.value <= self.DRAFT.value
51
52 def is_in_serve(self):
53 return self.value >= self.DRAFT.value
54
55 def is_in_nav(self):
56 return self.value > self.NOT_IN_NAV.value
57
58 def is_not_in_nav(self):
59 return self.value <= self.NOT_IN_NAV.value
60
61
62 class Files:
63 """A collection of [File][mkdocs.structure.files.File] objects."""
64
65 def __init__(self, files: Iterable[File]) -> None:
66 self._src_uris = {f.src_uri: f for f in files}
67
68 def __iter__(self) -> Iterator[File]:
69 """Iterate over the files within."""
70 return iter(self._src_uris.values())
71
72 def __len__(self) -> int:
73 """The number of files within."""
74 return len(self._src_uris)
75
76 def __contains__(self, path: str) -> bool:
77 """Soft-deprecated, prefer `get_file_from_path(path) is not None`."""
78 return PurePath(path).as_posix() in self._src_uris
79
80 @property
81 def src_paths(self) -> dict[str, File]:
82 """Soft-deprecated, prefer `src_uris`."""
83 return {file.src_path: file for file in self}
84
85 @property
86 def src_uris(self) -> Mapping[str, File]:
87 """
88 A mapping containing every file, with the keys being their
89 [`src_uri`][mkdocs.structure.files.File.src_uri].
90 """
91 return self._src_uris
92
93 def get_file_from_path(self, path: str) -> File | None:
94 """Return a File instance with File.src_uri equal to path."""
95 return self._src_uris.get(PurePath(path).as_posix())
96
97 def append(self, file: File) -> None:
98 """Add file to the Files collection."""
99 if file.src_uri in self._src_uris:
100 warnings.warn(
101 "To replace an existing file, call `remove` before `append`.", DeprecationWarning
102 )
103 del self._src_uris[file.src_uri]
104 self._src_uris[file.src_uri] = file
105
106 def remove(self, file: File) -> None:
107 """Remove file from Files collection."""
108 try:
109 del self._src_uris[file.src_uri]
110 except KeyError:
111 raise ValueError(f'{file.src_uri!r} not in collection')
112
113 def copy_static_files(
114 self,
115 dirty: bool = False,
116 *,
117 inclusion: Callable[[InclusionLevel], bool] = InclusionLevel.is_included,
118 ) -> None:
119 """Copy static files from source to destination."""
120 for file in self:
121 if not file.is_documentation_page() and inclusion(file.inclusion):
122 file.copy_file(dirty)
123
124 def documentation_pages(
125 self, *, inclusion: Callable[[InclusionLevel], bool] = InclusionLevel.is_included
126 ) -> Sequence[File]:
127 """Return iterable of all Markdown page file objects."""
128 return [file for file in self if file.is_documentation_page() and inclusion(file.inclusion)]
129
130 def static_pages(self) -> Sequence[File]:
131 """Return iterable of all static page file objects."""
132 return [file for file in self if file.is_static_page()]
133
134 def media_files(self) -> Sequence[File]:
135 """Return iterable of all file objects which are not documentation or static pages."""
136 return [file for file in self if file.is_media_file()]
137
138 def javascript_files(self) -> Sequence[File]:
139 """Return iterable of all javascript file objects."""
140 return [file for file in self if file.is_javascript()]
141
142 def css_files(self) -> Sequence[File]:
143 """Return iterable of all CSS file objects."""
144 return [file for file in self if file.is_css()]
145
146 def add_files_from_theme(self, env: jinja2.Environment, config: MkDocsConfig) -> None:
147 """Retrieve static files from Jinja environment and add to collection."""
148
149 def filter(name):
150 # '.*' filters dot files/dirs at root level whereas '*/.*' filters nested levels
151 patterns = ['.*', '*/.*', '*.py', '*.pyc', '*.html', '*readme*', 'mkdocs_theme.yml']
152 # Exclude translation files
153 patterns.append("locales/*")
154 patterns.extend(f'*{x}' for x in utils.markdown_extensions)
155 patterns.extend(config.theme.static_templates)
156 for pattern in patterns:
157 if fnmatch.fnmatch(name.lower(), pattern):
158 return False
159 return True
160
161 for path in env.list_templates(filter_func=filter):
162 # Theme files do not override docs_dir files
163 if self.get_file_from_path(path) is None:
164 for dir in config.theme.dirs:
165 # Find the first theme dir which contains path
166 if os.path.isfile(os.path.join(dir, path)):
167 self.append(File(path, dir, config.site_dir, config.use_directory_urls))
168 break
169
170 @property
171 def _files(self) -> Iterable[File]:
172 warnings.warn("Do not access Files._files.", DeprecationWarning)
173 return self
174
175 @_files.setter
176 def _files(self, value: Iterable[File]):
177 warnings.warn("Do not access Files._files.", DeprecationWarning)
178 self._src_uris = {f.src_uri: f for f in value}
179
180
181 class File:
182 """
183 A MkDocs File object.
184
185 It represents how the contents of one file should be populated in the destination site.
186
187 A file always has its `abs_dest_path` (obtained by joining `dest_dir` and `dest_path`),
188 where the `dest_dir` is understood to be the *site* directory.
189
190 `content_bytes`/`content_string` (new in MkDocs 1.6) can always be used to obtain the file's
191 content. But it may be backed by one of the two sources:
192
193 * A physical source file at `abs_src_path` (by default obtained by joining `src_dir` and
194 `src_uri`). `src_dir` is understood to be the *docs* directory.
195
196 Then `content_bytes`/`content_string` will read the file at `abs_src_path`.
197
198 `src_dir` *should* be populated for real files and should be `None` for generated files.
199
200 * Since MkDocs 1.6 a file may alternatively be stored in memory - `content_string`/`content_bytes`.
201
202 Then `src_dir` and `abs_src_path` will remain `None`. `content_bytes`/`content_string` need
203 to be written to, or populated through the `content` argument in the constructor.
204
205 But `src_uri` is still populated for such files as well! The virtual file pretends as if it
206 originated from that path in the `docs` directory, and other values are derived.
207
208 For static files the file is just copied to the destination, and `dest_uri` equals `src_uri`.
209
210 For Markdown files (determined by the file extension in `src_uri`) the destination content
211 will be the rendered content, and `dest_uri` will have the `.html` extension and some
212 additional transformations to the path, based on `use_directory_urls`.
213 """
214
215 src_uri: str
216 """The pure path (always '/'-separated) of the source file relative to the source directory."""
217
218 use_directory_urls: bool
219 """Whether directory URLs ('foo/') should be used or not ('foo.html').
220
221 If `False`, a Markdown file is mapped to an HTML file of the same name (the file extension is
222 changed to `.html`). If True, a Markdown file is mapped to an HTML index file (`index.html`)
223 nested in a directory using the "name" of the file in `path`. Non-Markdown files retain their
224 original path.
225 """
226
227 src_dir: str | None
228 """The OS path of the top-level directory that the source file originates from.
229
230 Assumed to be the *docs_dir*; not populated for generated files."""
231
232 dest_dir: str
233 """The OS path of the destination directory (top-level site_dir) that the file should be copied to."""
234
235 inclusion: InclusionLevel = InclusionLevel.UNDEFINED
236 """Whether the file will be excluded from the built site."""
237
238 generated_by: str | None = None
239 """If not None, indicates that a plugin generated this file on the fly.
240
241 The value is the plugin's entrypoint name and can be used to find the plugin by key in the PluginCollection."""
242
243 _content: str | bytes | None = None
244 """If set, the file's content will be read from here.
245
246 This logic is handled by `content_bytes`/`content_string`, which should be used instead of
247 accessing this attribute."""
248
249 @property
250 def src_path(self) -> str:
251 """Same as `src_uri` (and synchronized with it) but will use backslashes on Windows. Discouraged."""
252 return os.path.normpath(self.src_uri)
253
254 @src_path.setter
255 def src_path(self, value: str):
256 self.src_uri = PurePath(value).as_posix()
257
258 @property
259 def dest_path(self) -> str:
260 """Same as `dest_uri` (and synchronized with it) but will use backslashes on Windows. Discouraged."""
261 return os.path.normpath(self.dest_uri)
262
263 @dest_path.setter
264 def dest_path(self, value: str):
265 self.dest_uri = PurePath(value).as_posix()
266
267 page: Page | None = None
268
269 @overload
270 @classmethod
271 def generated(
272 cls,
273 config: MkDocsConfig,
274 src_uri: str,
275 *,
276 content: str | bytes,
277 inclusion: InclusionLevel = InclusionLevel.UNDEFINED,
278 ) -> File:
279 """
280 Create a virtual file backed by in-memory content.
281
282 It will pretend to be a file in the docs dir at `src_uri`.
283 """
284
285 @overload
286 @classmethod
287 def generated(
288 cls,
289 config: MkDocsConfig,
290 src_uri: str,
291 *,
292 abs_src_path: str,
293 inclusion: InclusionLevel = InclusionLevel.UNDEFINED,
294 ) -> File:
295 """
296 Create a virtual file backed by a physical temporary file at `abs_src_path`.
297
298 It will pretend to be a file in the docs dir at `src_uri`.
299 """
300
301 @classmethod
302 def generated(
303 cls,
304 config: MkDocsConfig,
305 src_uri: str,
306 *,
307 content: str | bytes | None = None,
308 abs_src_path: str | None = None,
309 inclusion: InclusionLevel = InclusionLevel.UNDEFINED,
310 ) -> File:
311 """
312 Create a virtual file, backed either by in-memory `content` or by a file at `abs_src_path`.
313
314 It will pretend to be a file in the docs dir at `src_uri`.
315 """
316 if (content is None) == (abs_src_path is None):
317 raise TypeError("File must have exactly one of 'content' or 'abs_src_path'")
318 f = cls(
319 src_uri,
320 src_dir=None,
321 dest_dir=config.site_dir,
322 use_directory_urls=config.use_directory_urls,
323 inclusion=inclusion,
324 )
325 f.generated_by = config.plugins._current_plugin or '<unknown>'
326 f.abs_src_path = abs_src_path
327 f._content = content
328 return f
329
330 def __init__(
331 self,
332 path: str,
333 src_dir: str | None,
334 dest_dir: str,
335 use_directory_urls: bool,
336 *,
337 dest_uri: str | None = None,
338 inclusion: InclusionLevel = InclusionLevel.UNDEFINED,
339 ) -> None:
340 self.src_path = path
341 self.src_dir = src_dir
342 self.dest_dir = dest_dir
343 self.use_directory_urls = use_directory_urls
344 if dest_uri is not None:
345 self.dest_uri = dest_uri
346 self.inclusion = inclusion
347
348 def __repr__(self):
349 return (
350 f"{type(self).__name__}({self.src_uri!r}, src_dir={self.src_dir!r}, "
351 f"dest_dir={self.dest_dir!r}, use_directory_urls={self.use_directory_urls!r}, "
352 f"dest_uri={self.dest_uri!r}, inclusion={self.inclusion})"
353 )
354
355 @utils.weak_property
356 def edit_uri(self) -> str | None:
357 """
358 A path relative to the source repository to use for the "edit" button.
359
360 Defaults to `src_uri` and can be overwritten.
361 For generated files this should be set to `None`.
362 """
363 return self.src_uri if self.generated_by is None else None
364
365 def _get_stem(self) -> str:
366 """Soft-deprecated, do not use."""
367 filename = posixpath.basename(self.src_uri)
368 stem, ext = posixpath.splitext(filename)
369 return 'index' if stem == 'README' else stem
370
371 name = cached_property(_get_stem)
372 """Return the name of the file without its extension."""
373
374 def _get_dest_path(self, use_directory_urls: bool | None = None) -> str:
375 """Soft-deprecated, do not use."""
376 if self.is_documentation_page():
377 parent, filename = posixpath.split(self.src_uri)
378 if use_directory_urls is None:
379 use_directory_urls = self.use_directory_urls
380 if not use_directory_urls or self.name == 'index':
381 # index.md or README.md => index.html
382 # foo.md => foo.html
383 return posixpath.join(parent, self.name + '.html')
384 else:
385 # foo.md => foo/index.html
386 return posixpath.join(parent, self.name, 'index.html')
387 return self.src_uri
388
389 dest_uri = cached_property(_get_dest_path)
390 """The pure path (always '/'-separated) of the destination file relative to the destination directory."""
391
392 def _get_url(self, use_directory_urls: bool | None = None) -> str:
393 """Soft-deprecated, do not use."""
394 url = self.dest_uri
395 dirname, filename = posixpath.split(url)
396 if use_directory_urls is None:
397 use_directory_urls = self.use_directory_urls
398 if use_directory_urls and filename == 'index.html':
399 url = (dirname or '.') + '/'
400 return urlquote(url)
401
402 url = cached_property(_get_url)
403 """The URI of the destination file relative to the destination directory as a string."""
404
405 @cached_property
406 def abs_src_path(self) -> str | None:
407 """
408 The absolute concrete path of the source file. Will use backslashes on Windows.
409
410 Note: do not use this path to read the file, prefer `content_bytes`/`content_string`.
411 """
412 if self.src_dir is None:
413 return None
414 return os.path.normpath(os.path.join(self.src_dir, self.src_uri))
415
416 @cached_property
417 def abs_dest_path(self) -> str:
418 """The absolute concrete path of the destination file. Will use backslashes on Windows."""
419 return os.path.normpath(os.path.join(self.dest_dir, self.dest_uri))
420
421 def url_relative_to(self, other: File | str) -> str:
422 """Return url for file relative to other file."""
423 return utils.get_relative_url(self.url, other.url if isinstance(other, File) else other)
424
425 @property
426 def content_bytes(self) -> bytes:
427 """
428 Get the content of this file as a bytestring.
429
430 May raise if backed by a real file (`abs_src_path`) if it cannot be read.
431
432 If used as a setter, it defines the content of the file, and `abs_src_path` becomes unset.
433 """
434 content = self._content
435 if content is None:
436 assert self.abs_src_path is not None
437 with open(self.abs_src_path, 'rb') as f:
438 return f.read()
439 if not isinstance(content, bytes):
440 content = content.encode()
441 return content
442
443 @content_bytes.setter
444 def content_bytes(self, value: bytes):
445 assert isinstance(value, bytes)
446 self._content = value
447 self.abs_src_path = None
448
449 @property
450 def content_string(self) -> str:
451 """
452 Get the content of this file as a string. Assumes UTF-8 encoding, may raise.
453
454 May also raise if backed by a real file (`abs_src_path`) if it cannot be read.
455
456 If used as a setter, it defines the content of the file, and `abs_src_path` becomes unset.
457 """
458 content = self._content
459 if content is None:
460 assert self.abs_src_path is not None
461 with open(self.abs_src_path, encoding='utf-8-sig', errors='strict') as f:
462 return f.read()
463 if not isinstance(content, str):
464 content = content.decode('utf-8-sig', errors='strict')
465 return content
466
467 @content_string.setter
468 def content_string(self, value: str):
469 assert isinstance(value, str)
470 self._content = value
471 self.abs_src_path = None
472
473 def copy_file(self, dirty: bool = False) -> None:
474 """Copy source file to destination, ensuring parent directories exist."""
475 if dirty and not self.is_modified():
476 log.debug(f"Skip copying unmodified file: '{self.src_uri}'")
477 return
478 log.debug(f"Copying media file: '{self.src_uri}'")
479 output_path = self.abs_dest_path
480 os.makedirs(os.path.dirname(output_path), exist_ok=True)
481 content = self._content
482 if content is None:
483 assert self.abs_src_path is not None
484 try:
485 utils.copy_file(self.abs_src_path, output_path)
486 except shutil.SameFileError:
487 pass # Let plugins write directly into site_dir.
488 elif isinstance(content, str):
489 with open(output_path, 'w', encoding='utf-8') as output_file:
490 output_file.write(content)
491 else:
492 with open(output_path, 'wb') as output_file:
493 output_file.write(content)
494
495 def is_modified(self) -> bool:
496 if self._content is not None:
497 return True
498 assert self.abs_src_path is not None
499 if os.path.isfile(self.abs_dest_path):
500 return os.path.getmtime(self.abs_dest_path) < os.path.getmtime(self.abs_src_path)
501 return True
502
503 def is_documentation_page(self) -> bool:
504 """Return True if file is a Markdown page."""
505 return utils.is_markdown_file(self.src_uri)
506
507 def is_static_page(self) -> bool:
508 """Return True if file is a static page (HTML, XML, JSON)."""
509 return self.src_uri.endswith(('.html', '.htm', '.xml', '.json'))
510
511 def is_media_file(self) -> bool:
512 """Return True if file is not a documentation or static page."""
513 return not (self.is_documentation_page() or self.is_static_page())
514
515 def is_javascript(self) -> bool:
516 """Return True if file is a JavaScript file."""
517 return self.src_uri.endswith(('.js', '.javascript', '.mjs'))
518
519 def is_css(self) -> bool:
520 """Return True if file is a CSS file."""
521 return self.src_uri.endswith('.css')
522
523
524 _default_exclude = pathspec.gitignore.GitIgnoreSpec.from_lines(['.*', '/templates/'])
525
526
527 def set_exclusions(files: Iterable[File], config: MkDocsConfig) -> None:
528 """Re-calculate which files are excluded, based on the patterns in the config."""
529 exclude: pathspec.gitignore.GitIgnoreSpec | None = config.get('exclude_docs')
530 exclude = _default_exclude + exclude if exclude else _default_exclude
531 drafts: pathspec.gitignore.GitIgnoreSpec | None = config.get('draft_docs')
532 nav_exclude: pathspec.gitignore.GitIgnoreSpec | None = config.get('not_in_nav')
533
534 for file in files:
535 if file.inclusion == InclusionLevel.UNDEFINED:
536 if exclude.match_file(file.src_uri):
537 file.inclusion = InclusionLevel.EXCLUDED
538 elif drafts and drafts.match_file(file.src_uri):
539 file.inclusion = InclusionLevel.DRAFT
540 elif nav_exclude and nav_exclude.match_file(file.src_uri):
541 file.inclusion = InclusionLevel.NOT_IN_NAV
542 else:
543 file.inclusion = InclusionLevel.INCLUDED
544
545
546 def get_files(config: MkDocsConfig) -> Files:
547 """Walk the `docs_dir` and return a Files collection."""
548 files: list[File] = []
549 conflicting_files: list[tuple[File, File]] = []
550 for source_dir, dirnames, filenames in os.walk(config['docs_dir'], followlinks=True):
551 relative_dir = os.path.relpath(source_dir, config['docs_dir'])
552 dirnames.sort()
553 filenames.sort(key=_file_sort_key)
554
555 files_by_dest: dict[str, File] = {}
556 for filename in filenames:
557 file = File(
558 os.path.join(relative_dir, filename),
559 config['docs_dir'],
560 config['site_dir'],
561 config['use_directory_urls'],
562 )
563 # Skip README.md if an index file also exists in dir (part 1)
564 prev_file = files_by_dest.setdefault(file.dest_uri, file)
565 if prev_file is not file:
566 conflicting_files.append((prev_file, file))
567 files.append(file)
568 prev_file = file
569
570 set_exclusions(files, config)
571 # Skip README.md if an index file also exists in dir (part 2)
572 for a, b in conflicting_files:
573 if b.inclusion.is_included():
574 if a.inclusion.is_included():
575 log.warning(
576 f"Excluding '{a.src_uri}' from the site because it conflicts with '{b.src_uri}'."
577 )
578 try:
579 files.remove(a)
580 except ValueError:
581 pass # Catching this to avoid errors if attempting to remove the same file twice.
582 else:
583 try:
584 files.remove(b)
585 except ValueError:
586 pass
587
588 return Files(files)
589
590
591 def file_sort_key(f: File, /):
592 """
593 Replicates the sort order how `get_files` produces it - index first, directories last.
594
595 To sort a list of `File`, pass as the `key` argument to `sort`.
596 """
597 parts = PurePosixPath(f.src_uri).parts
598 if not parts:
599 return ()
600 return (parts[:-1], f.name != "index", parts[-1])
601
602
603 def _file_sort_key(f: str):
604 """Always sort `index` or `README` as first filename in list. This works only on basenames of files."""
605 return (os.path.splitext(f)[0] not in ('index', 'README'), f)
606
607
608 def _sort_files(filenames: Iterable[str]) -> list[str]:
609 """Soft-deprecated, do not use."""
610 return sorted(filenames, key=_file_sort_key)
611
612
613 def _filter_paths(basename: str, path: str, is_dir: bool, exclude: Iterable[str]) -> bool:
614 warnings.warn(
615 "_filter_paths is not used since MkDocs 1.5 and will be removed soon.", DeprecationWarning
616 )
617 for item in exclude:
618 # Items ending in '/' apply only to directories.
619 if item.endswith('/') and not is_dir:
620 continue
621 # Items starting with '/' apply to the whole path.
622 # In any other cases just the basename is used.
623 match = path if item.startswith('/') else basename
624 if fnmatch.fnmatch(match, item.strip('/')):
625 return True
626 return False