Debian Codegraph @

mkdocs/structure/pages.py

raw
1 from __future__ import annotations
2
3 import enum
4 import logging
5 import posixpath
6 import warnings
7 from typing import TYPE_CHECKING, Any, Callable, Iterator, MutableMapping, Sequence
8 from urllib.parse import unquote as urlunquote
9 from urllib.parse import urljoin, urlsplit, urlunsplit
10
11 import markdown
12 import markdown.extensions.toc
13 import markdown.htmlparser # type: ignore
14 import markdown.postprocessors
15 import markdown.treeprocessors
16 from markdown.util import AMP_SUBSTITUTE
17
18 from mkdocs import utils
19 from mkdocs.structure import StructureItem
20 from mkdocs.structure.toc import get_toc
21 from mkdocs.utils import _removesuffix, get_build_date, get_markdown_title, meta, weak_property
22 from mkdocs.utils.rendering import get_heading_text
23
24 if TYPE_CHECKING:
25 from xml.etree import ElementTree as etree
26
27 from mkdocs.config.defaults import MkDocsConfig
28 from mkdocs.structure.files import File, Files
29 from mkdocs.structure.toc import TableOfContents
30
31
32 log = logging.getLogger(__name__)
33
34
35 class Page(StructureItem):
36 def __init__(self, title: str | None, file: File, config: MkDocsConfig) -> None:
37 file.page = self
38 self.file = file
39 if title is not None:
40 self.title = title
41
42 # Navigation attributes
43 self.children = None
44 self.previous_page = None
45 self.next_page = None
46 self.active = False
47
48 self.update_date: str = get_build_date()
49
50 self._set_canonical_url(config.get('site_url', None))
51 self._set_edit_url(
52 config.get('repo_url', None), config.get('edit_uri'), config.get('edit_uri_template')
53 )
54
55 # Placeholders to be filled in later in the build process.
56 self.markdown = None
57 self._title_from_render: str | None = None
58 self.content = None
59 self.toc = [] # type: ignore
60 self.meta = {}
61
62 def __eq__(self, other) -> bool:
63 return (
64 isinstance(other, self.__class__)
65 and self.title == other.title
66 and self.file == other.file
67 )
68
69 def __repr__(self):
70 name = self.__class__.__name__
71 title = f"{self.title!r}" if self.title is not None else '[blank]'
72 url = self.abs_url or self.file.url
73 return f"{name}(title={title}, url={url!r})"
74
75 markdown: str | None
76 """The original Markdown content from the file."""
77
78 content: str | None
79 """The rendered Markdown as HTML, this is the contents of the documentation.
80
81 Populated after `.render()`."""
82
83 toc: TableOfContents
84 """An iterable object representing the Table of contents for a page. Each item in
85 the `toc` is an [`AnchorLink`][mkdocs.structure.toc.AnchorLink]."""
86
87 meta: MutableMapping[str, Any]
88 """A mapping of the metadata included at the top of the markdown page."""
89
90 @property
91 def url(self) -> str:
92 """The URL of the page relative to the MkDocs `site_dir`."""
93 url = self.file.url
94 if url in ('.', './'):
95 return ''
96 return url
97
98 file: File
99 """The documentation [`File`][mkdocs.structure.files.File] that the page is being rendered from."""
100
101 abs_url: str | None
102 """The absolute URL of the page from the server root as determined by the value
103 assigned to the [site_url][] configuration setting. The value includes any
104 subdirectory included in the `site_url`, but not the domain. [base_url][] should
105 not be used with this variable."""
106
107 canonical_url: str | None
108 """The full, canonical URL to the current page as determined by the value assigned
109 to the [site_url][] configuration setting. The value includes the domain and any
110 subdirectory included in the `site_url`. [base_url][] should not be used with this
111 variable."""
112
113 @property
114 def active(self) -> bool:
115 """When `True`, indicates that this page is the currently viewed page. Defaults to `False`."""
116 return self.__active
117
118 @active.setter
119 def active(self, value: bool):
120 """Set active status of page and ancestors."""
121 self.__active = bool(value)
122 if self.parent is not None:
123 self.parent.active = bool(value)
124
125 @property
126 def is_index(self) -> bool:
127 return self.file.name == 'index'
128
129 edit_url: str | None
130 """The full URL to the source page in the source repository. Typically used to
131 provide a link to edit the source page. [base_url][] should not be used with this
132 variable."""
133
134 @property
135 def is_homepage(self) -> bool:
136 """Evaluates to `True` for the homepage of the site and `False` for all other pages."""
137 return self.is_top_level and self.is_index and self.file.url in ('.', './', 'index.html')
138
139 previous_page: Page | None
140 """The [page][mkdocs.structure.pages.Page] object for the previous page or `None`.
141 The value will be `None` if the current page is the first item in the site navigation
142 or if the current page is not included in the navigation at all."""
143
144 next_page: Page | None
145 """The [page][mkdocs.structure.pages.Page] object for the next page or `None`.
146 The value will be `None` if the current page is the last item in the site navigation
147 or if the current page is not included in the navigation at all."""
148
149 children: None = None
150 """Pages do not contain children and the attribute is always `None`."""
151
152 is_section: bool = False
153 """Indicates that the navigation object is a "section" object. Always `False` for page objects."""
154
155 is_page: bool = True
156 """Indicates that the navigation object is a "page" object. Always `True` for page objects."""
157
158 is_link: bool = False
159 """Indicates that the navigation object is a "link" object. Always `False` for page objects."""
160
161 def _set_canonical_url(self, base: str | None) -> None:
162 if base:
163 if not base.endswith('/'):
164 base += '/'
165 self.canonical_url = canonical_url = urljoin(base, self.url)
166 self.abs_url = urlsplit(canonical_url).path
167 else:
168 self.canonical_url = None
169 self.abs_url = None
170
171 def _set_edit_url(
172 self,
173 repo_url: str | None,
174 edit_uri: str | None = None,
175 edit_uri_template: str | None = None,
176 ) -> None:
177 if not edit_uri_template and not edit_uri:
178 self.edit_url = None
179 return
180 src_uri = self.file.edit_uri
181 if src_uri is None:
182 self.edit_url = None
183 return
184
185 if edit_uri_template:
186 noext = posixpath.splitext(src_uri)[0]
187 file_edit_uri = edit_uri_template.format(path=src_uri, path_noext=noext)
188 else:
189 assert edit_uri is not None and edit_uri.endswith('/')
190 file_edit_uri = edit_uri + src_uri
191
192 if repo_url:
193 # Ensure urljoin behavior is correct
194 if not file_edit_uri.startswith(('?', '#')) and not repo_url.endswith('/'):
195 repo_url += '/'
196 else:
197 try:
198 parsed_url = urlsplit(file_edit_uri)
199 if not parsed_url.scheme or not parsed_url.netloc:
200 log.warning(
201 f"edit_uri: {file_edit_uri!r} is not a valid URL, it should include the http:// (scheme)"
202 )
203 except ValueError as e:
204 log.warning(f"edit_uri: {file_edit_uri!r} is not a valid URL: {e}")
205
206 self.edit_url = urljoin(repo_url or '', file_edit_uri)
207
208 def read_source(self, config: MkDocsConfig) -> None:
209 source = config.plugins.on_page_read_source(page=self, config=config)
210 if source is None:
211 try:
212 source = self.file.content_string
213 except OSError:
214 log.error(f'File not found: {self.file.src_path}')
215 raise
216 except ValueError:
217 log.error(f'Encoding error reading file: {self.file.src_path}')
218 raise
219
220 self.markdown, self.meta = meta.get_data(source)
221
222 def _set_title(self) -> None:
223 warnings.warn(
224 "_set_title is no longer used in MkDocs and will be removed soon.", DeprecationWarning
225 )
226
227 @weak_property
228 def title(self) -> str | None: # type: ignore[override]
229 """
230 Returns the title for the current page.
231
232 Before calling `read_source()`, this value is empty. It can also be updated by `render()`.
233
234 Checks these in order and uses the first that returns a valid title:
235
236 - value provided on init (passed in from config)
237 - value of metadata 'title'
238 - content of the first H1 in Markdown content
239 - convert filename to title
240 """
241 if self.markdown is None:
242 return None
243
244 if 'title' in self.meta:
245 return self.meta['title']
246
247 if self._title_from_render:
248 return self._title_from_render
249 elif self.content is None: # Preserve legacy behavior only for edge cases in plugins.
250 title_from_md = get_markdown_title(self.markdown)
251 if title_from_md is not None:
252 return title_from_md
253
254 if self.is_homepage:
255 return 'Home'
256
257 title = self.file.name.replace('-', ' ').replace('_', ' ')
258 # Capitalize if the filename was all lowercase, otherwise leave it as-is.
259 if title.lower() == title:
260 title = title.capitalize()
261 return title
262
263 def render(self, config: MkDocsConfig, files: Files) -> None:
264 """Convert the Markdown source file to HTML as per the config."""
265 if self.markdown is None:
266 raise RuntimeError("`markdown` field hasn't been set (via `read_source`)")
267
268 md = markdown.Markdown(
269 extensions=config['markdown_extensions'],
270 extension_configs=config['mdx_configs'] or {},
271 )
272
273 raw_html_ext = _RawHTMLPreprocessor()
274 raw_html_ext._register(md)
275
276 extract_anchors_ext = _ExtractAnchorsTreeprocessor(self.file, files, config)
277 extract_anchors_ext._register(md)
278
279 relative_path_ext = _RelativePathTreeprocessor(self.file, files, config)
280 relative_path_ext._register(md)
281
282 extract_title_ext = _ExtractTitleTreeprocessor()
283 extract_title_ext._register(md)
284
285 self.content = md.convert(self.markdown)
286 self.toc = get_toc(getattr(md, 'toc_tokens', []))
287 self._title_from_render = extract_title_ext.title
288 self.present_anchor_ids = (
289 extract_anchors_ext.present_anchor_ids | raw_html_ext.present_anchor_ids
290 )
291 if log.getEffectiveLevel() > logging.DEBUG:
292 self.links_to_anchors = relative_path_ext.links_to_anchors
293
294 present_anchor_ids: set[str] | None = None
295 """Anchor IDs that this page contains (can be linked to in this page)."""
296
297 links_to_anchors: dict[File, dict[str, str]] | None = None
298 """Links to anchors in other files that this page contains.
299
300 The structure is: `{file_that_is_linked_to: {'anchor': 'original_link/to/some_file.md#anchor'}}`.
301 Populated after `.render()`. Populated only if `validation: {anchors: info}` (or greater) is set.
302 """
303
304 def validate_anchor_links(self, *, files: Files, log_level: int) -> None:
305 if not self.links_to_anchors:
306 return
307 for to_file, links in self.links_to_anchors.items():
308 for anchor, original_link in links.items():
309 page = to_file.page
310 if page is None:
311 continue
312 if page.present_anchor_ids is None: # Page was somehow not rendered.
313 continue
314 if anchor in page.present_anchor_ids:
315 continue
316 context = ""
317 if to_file == self.file:
318 problem = "there is no such anchor on this page"
319 if anchor.startswith('fnref:'):
320 context = " This seems to be a footnote that is never referenced."
321 else:
322 problem = f"the doc '{to_file.src_uri}' does not contain an anchor '#{anchor}'"
323 log.log(
324 log_level,
325 f"Doc file '{self.file.src_uri}' contains a link '{original_link}', but {problem}.{context}",
326 )
327
328
329 class _ExtractAnchorsTreeprocessor(markdown.treeprocessors.Treeprocessor):
330 def __init__(self, file: File, files: Files, config: MkDocsConfig) -> None:
331 self.present_anchor_ids: set[str] = set()
332
333 def run(self, root: etree.Element) -> None:
334 add = self.present_anchor_ids.add
335 for element in root.iter():
336 if anchor := element.get('id'):
337 add(anchor)
338 if element.tag == 'a':
339 if anchor := element.get('name'):
340 add(anchor)
341
342 def _register(self, md: markdown.Markdown) -> None:
343 md.treeprocessors.register(self, "mkdocs_extract_anchors", priority=5) # Same as 'toc'.
344
345
346 class _RelativePathTreeprocessor(markdown.treeprocessors.Treeprocessor):
347 def __init__(self, file: File, files: Files, config: MkDocsConfig) -> None:
348 self.file = file
349 self.files = files
350 self.config = config
351 self.links_to_anchors: dict[File, dict[str, str]] = {}
352
353 def run(self, root: etree.Element) -> etree.Element:
354 """
355 Update urls on anchors and images to make them relative.
356
357 Iterates through the full document tree looking for specific
358 tags and then makes them relative based on the site navigation
359 """
360 for element in root.iter():
361 if element.tag == 'a':
362 key = 'href'
363 elif element.tag == 'img':
364 key = 'src'
365 else:
366 continue
367
368 url = element.get(key)
369 assert url is not None
370 new_url = self.path_to_url(url)
371 element.set(key, new_url)
372
373 return root
374
375 @classmethod
376 def _target_uri(cls, src_path: str, dest_path: str) -> str:
377 return posixpath.normpath(
378 posixpath.join(posixpath.dirname(src_path), dest_path).lstrip('/')
379 )
380
381 @classmethod
382 def _possible_target_uris(
383 cls, file: File, path: str, use_directory_urls: bool, suggest_absolute: bool = False
384 ) -> Iterator[str]:
385 """First yields the resolved file uri for the link, then proceeds to yield guesses for possible mistakes."""
386 target_uri = cls._target_uri(file.src_uri, path)
387 yield target_uri
388
389 if posixpath.normpath(path) == '.':
390 # Explicitly link to current file.
391 yield file.src_uri
392 return
393 tried = {target_uri}
394
395 prefixes = [target_uri, cls._target_uri(file.url, path)]
396 if prefixes[0] == prefixes[1]:
397 prefixes.pop()
398
399 suffixes: list[Callable[[str], str]] = []
400 if use_directory_urls:
401 suffixes.append(lambda p: p)
402 if not posixpath.splitext(target_uri)[-1]:
403 suffixes.append(lambda p: posixpath.join(p, 'index.md'))
404 suffixes.append(lambda p: posixpath.join(p, 'README.md'))
405 if (
406 not target_uri.endswith('.')
407 and not path.endswith('.md')
408 and (use_directory_urls or not path.endswith('/'))
409 ):
410 suffixes.append(lambda p: _removesuffix(p, '.html') + '.md')
411
412 for pref in prefixes:
413 for suf in suffixes:
414 guess = posixpath.normpath(suf(pref))
415 if guess not in tried and not guess.startswith('../'):
416 yield guess
417 tried.add(guess)
418
419 def path_to_url(self, url: str) -> str:
420 scheme, netloc, path, query, anchor = urlsplit(url)
421
422 absolute_link = None
423 warning_level, warning = 0, ''
424
425 # Ignore URLs unless they are a relative link to a source file.
426 if scheme or netloc: # External link.
427 return url
428 elif url.startswith(('/', '\\')): # Absolute link.
429 absolute_link = self.config.validation.links.absolute_links
430 if absolute_link is not _AbsoluteLinksValidationValue.RELATIVE_TO_DOCS:
431 warning_level = absolute_link
432 warning = f"Doc file '{self.file.src_uri}' contains an absolute link '{url}', it was left as is."
433 elif AMP_SUBSTITUTE in url: # AMP_SUBSTITUTE is used internally by Markdown only for email.
434 return url
435 elif not path: # Self-link containing only query or anchor.
436 if anchor:
437 # Register that the page links to itself with an anchor.
438 self.links_to_anchors.setdefault(self.file, {}).setdefault(anchor, url)
439 return url
440
441 path = urlunquote(path)
442 # Determine the filepath of the target.
443 possible_target_uris = self._possible_target_uris(
444 self.file, path, self.config.use_directory_urls
445 )
446
447 if warning:
448 # For absolute path (already has a warning), the primary lookup path should be preserved as a tip option.
449 target_uri = url
450 target_file = None
451 else:
452 # Validate that the target exists in files collection.
453 target_uri = next(possible_target_uris)
454 target_file = self.files.get_file_from_path(target_uri)
455
456 if target_file is None and not warning:
457 # Primary lookup path had no match, definitely produce a warning, just choose which one.
458 if not posixpath.splitext(path)[-1] and absolute_link is None:
459 # No '.' in the last part of a path indicates path does not point to a file.
460 warning_level = self.config.validation.links.unrecognized_links
461 warning = (
462 f"Doc file '{self.file.src_uri}' contains an unrecognized relative link '{url}', "
463 f"it was left as is."
464 )
465 else:
466 target = f" '{target_uri}'" if target_uri != url.lstrip('/') else ""
467 warning_level = self.config.validation.links.not_found
468 warning = (
469 f"Doc file '{self.file.src_uri}' contains a link '{url}', "
470 f"but the target{target} is not found among documentation files."
471 )
472
473 if warning:
474 if self.file.inclusion.is_excluded():
475 warning_level = min(logging.INFO, warning_level)
476
477 # There was no match, so try to guess what other file could've been intended.
478 if warning_level > logging.DEBUG:
479 suggest_url = ''
480 for path in possible_target_uris:
481 if self.files.get_file_from_path(path) is not None:
482 if anchor and path == self.file.src_uri:
483 path = ''
484 elif absolute_link is _AbsoluteLinksValidationValue.RELATIVE_TO_DOCS:
485 path = '/' + path
486 else:
487 path = utils.get_relative_url(path, self.file.src_uri)
488 suggest_url = urlunsplit(('', '', path, query, anchor))
489 break
490 else:
491 if '@' in url and '.' in url and '/' not in url:
492 suggest_url = f'mailto:{url}'
493 if suggest_url:
494 warning += f" Did you mean '{suggest_url}'?"
495 log.log(warning_level, warning)
496 return url
497
498 assert target_uri is not None
499 assert target_file is not None
500
501 if anchor:
502 # Register that this page links to the target file with an anchor.
503 self.links_to_anchors.setdefault(target_file, {}).setdefault(anchor, url)
504
505 if target_file.inclusion.is_excluded():
506 if self.file.inclusion.is_excluded():
507 warning_level = logging.DEBUG
508 else:
509 warning_level = min(logging.INFO, self.config.validation.links.not_found)
510 warning = (
511 f"Doc file '{self.file.src_uri}' contains a link to "
512 f"'{target_uri}' which is excluded from the built site."
513 )
514 log.log(warning_level, warning)
515 path = utils.get_relative_url(target_file.url, self.file.url)
516 return urlunsplit(('', '', path, query, anchor))
517
518 def _register(self, md: markdown.Markdown) -> None:
519 md.treeprocessors.register(self, "relpath", 0)
520
521
522 class _RawHTMLPreprocessor(markdown.preprocessors.Preprocessor):
523 def __init__(self) -> None:
524 super().__init__()
525 self.present_anchor_ids: set[str] = set()
526
527 def run(self, lines: list[str]) -> list[str]:
528 parser = _HTMLHandler()
529 parser.feed('\n'.join(lines))
530 parser.close()
531 self.present_anchor_ids = parser.present_anchor_ids
532 return lines
533
534 def _register(self, md: markdown.Markdown) -> None:
535 md.preprocessors.register(
536 self, "mkdocs_raw_html", priority=21 # Right before 'html_block'.
537 )
538
539
540 class _HTMLHandler(markdown.htmlparser.htmlparser.HTMLParser): # type: ignore[name-defined]
541 def __init__(self) -> None:
542 super().__init__()
543 self.present_anchor_ids: set[str] = set()
544
545 def handle_starttag(self, tag: str, attrs: Sequence[tuple[str, str]]) -> None:
546 for k, v in attrs:
547 if k == 'id' or (k == 'name' and tag == 'a'):
548 self.present_anchor_ids.add(v)
549 return super().handle_starttag(tag, attrs)
550
551
552 class _ExtractTitleTreeprocessor(markdown.treeprocessors.Treeprocessor):
553 title: str | None = None
554 md: markdown.Markdown
555
556 def run(self, root: etree.Element) -> etree.Element:
557 for el in root:
558 if el.tag == 'h1':
559 self.title = get_heading_text(el, self.md)
560 break
561 return root
562
563 def _register(self, md: markdown.Markdown) -> None:
564 self.md = md
565 md.treeprocessors.register(self, "mkdocs_extract_title", priority=1) # Close to the end.
566
567
568 class _AbsoluteLinksValidationValue(enum.IntEnum):
569 RELATIVE_TO_DOCS = -1