Coverage for packages/workshop/src/livery/workshop/_regions.py: 100%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop, packages/extensions/ty, packages/extensions/ruff, packages/extensions/python, packages/extensions/pytest, packages/extensions/pyrefly, packages/extensions/nanobind, packages/extensions/mypy, packages/extensions/mkdocstrings, packages/extensions/lfs, packages/extensions/docs, packages/extensions/cpp, packages/extensions/coverage, packages/extensions/conan, packages/extensions/cmake, packages/extensions/claude, packages/extensions/clang-tidy, packages/extensions/clang-format, packages/extensions/changelog, packages/extensions/basedpyright ran.

1"""The content a repository owns inside its managed files.
2
3A managed file is rendered whole and judged byte for byte, and a
4repository still needs lines of its own in some of them: its own
5rules in the root ``.gitignore``, its own tables in ``pyproject.toml``,
6its own tasks below the mount in ``tasks.py``. A region carries them.
7
8A **region** is a pair of marker comments the template renders, with
9the repository's lines between them. The fragment engine reads each
10region from the committed file and writes it back in place, so a sync
11preserves it by construction and the drift gate still compares whole
12bytes: an edit
13inside a region is the repository's, an edit outside it is drift,
14and a removed marker is drift too. A file without the region yet
15gains the markers, empty, on the next apply.
16
17The markers are one shape in every comment style, so a reader who
18has seen one has seen them all::
19
20 # -- workshop: region tables, yours to edit; the render keeps it --
21 # -- workshop: end tables --
22"""
23
24from __future__ import annotations
25
26import re
27from dataclasses import dataclass
28from pathlib import Path
29
30#: The marker lines, formatted with the file's comment leader and the
31#: region's name. A template writes them verbatim, so the parser and
32#: the template agree by this one spelling.
33OPEN = "{leader} -- workshop: region {name}, yours to edit; the render keeps it --"
34CLOSE = "{leader} -- workshop: end {name} --"
35
36_OPEN = re.compile(r"^\s*(?:#|//)\s*-- workshop: region ([A-Za-z0-9_-]+), .*--\s*$")
37_CLOSE = re.compile(r"^\s*(?:#|//)\s*-- workshop: end ([A-Za-z0-9_-]+) --\s*$")
38
39
40@dataclass(frozen=True)
41class Region:
42 """One region as a committed file carries it.
43
44 Attributes:
45 name: The region's name, as its markers spell it.
46 content: The lines between the markers, newline-terminated
47 when there are any, empty otherwise.
48 first: The line number of the opening marker, one-based.
49 last: The line number of the closing marker, one-based.
50 """
51
52 name: str
53 content: str
54 first: int
55 last: int
56
57
58def regions_in(text: str) -> tuple[Region, ...]:
59 """Every region *text* carries, in file order.
60
61 A marker without its partner is not a region: the drift gate
62 reports the file, since the markers are rendered bytes.
63 """
64 found: list[Region] = []
65 lines = text.split("\n")
66 open_name = ""
67 start = 0
68 body: list[str] = []
69 for number, line in enumerate(lines, start=1):
70 opened = _OPEN.match(line)
71 closed = _CLOSE.match(line)
72 if opened and not open_name:
73 open_name, start, body = opened.group(1), number, []
74 continue
75 if closed and open_name and closed.group(1) == open_name:
76 content = "".join(f"{item}\n" for item in body)
77 found.append(Region(open_name, content, start, number))
78 open_name = ""
79 continue
80 if open_name:
81 body.append(line)
82 return tuple(found)
83
84
85def region_names(text: str) -> tuple[str, ...]:
86 """The names the markers in *text* open, whether or not they close."""
87 return tuple(
88 m.group(1) for m in (_OPEN.match(line) for line in text.split("\n")) if m
89 )
90
91
92def contents(path: Path) -> dict[str, str]:
93 """The committed file's regions, name to content; empty when the file is absent."""
94 if not path.is_file():
95 return {}
96 text = path.read_text(encoding="utf-8")
97 return {region.name: region.content for region in regions_in(text)}
98
99
100def unmatched(text: str) -> tuple[str, ...]:
101 """The names whose markers do not pair up in *text*."""
102 paired = {region.name for region in regions_in(text)}
103 opened = set(region_names(text))
104 closed = {
105 m.group(1) for m in (_CLOSE.match(line) for line in text.split("\n")) if m
106 }
107 return tuple(sorted((opened | closed) - paired))
108
109
110def marker_lines(leader: str, name: str) -> tuple[str, str]:
111 """The opening and closing marker for *name* under *leader*."""
112 return OPEN.format(leader=leader, name=name), CLOSE.format(leader=leader, name=name)