chore: organize repository structure
This commit is contained in:
parent
d50f297eb5
commit
d7562257d3
120 changed files with 11968 additions and 177 deletions
426
scripts/dev/check-docs-links.py
Executable file
426
scripts/dev/check-docs-links.py
Executable file
|
|
@ -0,0 +1,426 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Check local Markdown file and anchor links without network access."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from dataclasses import dataclass
|
||||
import html
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import unicodedata
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MarkdownLink:
|
||||
source: Path
|
||||
line: int
|
||||
target: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Diagnostic:
|
||||
source: Path
|
||||
line: int
|
||||
target: str
|
||||
reason: str
|
||||
|
||||
|
||||
_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
|
||||
_REFERENCE_DEFINITION = re.compile(r"^ {0,3}\[([^]]+)\]:[ \t]*(.*)$")
|
||||
_ATX_HEADING = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]+(.*)|[ \t]*)$")
|
||||
_SETEXT_HEADING = re.compile(r"^ {0,3}(?:=+|-+)[ \t]*$")
|
||||
_HTML_ID = re.compile(
|
||||
r"<[^>]+\s(?:id|name)\s*=\s*(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))[^>]*>",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_TITLE_TEXT = r'(?:"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|\((?:[^)\\]|\\.)*\))'
|
||||
_TITLE = re.compile(rf'^(.*?)(?:[ \t]+{_TITLE_TEXT})?$', re.DOTALL)
|
||||
_TITLE_ONLY = re.compile(rf'^{_TITLE_TEXT}$', re.DOTALL)
|
||||
_BACKSLASH_ESCAPE = re.compile(r"\\([!\"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~])")
|
||||
|
||||
|
||||
def _is_escaped(text: str, index: int) -> bool:
|
||||
backslashes = 0
|
||||
index -= 1
|
||||
while index >= 0 and text[index] == "\\":
|
||||
backslashes += 1
|
||||
index -= 1
|
||||
return backslashes % 2 == 1
|
||||
|
||||
|
||||
def _without_code_spans(line: str) -> str:
|
||||
result = list(line)
|
||||
index = 0
|
||||
while index < len(line):
|
||||
if line[index] != "`" or _is_escaped(line, index):
|
||||
index += 1
|
||||
continue
|
||||
end = index
|
||||
while end < len(line) and line[end] == "`":
|
||||
end += 1
|
||||
delimiter = line[index:end]
|
||||
closing = line.find(delimiter, end)
|
||||
if closing < 0:
|
||||
index = end
|
||||
continue
|
||||
for position in range(index, closing + len(delimiter)):
|
||||
if result[position] != "\n":
|
||||
result[position] = " "
|
||||
index = closing + len(delimiter)
|
||||
return "".join(result)
|
||||
|
||||
|
||||
def _matching_delimiter(
|
||||
text: str, start: int, opening: str, closing: str
|
||||
) -> int | None:
|
||||
depth = 0
|
||||
in_angle_destination = False
|
||||
for index in range(start, len(text)):
|
||||
char = text[index]
|
||||
if _is_escaped(text, index):
|
||||
continue
|
||||
if opening == "(" and char == "<" and depth == 1:
|
||||
in_angle_destination = True
|
||||
elif in_angle_destination and char == ">":
|
||||
in_angle_destination = False
|
||||
elif not in_angle_destination and char == opening:
|
||||
depth += 1
|
||||
elif not in_angle_destination and char == closing:
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return index
|
||||
return None
|
||||
|
||||
|
||||
def _unescape(target: str) -> str:
|
||||
return _BACKSLASH_ESCAPE.sub(r"\1", target)
|
||||
|
||||
|
||||
def _destination(contents: str) -> str | None:
|
||||
contents = contents.strip()
|
||||
if contents.startswith("<"):
|
||||
index = 1
|
||||
while index < len(contents):
|
||||
if contents[index] == ">" and not _is_escaped(contents, index):
|
||||
rest = contents[index + 1 :].strip()
|
||||
if rest and not _TITLE_ONLY.fullmatch(rest):
|
||||
return None
|
||||
return _unescape(contents[1:index])
|
||||
if contents[index] == "\n":
|
||||
return None
|
||||
index += 1
|
||||
return None
|
||||
|
||||
match = _TITLE.fullmatch(contents)
|
||||
if match is None:
|
||||
return None
|
||||
destination = match.group(1).strip()
|
||||
if any(char in destination for char in "\r\n"):
|
||||
return None
|
||||
return _unescape(destination)
|
||||
|
||||
|
||||
def _normalise_label(label: str) -> str:
|
||||
return " ".join(label.split()).casefold()
|
||||
|
||||
|
||||
def _links_in_file(path: Path) -> list[MarkdownLink]:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
lines = text.splitlines()
|
||||
definitions: dict[str, str] = {}
|
||||
references: list[tuple[int, str, str]] = []
|
||||
links: list[MarkdownLink] = []
|
||||
fence: str | None = None
|
||||
|
||||
for line_number, original in enumerate(lines, start=1):
|
||||
fence_match = _FENCE.match(original)
|
||||
if fence is not None:
|
||||
if fence_match and fence_match.group(1)[0] == fence[0]:
|
||||
fence = None
|
||||
continue
|
||||
if fence_match:
|
||||
fence = fence_match.group(1)
|
||||
continue
|
||||
|
||||
line = _without_code_spans(original)
|
||||
definition = _REFERENCE_DEFINITION.match(line)
|
||||
if definition:
|
||||
target = _destination(definition.group(2))
|
||||
if target is not None:
|
||||
definitions[_normalise_label(definition.group(1))] = target
|
||||
continue
|
||||
|
||||
index = 0
|
||||
while index < len(line):
|
||||
if line[index] != "[" or _is_escaped(line, index):
|
||||
index += 1
|
||||
continue
|
||||
label_end = _matching_delimiter(line, index, "[", "]")
|
||||
if label_end is None:
|
||||
index += 1
|
||||
continue
|
||||
label = original[index + 1 : label_end]
|
||||
following = label_end + 1
|
||||
if following < len(line) and line[following] == "(":
|
||||
target_end = _matching_delimiter(line, following, "(", ")")
|
||||
if target_end is None:
|
||||
index = label_end + 1
|
||||
continue
|
||||
target = _destination(original[following + 1 : target_end])
|
||||
if target is not None:
|
||||
links.append(MarkdownLink(path, line_number, target))
|
||||
index = target_end + 1
|
||||
continue
|
||||
if following < len(line) and line[following] == "[":
|
||||
reference_end = _matching_delimiter(line, following, "[", "]")
|
||||
if reference_end is None:
|
||||
index = label_end + 1
|
||||
continue
|
||||
reference_label = original[following + 1 : reference_end] or label
|
||||
references.append((line_number, label, reference_label))
|
||||
index = reference_end + 1
|
||||
continue
|
||||
references.append((line_number, label, label))
|
||||
index = label_end + 1
|
||||
|
||||
for line_number, _label, reference_label in references:
|
||||
target = definitions.get(_normalise_label(reference_label))
|
||||
if target is not None:
|
||||
links.append(MarkdownLink(path, line_number, target))
|
||||
return links
|
||||
|
||||
|
||||
def _heading_text(text: str) -> str:
|
||||
previous = None
|
||||
while previous != text:
|
||||
previous = text
|
||||
text = re.sub(r"!?\[([^]]*)\]\([^)]*\)", r"\1", text)
|
||||
text = re.sub(r"!?\[([^]]*)\]\[[^]]*\]", r"\1", text)
|
||||
text = re.sub(r"<[^>]*>", "", text)
|
||||
return html.unescape(_unescape(text))
|
||||
|
||||
|
||||
def _slug(text: str) -> str:
|
||||
text = _heading_text(text).lower()
|
||||
kept = []
|
||||
for char in text:
|
||||
category = unicodedata.category(char)
|
||||
if char.isalnum() or char in "_-" or char.isspace() or category.startswith("M"):
|
||||
kept.append(char)
|
||||
return re.sub(r"\s", "-", "".join(kept))
|
||||
|
||||
|
||||
def _anchors(path: Path) -> set[str]:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
lines = text.splitlines()
|
||||
anchors: set[str] = set()
|
||||
occurrences: dict[str, int] = {}
|
||||
fence: str | None = None
|
||||
|
||||
def add_heading(heading: str) -> None:
|
||||
base = _slug(heading.strip())
|
||||
count = occurrences.get(base, 0)
|
||||
occurrences[base] = count + 1
|
||||
anchors.add(base if count == 0 else f"{base}-{count}")
|
||||
|
||||
for index, original in enumerate(lines):
|
||||
fence_match = _FENCE.match(original)
|
||||
if fence is not None:
|
||||
if fence_match and fence_match.group(1)[0] == fence[0]:
|
||||
fence = None
|
||||
continue
|
||||
if fence_match:
|
||||
fence = fence_match.group(1)
|
||||
continue
|
||||
for match in _HTML_ID.finditer(original):
|
||||
anchors.add(next(group for group in match.groups() if group is not None))
|
||||
heading = _ATX_HEADING.match(original)
|
||||
if heading:
|
||||
title = re.sub(r"[ \t]+#+[ \t]*$", "", heading.group(2) or "")
|
||||
add_heading(title)
|
||||
elif (
|
||||
index > 0
|
||||
and _SETEXT_HEADING.match(original)
|
||||
and lines[index - 1].strip()
|
||||
and not _FENCE.match(lines[index - 1])
|
||||
):
|
||||
add_heading(lines[index - 1])
|
||||
return anchors
|
||||
|
||||
|
||||
def _relative_source(root: Path, source: Path) -> str:
|
||||
return source.resolve().relative_to(root).as_posix()
|
||||
|
||||
|
||||
def _check_link(
|
||||
root: Path, link: MarkdownLink, anchor_cache: dict[Path, set[str]]
|
||||
) -> Diagnostic | None:
|
||||
target = link.target
|
||||
if re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", target):
|
||||
return None
|
||||
|
||||
try:
|
||||
parsed = urlsplit(target)
|
||||
except ValueError as error:
|
||||
return Diagnostic(link.source, link.line, target, f"malformed target: {error}")
|
||||
|
||||
try:
|
||||
decoded_path = unquote(parsed.path)
|
||||
fragment = unquote(parsed.fragment)
|
||||
except (UnicodeError, ValueError) as error:
|
||||
return Diagnostic(link.source, link.line, target, f"invalid URL encoding: {error}")
|
||||
|
||||
if decoded_path.startswith("/"):
|
||||
return None
|
||||
|
||||
try:
|
||||
if decoded_path:
|
||||
destination = (link.source.parent / decoded_path).resolve()
|
||||
destination.relative_to(root)
|
||||
else:
|
||||
destination = link.source.resolve()
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
return Diagnostic(link.source, link.line, target, "target is outside root or invalid")
|
||||
|
||||
if not destination.exists():
|
||||
return Diagnostic(link.source, link.line, target, "target does not exist")
|
||||
if not destination.is_file() and not destination.is_dir():
|
||||
return Diagnostic(link.source, link.line, target, "target is not a file or directory")
|
||||
if not fragment:
|
||||
return None
|
||||
if not destination.is_file() or destination.suffix.lower() not in {".md", ".markdown"}:
|
||||
return None
|
||||
|
||||
try:
|
||||
if destination not in anchor_cache:
|
||||
anchor_cache[destination] = _anchors(destination)
|
||||
except OSError as error:
|
||||
return Diagnostic(link.source, link.line, target, f"cannot read target: {error}")
|
||||
if fragment not in anchor_cache[destination]:
|
||||
return Diagnostic(link.source, link.line, target, "anchor does not exist")
|
||||
return None
|
||||
|
||||
|
||||
def _markdown_files(root: Path, paths: list[Path]) -> list[Path]:
|
||||
selected = paths or [Path()]
|
||||
files: set[Path] = set()
|
||||
for selected_path in selected:
|
||||
path = (root / selected_path).resolve()
|
||||
path.relative_to(root)
|
||||
if path.is_file():
|
||||
if path.suffix.lower() in {".md", ".markdown"}:
|
||||
files.add(path)
|
||||
continue
|
||||
if not path.is_dir():
|
||||
raise ValueError(f"input path does not exist: {selected_path}")
|
||||
for directory, directory_names, file_names in os.walk(path):
|
||||
directory_names[:] = [
|
||||
name
|
||||
for name in directory_names
|
||||
if name not in {".git", ".claude", "node_modules", "target"}
|
||||
]
|
||||
for name in file_names:
|
||||
candidate = Path(directory) / name
|
||||
if candidate.suffix.lower() in {".md", ".markdown"}:
|
||||
files.add(candidate.resolve())
|
||||
return sorted(files, key=lambda path: path.relative_to(root).as_posix())
|
||||
|
||||
|
||||
def _parse_allowlist(values: list[str]) -> set[tuple[str, str]]:
|
||||
allowlist: set[tuple[str, str]] = set()
|
||||
for value in values:
|
||||
source, separator, target = value.partition("=")
|
||||
if not separator or not source or not target:
|
||||
raise ValueError(f"allowlist entry must be SOURCE=TARGET: {value!r}")
|
||||
source_path = Path(source)
|
||||
if source_path.is_absolute() or ".." in source_path.parts:
|
||||
raise ValueError(f"allowlist source must be a root-relative file: {source!r}")
|
||||
normalised_source = source_path.as_posix()
|
||||
if normalised_source.startswith("./"):
|
||||
normalised_source = normalised_source[2:]
|
||||
allowlist.add((normalised_source, target))
|
||||
return allowlist
|
||||
|
||||
|
||||
def check(
|
||||
root: Path, paths: list[Path] | None = None, allowlist: set[tuple[str, str]] | None = None
|
||||
) -> tuple[list[Diagnostic], int, int]:
|
||||
root = root.resolve()
|
||||
allowed = allowlist or set()
|
||||
diagnostics: list[Diagnostic] = []
|
||||
anchor_cache: dict[Path, set[str]] = {}
|
||||
files = _markdown_files(root, paths or [])
|
||||
link_count = 0
|
||||
for source in files:
|
||||
try:
|
||||
links = _links_in_file(source)
|
||||
except OSError as error:
|
||||
diagnostics.append(Diagnostic(source, 1, source.name, f"cannot read source: {error}"))
|
||||
continue
|
||||
for link in links:
|
||||
source_name = _relative_source(root, source)
|
||||
if (source_name, link.target) in allowed:
|
||||
continue
|
||||
link_count += 1
|
||||
diagnostic = _check_link(root, link, anchor_cache)
|
||||
if diagnostic is not None:
|
||||
diagnostics.append(diagnostic)
|
||||
return diagnostics, len(files), link_count
|
||||
|
||||
|
||||
def _argument_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Check local Markdown file and anchor links; never accesses the network."
|
||||
)
|
||||
parser.add_argument("--root", type=Path, required=True, help="repository or public-tree root")
|
||||
parser.add_argument(
|
||||
"paths",
|
||||
nargs="*",
|
||||
type=Path,
|
||||
help="root-relative Markdown files or directories (default: the whole root)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--allow",
|
||||
action="append",
|
||||
default=[],
|
||||
metavar="SOURCE=TARGET",
|
||||
help="allow one exact root-relative source and raw target pair (repeatable)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--public",
|
||||
action="store_true",
|
||||
help="public-tree mode: historical allowlist entries are forbidden",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = _argument_parser()
|
||||
arguments = parser.parse_args(argv)
|
||||
if arguments.public and arguments.allow:
|
||||
parser.error("--public does not permit --allow exceptions")
|
||||
root = arguments.root.resolve()
|
||||
if not root.is_dir():
|
||||
parser.error(f"root is not a directory: {arguments.root}")
|
||||
try:
|
||||
allowlist = _parse_allowlist(arguments.allow)
|
||||
diagnostics, file_count, link_count = check(root, arguments.paths, allowlist)
|
||||
except (OSError, ValueError) as error:
|
||||
parser.error(str(error))
|
||||
|
||||
for diagnostic in diagnostics:
|
||||
source = _relative_source(root, diagnostic.source)
|
||||
print(f"{source}:{diagnostic.line} → {diagnostic.target} ({diagnostic.reason})")
|
||||
print(
|
||||
f"Checked {file_count} Markdown files, examined {link_count} non-allowlisted links; "
|
||||
f"{len(diagnostics)} broken links."
|
||||
)
|
||||
return 1 if diagnostics else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
207
scripts/dev/test_check_docs_links.py
Normal file
207
scripts/dev/test_check_docs_links.py
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).with_name("check-docs-links.py")
|
||||
SPEC = importlib.util.spec_from_file_location("check_docs_links", MODULE_PATH)
|
||||
if SPEC is None or SPEC.loader is None:
|
||||
raise ImportError(f"cannot load {MODULE_PATH}")
|
||||
check_docs_links = importlib.util.module_from_spec(SPEC)
|
||||
sys.modules[SPEC.name] = check_docs_links
|
||||
SPEC.loader.exec_module(check_docs_links)
|
||||
|
||||
|
||||
class DocsLinkCheckerTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temporary_directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary_directory.cleanup)
|
||||
self.root = Path(self.temporary_directory.name)
|
||||
|
||||
def write(self, relative: str, contents: str = "") -> Path:
|
||||
path = self.root / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(contents, encoding="utf-8")
|
||||
return path
|
||||
|
||||
def check(self, *paths: str, allowlist=None):
|
||||
selected = [Path(path) for path in paths]
|
||||
return check_docs_links.check(self.root, selected, allowlist)
|
||||
|
||||
def run_main(self, *arguments: str) -> tuple[int, str]:
|
||||
output = io.StringIO()
|
||||
with contextlib.redirect_stdout(output):
|
||||
result = check_docs_links.main(list(arguments))
|
||||
return result, output.getvalue()
|
||||
|
||||
def test_relative_dot_parent_url_decoding_and_external_links(self) -> None:
|
||||
self.write("docs/guide/start.md", "[a](./next.md) [b](../other.md)\n")
|
||||
self.write("docs/guide/next.md", "[up](../guide/start.md)\n")
|
||||
self.write("docs/other.md", "[space](<space file.md>)\n")
|
||||
self.write("docs/space file.md", "")
|
||||
self.write(
|
||||
"docs/external.md",
|
||||
"[web](https://example.invalid/missing) [http](http://example.invalid) "
|
||||
"[mail](mailto:test@example.invalid) [old](/tmp/evidence.txt)\n",
|
||||
)
|
||||
|
||||
diagnostics, file_count, link_count = self.check("docs")
|
||||
|
||||
self.assertEqual([], diagnostics)
|
||||
self.assertEqual(5, file_count)
|
||||
self.assertEqual(8, link_count)
|
||||
|
||||
def test_percent_encoded_cyrillic_path_and_anchors(self) -> None:
|
||||
encoded_name = "%D0%BF%D0%BB%D0%B0%D0%BD%20%D1%80%D0%B0%D0%B1%D0%BE%D1%82.md"
|
||||
encoded_anchor = "#%D1%86%D0%B5%D0%BB%D1%8C-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0"
|
||||
self.write("docs/index.md", f"[plan]({encoded_name}{encoded_anchor})\n")
|
||||
self.write("docs/план работ.md", "# Цель проекта\n")
|
||||
|
||||
diagnostics, _, _ = self.check()
|
||||
|
||||
self.assertEqual([], diagnostics)
|
||||
|
||||
def test_heading_slugs_duplicates_and_inline_markup(self) -> None:
|
||||
self.write(
|
||||
"docs/target.md",
|
||||
"# Hello, *world*!\n# Hello, world!\n# Раздел с пробелами\n",
|
||||
)
|
||||
self.write(
|
||||
"docs/source.md",
|
||||
"[first](target.md#hello-world) [second](target.md#hello-world-1) "
|
||||
"[cyrillic](target.md#раздел-с-пробелами)\n",
|
||||
)
|
||||
|
||||
diagnostics, _, _ = self.check()
|
||||
|
||||
self.assertEqual([], diagnostics)
|
||||
|
||||
def test_broken_file_has_precise_diagnostic_and_exit_one(self) -> None:
|
||||
self.write("docs/source.md", "prefix\n[broken](../missing.md)\n")
|
||||
|
||||
result, output = self.run_main("--root", str(self.root), "docs")
|
||||
|
||||
self.assertEqual(1, result)
|
||||
self.assertIn("docs/source.md:2 → ../missing.md (target does not exist)", output)
|
||||
self.assertIn("1 broken links", output)
|
||||
|
||||
def test_broken_anchor_is_distinct_from_broken_file(self) -> None:
|
||||
self.write("docs/target.md", "# Existing heading\n")
|
||||
self.write("docs/source.md", "[broken](target.md#missing-heading)\n")
|
||||
|
||||
diagnostics, _, _ = self.check()
|
||||
|
||||
self.assertEqual(1, len(diagnostics))
|
||||
self.assertEqual("anchor does not exist", diagnostics[0].reason)
|
||||
self.assertEqual(1, diagnostics[0].line)
|
||||
|
||||
def test_source_line_anchor_only_requires_existing_file(self) -> None:
|
||||
self.write("apps/desktop/src/lib.rs", "pub fn example() {}\n")
|
||||
self.write("docs/source.md", "[line](../apps/desktop/src/lib.rs#L1)\n")
|
||||
|
||||
diagnostics, _, _ = self.check()
|
||||
|
||||
self.assertEqual([], diagnostics)
|
||||
|
||||
def test_allowlist_requires_exact_source_and_target(self) -> None:
|
||||
self.write(
|
||||
"docs/source.md",
|
||||
"[old](/not-checked.md) [bad](missing.md) [different](other-missing.md)\n",
|
||||
)
|
||||
self.write("docs/other.md", "[bad](missing.md)\n")
|
||||
allowed = {("docs/source.md", "missing.md")}
|
||||
|
||||
diagnostics, _, _ = self.check(allowlist=allowed)
|
||||
|
||||
self.assertEqual(2, len(diagnostics))
|
||||
self.assertEqual(
|
||||
{
|
||||
(self.root / "docs/source.md", "other-missing.md"),
|
||||
(self.root / "docs/other.md", "missing.md"),
|
||||
},
|
||||
{(item.source, item.target) for item in diagnostics},
|
||||
)
|
||||
|
||||
def test_public_mode_rejects_all_allowlist_entries(self) -> None:
|
||||
self.write("README.md", "[bad](missing.md)\n")
|
||||
error_output = io.StringIO()
|
||||
|
||||
with contextlib.redirect_stderr(error_output), self.assertRaises(SystemExit) as raised:
|
||||
check_docs_links.main(
|
||||
["--root", str(self.root), "--public", "--allow", "README.md=missing.md"]
|
||||
)
|
||||
|
||||
self.assertEqual(2, raised.exception.code)
|
||||
self.assertIn("does not permit --allow", error_output.getvalue())
|
||||
|
||||
def test_malformed_links_do_not_crash(self) -> None:
|
||||
self.write(
|
||||
"docs/source.md",
|
||||
"[unclosed](target.md\n[unclosed bracket](x[y]\n"
|
||||
"[bad percent](bad%ZZ.md) [bad url](relative.md#[) "
|
||||
"[bad title](<target.md> junk)\n",
|
||||
)
|
||||
|
||||
diagnostics, _, _ = self.check()
|
||||
|
||||
self.assertEqual(2, len(diagnostics))
|
||||
self.assertTrue(all(item.line == 3 for item in diagnostics))
|
||||
|
||||
def test_code_fences_inline_code_and_unknown_references_are_ignored(self) -> None:
|
||||
self.write(
|
||||
"docs/source.md",
|
||||
"```md\n[broken](missing.md)\n```\n"
|
||||
"`[broken](inline.md)`\n[not a reference][unknown]\n",
|
||||
)
|
||||
|
||||
diagnostics, _, link_count = self.check()
|
||||
|
||||
self.assertEqual([], diagnostics)
|
||||
self.assertEqual(0, link_count)
|
||||
|
||||
def test_reference_links_and_titles_are_checked(self) -> None:
|
||||
self.write("docs/target file.md", "# Heading\n")
|
||||
self.write(
|
||||
"docs/source.md",
|
||||
"[inline](<target%20file.md#heading> \"title\")\n"
|
||||
"[reference][target]\n[target]: <target%20file.md#heading> 'title'\n",
|
||||
)
|
||||
|
||||
diagnostics, _, link_count = self.check()
|
||||
|
||||
self.assertEqual([], diagnostics)
|
||||
self.assertEqual(2, link_count)
|
||||
|
||||
def test_external_links_never_open_a_socket(self) -> None:
|
||||
self.write("README.md", "[web](https://example.invalid) [mail](mailto:a@example.invalid)\n")
|
||||
|
||||
with mock.patch.object(socket, "socket", side_effect=AssertionError("network access")):
|
||||
diagnostics, _, link_count = self.check()
|
||||
|
||||
self.assertEqual([], diagnostics)
|
||||
self.assertEqual(2, link_count)
|
||||
|
||||
def test_link_cannot_escape_explicit_root(self) -> None:
|
||||
outside = self.root.parent / "outside-check-docs-links.md"
|
||||
outside.write_text("", encoding="utf-8")
|
||||
self.addCleanup(outside.unlink)
|
||||
self.write("docs/source.md", "[outside](../../outside-check-docs-links.md)\n")
|
||||
|
||||
diagnostics, _, _ = self.check()
|
||||
|
||||
self.assertEqual(1, len(diagnostics))
|
||||
self.assertIn("outside root", diagnostics[0].reason)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Add table
Add a link
Reference in a new issue