"""Reading repository files without following a symlink out of the tree.""" from __future__ import annotations import os from pathlib import Path def inside(root: Path, path: Path) -> bool: """True when path's real location is root's real location or below it.""" real_root = os.path.realpath(root) real = os.path.realpath(path) return os.path.commonpath([real_root, real]) == real_root def read_in_tree(root: Path, rel: str) -> str | None: """The text of root/rel, or None when it is a symlink, not a regular file, or resolves outside root (a symlinked parent directory included).""" path = root / rel if path.is_symlink() or not path.is_file() or not inside(root, path): return None return path.read_text(encoding="utf-8", errors="replace")