"""Fail when code a reader sees in rendered documentation is too wide. The libtmux ports share this checker through the ``check-example-width`` action of libtmux/.github, and it enforces the example rules in WRITING.md. Configuration lives in ``.github/example-width.toml``:: width = 80 tab_width = 4 markdown = ["**/*.md"] sources = ["examples/**/*.rs"] doc_comments = ["src/**/*.rs"] shared_digest = "" allow_ceiling = 1 [[exclude]] glob = "docs/decisions/**" reason = "dated decision records, not reader-facing examples" [[formatter_copies]] copy = "examples/rustfmt.toml" root = "rustfmt.toml" key = "max_width" [[allow]] path = "README.md" line = "the exact line, as it appears in the file" reason = "why breaking it would make the example worse" It checks code in ``markdown`` files (fences, indented blocks outside lists and ``
`` blocks; literal and ``code-block`` blocks in a
``.rst`` one), every line of ``sources`` files, and the code inside doc
comments of ``doc_comments`` files: fences, ``>>>`` doctests, and reST
literal blocks in Python docstrings. Output is not checked: fences
tagged ``text`` and the lines a ``console`` block prints. An untagged
Markdown fence is code, and a ``text`` fence that opens with a ``$ `` or
``PS> `` prompt is a console session. A line that is only a URL (after an
optional comment, list or quote marker) and a hidden line (a rustdoc
``# `` line, a doctest marked ``# doctest: +HIDE``) are skipped. Wide
characters count as two columns; a tab advances to the next multiple of
``tab_width`` (default 4).

``width`` must be 80, the shared rule. Every key must be known, at the
top level and inside each ``[[...]]`` entry, so a key written below a
table header cannot be swallowed by that entry; every entry must hold
the keys the check reads, and every value must have the type it reads.
Every glob must match a tracked file and every exclusion a checked one;
every exclusion and allow entry must give a reason, and every allow entry
must match a line. Every tracked file under a directory named
``examples`` must be checked or excluded, so a new example file cannot go
unread.
``allow_ceiling`` must equal the number of allow entries, so the list
grows only through a reviewed change to that number and a fixed line must
lower it. Each formatter copy must equal its root file except for the
lines naming ``key``, and the digest of WRITING.md's shared section must
equal ``shared_digest``, which is required, so a local edit to that section
fails until every port changes together. AGENTS.md must hold a Markdown
link that resolves to this WRITING.md and the heading the shared section
sits under, so an agent is routed to the rules, and WRITING.md's
``### In this repository`` block must hold the four labelled bullets in
order, then one Bad and one Good example.

``--digest`` prints the SHA-256 of WRITING.md's shared example section
(between ```` and ````), so a
job that reads every port can confirm they still agree. The tests under
``tests/`` plant failures and clean controls to prove the checker can fail.
"""

from __future__ import annotations

import argparse
import dataclasses
import hashlib
import json
import os
import pathlib
import re
import subprocess
import sys
import typing as t
import unicodedata

# tomllib is in the standard library from 3.11, and the hosted runners the
# action targets ship 3.12.
if sys.version_info < (3, 11):
    sys.exit("check_example_width.py needs Python 3.11 or newer")

import tomllib

