"""Paths and names a document mentions, resolved relative to the document.""" from __future__ import annotations import posixpath import re from dataclasses import dataclass # Each directory alternative is fixed by its first two characters (./ or ../, else an # optional dot then a word character), so a run of ../ matches only one way and cannot # backtrack exponentially. The optional dot keeps .gitea/ and .github/ directories. _PATH_TOKEN = re.compile( r"(? str | None: """Normalize a path relative to a directory; None if it leaves the repository.""" resolved = posixpath.normpath(posixpath.join(doc_dir, token)) return None if resolved == ".." or resolved.startswith("../") else resolved def _resolve_both(token: str, doc_dir: str) -> set[str]: """The token as written and resolved against doc_dir, where each stays inside.""" out = set() for base in ("", doc_dir): resolved = _resolve(token, base) if resolved is not None: out.add(resolved) return out def doc_mentions(text: str, doc_path: str) -> Mentions: """What the document refers to. Each path token counts as written (when it stays inside the repository) and as resolved against the document's own directory. Directory tokens (a trailing slash, in backticks or a link target) resolve the same way, without the slash; one that resolves to the repository root is dropped. Names count only in backticks or followed by an opening parenthesis. """ doc_dir = posixpath.dirname(doc_path) paths: set[str] = set() for token in _PATH_TOKEN.findall(text): paths |= _resolve_both(token, doc_dir) dirs: set[str] = set() for code, link in _DIR_TOKEN.findall(text): dirs |= _resolve_both(code or link, doc_dir) dirs.discard(".") names = set(_BACKTICK_NAME.findall(text)) | set(_CALL_NAME.findall(text)) return Mentions( paths=frozenset(paths), basenames=frozenset(posixpath.basename(p) for p in paths), names=frozenset(names), dirs=frozenset(dirs), )