docs: document scaffold status and make local doc checks reproducible

This commit is contained in:
shira committed 2026-10-05 21:03:19 +03:00
1 parent 70f96adf26
commit 0f206bfc29
7 files changed
+214 -7

No files matched your search

+57 -3
View File
@@ -1,11 +1,16 @@
#!/usr/bin/env python3
"""Check project-owned Markdown links, language docs, routes, and imports."""
"""Check project-owned Markdown links, language docs, routes, and imports.
Inside a git work tree, Markdown files that git ignores (for example through
.gitignore or .git/info/exclude) are local material and are not checked.
"""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from pathlib import Path
from urllib.parse import unquote, urlsplit
@@ -45,7 +50,52 @@ HEADING = re.compile(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$")
HTML_ID = re.compile(r"\bid\s*=\s*['\"]([^'\"]+)['\"]", re.IGNORECASE)
class GitIgnoreError(RuntimeError):
"""Raised when git reports a work tree but cannot evaluate ignore rules."""
def inside_git_work_tree(root: Path) -> bool:
"""Return True only when git is available and root belongs to a work tree."""
try:
result = subprocess.run(
["git", "-C", str(root), "rev-parse", "--is-inside-work-tree"],
capture_output=True,
check=False,
)
except OSError:
return False
return result.returncode == 0 and result.stdout.strip() == b"true"
def git_ignored(root: Path, paths: list[Path]) -> set[Path]:
"""Return the paths that git ignores, using one check-ignore call.
Tracked files are never reported because check-ignore runs without
--no-index, so only local files that git would not track are skipped.
"""
if not paths or not inside_git_work_tree(root):
return set()
by_name = {path.relative_to(root).as_posix(): path for path in paths}
payload = b"".join(os.fsencode(name) + b"\0" for name in by_name)
try:
result = subprocess.run(
["git", "check-ignore", "--stdin", "-z"],
cwd=root,
input=payload,
capture_output=True,
check=False,
)
except OSError as error:
raise GitIgnoreError(f"git check-ignore could not run: {error}") from error
# Exit status 1 means that no path is ignored; anything else is a failure.
if result.returncode not in (0, 1):
message = result.stderr.decode("utf-8", errors="replace").strip()
raise GitIgnoreError(f"git check-ignore failed with status {result.returncode}: {message}")
return {by_name[os.fsdecode(name)] for name in result.stdout.split(b"\0") if name}
def markdown_files(root: Path) -> list[Path]:
root = root.resolve()
found: list[Path] = []
for current, directories, filenames in os.walk(root):
directories[:] = sorted(
@@ -57,7 +107,8 @@ def markdown_files(root: Path) -> list[Path]:
path = Path(current) / filename
if path.suffix.lower() == ".md" and not path.is_symlink():
found.append(path.resolve())
return sorted(found)
ignored = git_ignored(root, found)
return sorted(path for path in found if path not in ignored)
def visible_lines(markdown: str) -> list[tuple[int, str]]:
@@ -294,7 +345,10 @@ def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
args = parser.parse_args()
errors = validate_repository(args.root)
try:
errors = validate_repository(args.root)
except GitIgnoreError as error:
errors = [str(error)]
if errors:
for error in errors:
print(f"ERROR: {error}", file=sys.stderr)
+66 -1
View File
@@ -1,9 +1,13 @@
from __future__ import annotations
import importlib.util
import os
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest import mock
MODULE_PATH = Path(__file__).with_name("docs-check.py")
@@ -13,7 +17,9 @@ DOCS_CHECK = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(DOCS_CHECK)
class DocsCheckTests(unittest.TestCase):
class RepositoryTestCase(unittest.TestCase):
"""Create a minimal valid repository layout in a temporary directory."""
def setUp(self) -> None:
self.temporary = tempfile.TemporaryDirectory()
self.root = Path(self.temporary.name)
@@ -40,6 +46,8 @@ class DocsCheckTests(unittest.TestCase):
path.write_text(content, encoding="utf-8")
return path
class DocsCheckTests(RepositoryTestCase):
def test_accepts_angle_bracket_path_with_spaces(self) -> None:
self.write("README.md", "# Root\n\n[Guide](<guides/guide with spaces.md>)\n")
self.write("guides/guide with spaces.md", "# Guide\n")
@@ -119,5 +127,62 @@ class DocsCheckTests(unittest.TestCase):
self.assertTrue(any("instruction import cycle" in error for error in errors), errors)
@unittest.skipUnless(shutil.which("git"), "git is required for ignore-rule tests")
class DocsCheckGitIgnoreTests(RepositoryTestCase):
LOCAL_README = "docs/other/notes/README.md"
def setUp(self) -> None:
super().setUp()
# Isolate git from user and system configuration and from any parent repository.
environment = mock.patch.dict(
os.environ,
{
"GIT_CONFIG_GLOBAL": os.devnull,
"GIT_CONFIG_NOSYSTEM": "1",
"GIT_CEILING_DIRECTORIES": str(self.root.resolve().parent),
},
)
environment.start()
self.addCleanup(environment.stop)
self.write(self.LOCAL_README, "[Missing](missing.md)\n")
def git(self, *arguments: str) -> None:
subprocess.run(["git", *arguments], cwd=self.root, check=True, capture_output=True)
def local_errors(self) -> list[str]:
errors = DOCS_CHECK.validate_repository(self.root)
return [error for error in errors if self.LOCAL_README in error]
def test_skips_markdown_excluded_through_info_exclude(self) -> None:
self.git("init", "--quiet")
with (self.root / ".git" / "info" / "exclude").open("a", encoding="utf-8") as exclude:
exclude.write("/docs/other/\n")
self.assertEqual([], DOCS_CHECK.validate_repository(self.root))
def test_skips_markdown_ignored_through_gitignore(self) -> None:
self.git("init", "--quiet")
self.write(".gitignore", "/docs/other/\n")
self.assertEqual([], DOCS_CHECK.validate_repository(self.root))
def test_reports_untracked_markdown_that_is_not_ignored(self) -> None:
self.git("init", "--quiet")
errors = self.local_errors()
self.assertTrue(any("broken local link" in error for error in errors), errors)
self.assertTrue(any("README is below a top-level directory" in error for error in errors), errors)
def test_reports_tracked_markdown_that_matches_ignore_rules(self) -> None:
self.git("init", "--quiet")
self.write(".gitignore", "/docs/other/\n")
self.git("add", "--force", self.LOCAL_README)
errors = self.local_errors()
self.assertTrue(any("broken local link" in error for error in errors), errors)
def test_reports_markdown_outside_git_work_tree(self) -> None:
self.write(".gitignore", "/docs/other/\n")
errors = self.local_errors()
self.assertTrue(any("broken local link" in error for error in errors), errors)
self.assertTrue(any("README is below a top-level directory" in error for error in errors), errors)
if __name__ == "__main__":
unittest.main()
+3 -1
View File
@@ -23,7 +23,9 @@ class MergeSchemasTest(unittest.TestCase):
def setUp(self) -> None:
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.contract_root = Path(self.temporary.name) / "api"
# merge_contract returns resolved paths; resolve the temporary root too because it
# may sit behind a symlink (for example /var -> /private/var on macOS).
self.contract_root = Path(self.temporary.name).resolve() / "api"
(self.contract_root / "components" / "schemas").mkdir(parents=True)
(self.contract_root / "routes").mkdir()