CONFIG = pathlib.PurePosixPath(".github/example-width.toml")
KEYS = frozenset(
    {
        "width",
        "tab_width",
        "markdown",
        "sources",
        "doc_comments",
        "exclude",
        "allow",
        "allow_ceiling",
        "formatter_copies",
        "shared_digest",
    }
)
# Keys each [[table]] entry holds.
TABLE_KEYS = {
    "exclude": frozenset({"glob", "reason"}),
    "allow": frozenset({"path", "line", "reason"}),
    "formatter_copies": frozenset({"copy", "root", "key"}),
}
GLOB_KEYS = ("markdown", "sources", "doc_comments")
# The reason the printed allow entry carries until someone writes a real one.
PLACEHOLDER = "why breaking this line would make the example worse"
# The type each top-level value must have; a TOML string where a list belongs
# would otherwise be read one character at a time.
VALUE_TYPES: dict[str, tuple[type, str]] = {
    "width": (int, "an integer"),
    "tab_width": (int, "an integer"),
    "allow_ceiling": (int, "an integer"),
    "shared_digest": (str, "a string"),
}
CODE_DIRECTIVES = frozenset({"code-block", "code", "code-cell", "sourcecode"})
# gp-libs hides a doctest line carrying this directive from the rendered page.
HIDDEN = re.compile(r"^\s*(?:>>>|\.\.\.) .*# doctest: \+HIDE\b")
OUTPUT_TAGS = frozenset({"text"})
# Fences that mix prompted commands with the output they print.
SESSION_TAGS = frozenset({"console", "shell-session", "pycon"})
# A Python fence that opens with a doctest prompt is a session too.
PYTHON_TAGS = frozenset({"python", "py", "python3"})
PROMPTS = ("$ ", "PS> ", ">>> ", "... ")
# A reST line that opens an indented code block: a paragraph ending in
# ``::`` or a code directive. Other directives, such as toctree, hold no code.
REST_BLOCK = re.compile(
    r"^\s*(?!\.\. )\S.*::\s*$|^\s*\.\. (code-block|code|sourcecode)::"
)
FENCE = re.compile(r"^(?P\s*)(?P`{3,}|~{3,})\s*(?P[^`]*)$")
RUSTDOC_TAGS = frozenset({"rust", "no_run", "ignore", "should_panic", "compile_fail"})
SHARED = re.compile(
    r"\n(?P.*?)", re.DOTALL
)
DOC_LINE = re.compile(r"^\s*(?:///|//!|\*(?!/)|#'|--- ?)\s?")
BLOCK_OPEN = re.compile(r"
\s*\{@code|\s*$")
BLOCK_CLOSE = re.compile(r"\}\s*
|^\s*") URL = re.compile(r"^(?:(?:#+|//+!?|-+|\*|>|")]) headings = [m[2] for m in HEADING.finditer(above) if len(m[1]) <= MAX_HEADING_LEVEL] if not headings: where = writing.relative_to(root).as_posix() return [f"{where}: no heading above the shared section"] anchor = slug(headings[-1]) agents = root / "AGENTS.md" links = LINK.findall(agents.read_text(encoding="utf-8")) if agents.is_file() else [] for target in links: path, _, fragment = target.partition("#") if fragment == anchor and (root / path).resolve() == writing.resolve(): return [] where = f"{writing.relative_to(root).as_posix()}#{anchor}" link = f"[{headings[-1]}]({where})" return [ ( f"AGENTS.md: no link to {where}, the section with the example rules; " f"add one such as {link}" ) ] def port_block_problems(text: str) -> list[str]: r"""Return how a WRITING.md's ``### In this repository`` block strays. >>> labels = "\n".join(label + " x" for label in PORT_LABELS) >>> block = f"### In this repository\n\n{labels}\n\nBad, over 80:\n\nGood, named:\n" >>> port_block_problems(block) [] >>> port_block_problems(block.replace("- **Not formatted:**", "- **Other:**")) ['In this repository: no "- **Not formatted:**" bullet in its place'] >>> port_block_problems("## Examples\n") ['no "### In this repository" block'] """ match = PORT_BLOCK.search(unfenced(text)) if match is None: return ['no "### In this repository" block'] lines = match["body"].splitlines() problems = [] at = 0 for label in PORT_LABELS: found = next((i for i, line in enumerate(lines) if line.startswith(label)), -1) if found < at: problems.append(f'In this repository: no "{label}" bullet in its place') else: at = found for example in ("Bad, over 80", "Good"): count = sum(line.startswith(example) for line in lines[at:]) if count != 1: problems.append(f'In this repository: {count} "{example}" examples, want 1') return problems def shared_digest(root: pathlib.Path) -> str: """Return the SHA-256 of WRITING.md's shared section, or ``missing``. The digest covers the text between the markers in WRITING.md. """ writing = writing_path(root) if writing is not None: match = SHARED.search(writing.read_text(encoding="utf-8")) if match: return hashlib.sha256(match["body"].encode()).hexdigest() return "missing" def digest_problems(root: pathlib.Path, config: dict[str, t.Any]) -> list[str]: """Return a problem when the shared section differs from its recorded digest. The message names the file that changed. The section is the same in every port, so an intended change goes to all of them; an edit meant for one repository is undone instead. """ if "shared_digest" not in config: return [ ( f"{CONFIG}: shared_digest is missing; run this checker with " "--digest and set shared_digest to the value it prints" ) ] actual = shared_digest(root) if actual == config["shared_digest"]: return [] writing = writing_path(root) shared = writing.relative_to(root).as_posix() if writing else "WRITING.md" return [ ( f"{shared}: the shared section has digest {actual[:12]}, but " f"shared_digest in {CONFIG} records {config['shared_digest'][:12]}. If " "the edit was meant for this repository only, restore the text between " f"the shared markers, copied from `git show HEAD:{shared}` so " "port-block edits stay. Every libtmux port carries the same text: to " "change it, change it in each repository's WRITING.md, run this " "checker with --digest in each, and set shared_digest in that " "repository's config to the value it prints" ) ] def main(argv: list[str] | None = None) -> int: """Check the repository, or print the shared section's digest.""" parser = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0]) parser.add_argument( "--digest", action="store_true", help="print the digest of the shared WRITING.md section", ) parser.add_argument( "--root", type=pathlib.Path, help="repository root (default: git toplevel)" ) args = parser.parse_args(argv) root = args.root or pathlib.Path( subprocess.run( ["git", "rev-parse", "--show-toplevel"], check=True, capture_output=True, text=True, ).stdout.strip() ) if args.digest: print(f"shared {shared_digest(root)}") return 0 try: config = tomllib.loads((root / CONFIG).read_text(encoding="utf-8")) except (OSError, tomllib.TOMLDecodeError) as error: print(f"{CONFIG}: cannot read the config: {error}") print("1 setup problem; fix the config first.") return 1 wrong = type_problems(config) if wrong: for problem in wrong: print(f"{CONFIG}: {problem}") print(f"{plural(len(wrong), 'setup problem')}; fix the config first.") return 1 files = tracked_files(root) writing = writing_path(root) # Each problem names the file to change; routing problems name their own. setup = config_problems(config, files) problems = ( [f"{CONFIG}: {problem}" for problem in setup] + copy_problems(root, config) + digest_problems(root, config) + routing_problems(root) ) new = untracked_matches(config, tracked_files(root, others=True)) more = ", ..." if len(new) > NOTICE_FILES else "" notice = ( f"Not checked until `git add`: {plural(len(new), 'untracked file')} " f"the config selects ({', '.join(new[:NOTICE_FILES])}{more})." if new else "" ) # An untracked file does not fail the run, but its wide lines are shown # so a new example can be fixed before it is added. pending, _ = check(root, config, new) if new and not setup else ([], []) if pending: they = "it fails" if len(new) == 1 else "they fail" notice += f" Once added, {they} on {plural(len(pending), 'wide line')}: " + ( "; ".join(str(finding) for finding in pending[:3]) ) if writing: where = writing.relative_to(root).as_posix() text = writing.read_text(encoding="utf-8") problems += [f"{where}: {problem}" for problem in port_block_problems(text)] # A config problem such as a misspelled glob key would make allow entries # look stale, so the width pass waits until the config is right. findings, stale = check(root, config, files) if not setup else ([], []) annotate = os.environ.get("GITHUB_ACTIONS") == "true" for problem in problems: print(problem) for finding in findings: print(finding) if annotate: print( f"::error file={finding.path},line={finding.number}::" f"{finding.columns} columns > {finding.width}" ) for entry in stale: print( f"{CONFIG}: allow entry for {entry['path']} matches no line: " f"{entry['line']!r}" ) if problems or findings or stale: rules = writing.relative_to(root).as_posix() if writing else "WRITING.md" print( f"{plural(len(problems), 'setup problem')}, " f"{plural(len(findings), 'wide line')}, " f"{plural(len(stale), 'stale allow entry', 'stale allow entries')}." ) if setup: print(f"The width check runs once the problems in {CONFIG} are fixed.") if findings: print( "Fix a wide line by changing the code, not the line breaks: " f"{rules}#reaching-80. If no change keeps the example clear, " f"add the line to [[allow]] in {CONFIG} with a reason and raise " "allow_ceiling. " + ( f"The first of {len(findings)}, as an entry:" if len(findings) > 1 else "As an entry:" ) ) print(allow_hint(findings[0])) if stale: print( f"Delete each stale allow entry in {CONFIG} and lower " f"allow_ceiling to {len(config.get('allow', [])) - len(stale)}." ) if notice: print(notice) return 1 read = [g for key in GLOB_KEYS for g in config.get(key, [])] skip = [entry["glob"] for entry in entries(config, "exclude")] count = sum(matches(path, read) and not matches(path, skip) for path in files) print(f"{count} files checked; no example is over {config.get('width', 80)}.") if notice: print(notice) return 0 if __name__ == "__main__": sys.exit(main())