transcript.md 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. transcript/__init__.py +35 -0
  2. transcript/_rule/__init__.py +0 -0
  3. transcript/_rule/archive.py +128 -0
  4. transcript/_rule/conda.py +52 -0
  5. transcript/_rule/container.py +290 -0
  6. transcript/_rule/core.py +524 -0
  7. transcript/_rule/lambdas.py +120 -0
  8. transcript/_rule/registry.py +54 -0
  9. transcript/_rule/serialize.py +26 -0
  10. transcript/_rule/snakefile.py +81 -0
  11. transcript/_rule/wildcards.py +110 -0
  12. transcript/cli.py +363 -0
  13. transcript/document.py +56 -0
  14. transcript/execute.py +240 -0
  15. transcript/html/__init__.py +17 -0
  16. transcript/html/_assets/.frontend.sha256 +1 -0
  17. transcript/html/_assets/__init__.py +21 -0
  18. transcript/html/_assets/style.min.css +1 -0
  19. transcript/html/_assets/transcript.min.js +21 -0
  20. transcript/html/_island.py +72 -0
  21. transcript/html/_navigate.py +198 -0
  22. transcript/html/_output.py +100 -0
  23. transcript/html/_resources.py +171 -0
  24. transcript/html/_review.py +34 -0
  25. transcript/html/markup.py +26 -0
  26. transcript/html/page.py +107 -0
  27. transcript/output.py +308 -0
  28. transcript/parse.py +256 -0
  29. transcript/renderers/__init__.py +126 -0
  30. transcript/renderers/bitmap.py +166 -0
  31. transcript/renderers/compose.py +174 -0
  32. transcript/renderers/compose_runtime.js +233 -0
  33. transcript/renderers/datavzrd.py +321 -0
  34. transcript/renderers/datavzrd_runtime.js +362 -0
  35. transcript/renderers/label.py +211 -0
  36. transcript/renderers/markdown.py +45 -0
  37. transcript/renderers/table.py +32 -0
  38. transcript/renderers/vegalite.py +250 -0
  39. transcript/review/__init__.py +13 -0
  40. transcript/review/_block.py +167 -0
  41. transcript/review/_migrate.py +212 -0
  42. transcript/review/_records.py +238 -0
  43. transcript/review/_span.py +287 -0
  44. transcript/review/load.py +64 -0
  45. transcript/tmd.py +159 -0
  46. transcript_md-0.1.0.dist-info/METADATA +17 -0
  47. transcript_md-0.1.0.dist-info/RECORD +49 -0
  48. transcript_md-0.1.0.dist-info/WHEEL +4 -0
  49. transcript_md-0.1.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,167 @@
1
+ """Locate and rewrite the trailing ``if "transcript.review":`` block.
2
+
3
+ The marker lives here rather than in :mod:`transcript.parse` so the parser has
4
+ no dependency on the review feature: :func:`transcript.document.parse` asks the
5
+ review package for the block after locating the report regions. The block is
6
+ serialized as JSON (:func:`transcript.review._records.dump`) and escaped for a
7
+ ``\"\"\"`` literal by :func:`transcript.tmd.escape_slot`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ast
13
+ import json
14
+ import warnings
15
+ from collections.abc import Callable, Sequence
16
+ from typing import NamedTuple
17
+
18
+ from ..tmd import body_hash, escape_slot
19
+ from ._migrate import migrate
20
+ from ._records import Record, ReviewIndex
21
+
22
+ REVIEW_MARKER = "transcript.review"
23
+
24
+
25
+ def render_block(records: Sequence[Record], indent: str = " ", hash: str = ""):
26
+ """Render the trailing ``if "transcript.review":`` block for *records*.
27
+
28
+ *hash* is the ``body_hash`` of the body the block follows; when given it is
29
+ carried in the marker (``transcript.review=<hash>``) so a later read can tell
30
+ whether the body still matches. The returned text has no trailing newline;
31
+ callers place it after the body.
32
+ """
33
+ lines = [json.dumps(record.to_dict(), ensure_ascii=False) for record in records]
34
+ if lines:
35
+ body = ",\n".join(indent + escape_slot(line) for line in lines)
36
+ inner = f"[\n{body}\n{indent}]"
37
+ else:
38
+ inner = "[]"
39
+ marker = REVIEW_MARKER if not hash else f"{REVIEW_MARKER}={hash}"
40
+ return f'if "{marker}":\n{indent}"""{inner}"""'
41
+
42
+
43
+ class ReviewBlock(NamedTuple):
44
+ """The trailing ``if "transcript.review":`` block, if the archive has one."""
45
+
46
+ start: int
47
+ end: int
48
+ value: str
49
+ hash: str = ""
50
+ """The ``body_hash`` recorded in the marker, or ``""`` for a legacy block."""
51
+
52
+ @classmethod
53
+ def find(cls, tree: ast.Module, position: Callable[[int, int], int]):
54
+ """Return the trailing review block, or ``None`` when there is none.
55
+
56
+ The marker must be the last top-level statement and its body a single
57
+ string literal holding the records; a block of any other shape is left
58
+ alone as an ordinary ``if`` instead of failing the archive. The marker
59
+ may carry the body hash after ``=``; without it the block is legacy and
60
+ is migrated without verification.
61
+ """
62
+ if not tree.body:
63
+ return None
64
+ node = tree.body[-1]
65
+ if not (
66
+ isinstance(node, ast.If)
67
+ and isinstance(node.test, ast.Constant)
68
+ and isinstance(node.test.value, str)
69
+ and len(node.body) == 1
70
+ ):
71
+ return None
72
+ marker: str = node.test.value
73
+ if marker == REVIEW_MARKER:
74
+ hash = ""
75
+ elif marker.startswith(REVIEW_MARKER + "="):
76
+ hash = marker[len(REVIEW_MARKER) + 1 :]
77
+ else:
78
+ return None
79
+ statement = node.body[0]
80
+ if not (
81
+ isinstance(statement, ast.Expr)
82
+ and isinstance(statement.value, ast.Constant)
83
+ and isinstance(statement.value.value, str)
84
+ ):
85
+ return None
86
+ assert node.end_lineno is not None and node.end_col_offset is not None
87
+ return cls(
88
+ position(node.lineno, node.col_offset),
89
+ position(node.end_lineno, node.end_col_offset),
90
+ statement.value.value,
91
+ hash,
92
+ )
93
+
94
+ def load(self):
95
+ """Parse and validate the block's records into a :class:`ReviewIndex`.
96
+
97
+ A block that cannot be parsed or validated is dropped entirely after a
98
+ warning: a damaged review is never preserved, which would freeze it, and
99
+ the drop is never silent. A whole block is dropped if any record is
100
+ invalid.
101
+ """
102
+ if not self.value.strip():
103
+ return ReviewIndex([])
104
+ try:
105
+ data = json.loads(self.value)
106
+ if not isinstance(data, list):
107
+ raise ValueError("the transcript.review block must hold a JSON array")
108
+ return ReviewIndex(Record.from_dict(item) for item in data)
109
+ except (KeyError, TypeError, ValueError) as error:
110
+ warnings.warn(
111
+ f"dropping invalid transcript.review block: {error}", stacklevel=2
112
+ )
113
+ return ReviewIndex([])
114
+
115
+
116
+ class ReviewSource(NamedTuple):
117
+ """A review block together with the archive body it was recorded against.
118
+
119
+ It is the one value the CLI needs to carry annotations across a re-render:
120
+ *body* is the archive text before the block, *records* its parsed records,
121
+ *hash* the body hash recorded in the marker (``""`` for legacy), and
122
+ *block* the original block text, kept verbatim when nothing moves.
123
+ """
124
+
125
+ body: str
126
+ records: Sequence[Record]
127
+ hash: str = ""
128
+ block: str = ""
129
+
130
+ @classmethod
131
+ def of(cls, review: ReviewBlock, source: str):
132
+ """Build a source from a located block and the archive text it sits in."""
133
+ return cls(
134
+ source[: review.start],
135
+ review.load().records,
136
+ review.hash,
137
+ source[review.start : review.end],
138
+ )
139
+
140
+ @property
141
+ def stale(self):
142
+ """Whether the block no longer matches the body it describes."""
143
+ return bool(self.hash) and body_hash(self.body) != self.hash
144
+
145
+
146
+ def migrated_block(new: str, source: ReviewSource, indent: str = " "):
147
+ """Return the block to append to *new*, migrating *source*'s records.
148
+
149
+ A stale source or an empty record set drops the block (returning ``""``);
150
+ an unchanged body keeps ``source.block`` verbatim; otherwise the records are
151
+ migrated onto *new* and rendered with its hash (an unchanged record set still
152
+ needs the new hash when the body moved).
153
+ """
154
+ if source.stale:
155
+ warnings.warn(
156
+ "dropping transcript.review block: archive body hash mismatch",
157
+ stacklevel=2,
158
+ )
159
+ return ""
160
+ if not source.records:
161
+ return ""
162
+ records = list(migrate(source.records, source.body, new))
163
+ if not records:
164
+ return ""
165
+ if records == source.records and body_hash(new) == source.hash:
166
+ return source.block
167
+ return render_block(records, indent, hash=body_hash(new))
@@ -0,0 +1,212 @@
1
+ """Incremental migration of review records across archive rewrites.
2
+
3
+ Records are immutable facts about a version: a source's ``at`` is a span in
4
+ the version it was created in, and its ``cover`` names the region it came from
5
+ in the *immediately previous* version plus that version's ``before`` boundary. A
6
+ migration therefore never rewrites an old record. A live source whose region
7
+ moved or changed is frozen (``before`` set, its own text kept in ``source``) and
8
+ its new region is appended as live successors, each carrying a ``cover`` back
9
+ into the frozen source. Movement alone is enough to need a successor: without
10
+ one the old coordinates could not be mapped forward.
11
+
12
+ The alignment is character-level: lines are diffed first (cheap and stable for
13
+ whole documents) and every replaced block is refined character by character,
14
+ so ``cover`` can name a part of an old line. Records are cut at new-text
15
+ newlines, one whole line per record, so a single old span expresses the mapping
16
+ exactly.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Sequence
22
+ from dataclasses import replace
23
+ from datetime import datetime
24
+ from difflib import SequenceMatcher
25
+
26
+ from ._records import Record, SourceRecord
27
+ from ._span import At, Span, _line, _starts, timestamp
28
+
29
+ __all__ = ["migrate"]
30
+
31
+
32
+ def _mapped_shift(offset: int, oa: int, ob: int, na: int, nb: int, *, end: bool):
33
+ """Map one offset across a segment, spreading a replacement linearly."""
34
+ if ob == oa:
35
+ return nb if end else na
36
+ if nb == na:
37
+ return na
38
+ if end:
39
+ return na + -((-(offset - oa) * (nb - na)) // (ob - oa))
40
+ return na + ((offset - oa) * (nb - na)) // (ob - oa)
41
+
42
+
43
+ class _Align:
44
+ """The character segments shared by one old/new text pair.
45
+
46
+ A segment is ``(old_start, old_stop, new_start, new_stop, equal)``; exact
47
+ runs carry ``equal`` and the gaps are replacements, insertions or
48
+ deletions, spread linearly when a region boundary falls inside one.
49
+ """
50
+
51
+ def __init__(self, old_text: str, new_text: str):
52
+ self.old_text = old_text
53
+ self.new_text = new_text
54
+ self.old_starts = _starts(old_text)
55
+ self.new_starts = _starts(new_text)
56
+
57
+ segments: list[tuple[int, int, int, int, bool]] = []
58
+ """old_start, old_stop, new_start, new_stop, is_equal"""
59
+ old_previous = new_previous = 0
60
+ for a, b, size in self._matched_blocks():
61
+ if a > old_previous or b > new_previous:
62
+ segments.append((old_previous, a, new_previous, b, False))
63
+ segments.append((a, a + size, b, b + size, True))
64
+ old_previous, new_previous = a + size, b + size
65
+ if old_previous < len(old_text) or new_previous < len(new_text):
66
+ segments.append(
67
+ (old_previous, len(old_text), new_previous, len(new_text), False)
68
+ )
69
+ self.segments = segments
70
+ self.old_segment_starts = [segment[0] for segment in segments]
71
+ self.new_segment_starts = [segment[2] for segment in segments]
72
+
73
+ def _matched_blocks(self):
74
+ """Character ranges that correspond exactly between the two texts."""
75
+ old_lines = self.old_text.splitlines()
76
+ new_lines = self.new_text.splitlines()
77
+ matcher = SequenceMatcher(None, old_lines, new_lines, autojunk=False)
78
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
79
+ oa = self.old_starts[i1]
80
+ ob = self.old_starts[i2]
81
+ na = self.new_starts[j1]
82
+ if tag == "equal":
83
+ yield oa, na, ob - oa
84
+ elif tag == "replace":
85
+ segment_old = self.old_text[oa:ob]
86
+ nb = self.new_starts[j2]
87
+ segment_new = self.new_text[na:nb]
88
+ inner = SequenceMatcher(None, segment_old, segment_new, autojunk=False)
89
+ for a, b, size in inner.get_matching_blocks():
90
+ if size:
91
+ yield oa + a, na + b, size
92
+
93
+ def old_to_new(self, start: int, stop: int):
94
+ """The new extent of an old character range (a point when deleted)."""
95
+ if stop <= start:
96
+ return None
97
+ first = self.segments[_line(start, self.old_segment_starts)]
98
+ begin = _mapped_shift(start, first[0], first[1], first[2], first[3], end=False)
99
+ last = self.segments[_line(stop - 1, self.old_segment_starts)]
100
+ end = _mapped_shift(stop, last[0], last[1], last[2], last[3], end=True)
101
+ return begin, end
102
+
103
+ def new_to_old(self, start: int, stop: int):
104
+ """The old extent a new character range came from, or ``None``."""
105
+ if stop <= start:
106
+ return None
107
+ first = self.segments[_line(start, self.new_segment_starts)]
108
+ begin = _mapped_shift(start, first[2], first[3], first[0], first[1], end=False)
109
+ last = self.segments[_line(stop - 1, self.new_segment_starts)]
110
+ end = _mapped_shift(stop, last[2], last[3], last[0], last[1], end=True)
111
+ return None if end <= begin else (begin, end)
112
+
113
+ def insert(self: _Align, offset: int, stamp: str, old_starts: list[int]):
114
+ """Mark a new line with no old counterpart as born at ``stamp``.
115
+
116
+ ``cover`` names a zero-length point on the old line it was inserted before,
117
+ so ``cover.time`` records when the line first appeared and the chain ends
118
+ there instead of linking it to an unrelated neighbouring line.
119
+ """
120
+ segment = self.segments[_line(offset, self.new_segment_starts)]
121
+ point = _mapped_shift(
122
+ offset, segment[2], segment[3], segment[0], segment[1], end=False
123
+ )
124
+ return At(Span.empty(_line(point, old_starts), 0), stamp)
125
+
126
+ def split(self, new_start: int, new_stop: int):
127
+ """Cut a new character range at newlines, one record per line.
128
+
129
+ Returns ``(new_span, old_span)`` pairs; ``old_span`` is ``None`` for an
130
+ inserted line.
131
+ """
132
+ if new_stop <= new_start:
133
+ return
134
+ first = _line(new_start, self.new_starts)
135
+ last = _line(new_stop - 1, self.new_starts)
136
+ for line in range(first, last + 1):
137
+ old_span = self.new_to_old(self.new_starts[line], self.new_starts[line + 1])
138
+ if old_span is not None:
139
+ old_span = Span.from_bound(*old_span, self.old_starts)
140
+ yield Span(line, 0, line + 1, 0), old_span
141
+
142
+
143
+ def migrate(
144
+ records: Sequence[Record],
145
+ old_text: str,
146
+ new_text: str,
147
+ *,
148
+ moment: datetime | None = None,
149
+ ):
150
+ """Update *records* for a body that changed from *old_text* to *new_text*.
151
+
152
+ Old records are never rewritten. A live source the change leaves alone is
153
+ kept; otherwise it is frozen at the migration moment and its new region is
154
+ appended as live successors linked back through ``cover``.
155
+ Reviews keep the coordinates of the version they were written in.
156
+ """
157
+ if not records:
158
+ return
159
+ if old_text == new_text:
160
+ yield from records
161
+ return
162
+
163
+ stamp = timestamp(moment)
164
+ align = _Align(old_text, new_text)
165
+ old_starts = align.old_starts
166
+ new_starts = align.new_starts
167
+ seen: set[int] = set()
168
+ for record in records:
169
+ if not isinstance(record, SourceRecord) or record.before is not None:
170
+ yield record
171
+ continue
172
+ span = Span.parse(record.at)
173
+ start, stop = span.bound(old_starts)
174
+ old_segment = old_text[start:stop]
175
+ extent = align.old_to_new(start, stop)
176
+ if extent == (start, stop) and new_text[start:stop] == old_segment:
177
+ lines = set(span.lines())
178
+ if lines & seen:
179
+ continue # a duplicate of an earlier live source
180
+ seen |= lines
181
+ yield record
182
+ continue
183
+ yield replace(record, before=stamp, source=old_segment)
184
+ if extent is None:
185
+ continue
186
+ new_start, new_stop = extent
187
+ if new_stop <= new_start:
188
+ # Fully deleted: keep a live zero-length successor at the point so
189
+ # the chain can still be followed to where the region stood.
190
+ at = Span.from_bound(new_start, new_start, new_starts)
191
+ old = Span.from_bound(start, stop, old_starts)
192
+ yield SourceRecord(at=str(at), cover=At(old, stamp))
193
+ continue
194
+ for new_span, old_span in align.split(new_start, new_stop):
195
+ if new_span.start_line in seen:
196
+ continue # another live source already owns this line
197
+ seen.add(new_span.start_line)
198
+ cover = (
199
+ At(old_span, stamp)
200
+ if old_span is not None
201
+ else align.insert(new_starts[new_span.start_line], stamp, old_starts)
202
+ )
203
+ yield SourceRecord(at=str(new_span), cover=cover)
204
+ for line in range(len(new_starts) - 1):
205
+ if line in seen:
206
+ continue
207
+ if align.new_to_old(new_starts[line], new_starts[line + 1]) is not None:
208
+ continue # the line came from the old text
209
+ yield SourceRecord(
210
+ at=str(Span(line, 0, line + 1, 0)),
211
+ cover=align.insert(new_starts[line], stamp, old_starts),
212
+ )
@@ -0,0 +1,238 @@
1
+ """The ``transcript.review`` record model: schema, lookup, and serialization.
2
+
3
+ An archive may end with a plain-Python review block: an ``if
4
+ "transcript.review":`` whose body is a single triple-quoted JSON array. The
5
+ block is an ordinary ``if`` whose body is one JSON string, so it stays valid
6
+ Python with no dependencies and is ignored when the document runs.
7
+
8
+ Records are objects: :class:`SourceRecord` versions a run of lines (``at``) and
9
+ points back to the region it replaced (``cover``);
10
+ :class:`ReviewRecord` carries a range plus the time its comment was written.
11
+ Records are immutable: each names coordinates in the version it was made for,
12
+ and the ``cover`` pointers form a chain the history view walks. A review's
13
+ ``coveredAt`` entries are derived from its ``time`` and the sources
14
+ (:meth:`ReviewIndex.covered_at`) and refreshed on every load.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Iterable
20
+ from dataclasses import dataclass, fields
21
+ from datetime import datetime
22
+ from typing import ClassVar
23
+
24
+ from ._span import TYPE_REVIEW, TYPE_SOURCE, At, Span, parse_time
25
+
26
+ __all__ = ["Record", "ReviewIndex", "ReviewRecord", "SourceRecord"]
27
+
28
+
29
+ @dataclass
30
+ class Record:
31
+ """Base class for the flat records in the review block.
32
+
33
+ Subclasses are dataclasses. :meth:`to_dict` emits the JSON object, skipping
34
+ unset fields, and :meth:`from_dict` rebuilds the right subclass from JSON.
35
+ """
36
+
37
+ TYPE: ClassVar[str]
38
+ at: str
39
+
40
+ def to_dict(self):
41
+ """Return the JSON object for this record, dropping unset fields."""
42
+ data: dict = {"type": self.TYPE}
43
+ for item in fields(self):
44
+ key = item.name
45
+ value = getattr(self, key)
46
+ if value is not None:
47
+ data[key] = value
48
+ return data
49
+
50
+ def validate(self):
51
+ """Raise :class:`ValueError` when the record violates its invariants."""
52
+
53
+ @classmethod
54
+ def from_dict(cls, data: dict):
55
+ """Rebuild a record from its JSON object, rejecting unknown fields."""
56
+ if not isinstance(data, dict):
57
+ raise ValueError(f"a review record must be a JSON object: {data!r}")
58
+ kind: str = data["type"]
59
+ if kind == TYPE_SOURCE:
60
+ target = SourceRecord
61
+ elif kind == TYPE_REVIEW:
62
+ target = ReviewRecord
63
+ else:
64
+ raise ValueError(f"unknown review record type: {kind!r}")
65
+ kwargs = {}
66
+ for item in fields(target):
67
+ key = item.name
68
+ if key in data:
69
+ kwargs[key] = data[key]
70
+ if data.keys() - kwargs.keys() - {"type"}:
71
+ raise ValueError(f"unknown fields in review record: {data!r}")
72
+ return target._from_dict(kwargs)
73
+
74
+
75
+ @dataclass
76
+ class SourceRecord(Record):
77
+ """One whole source line (``at``) and the region it replaced.
78
+
79
+ ``at`` always is span of complete line(s).
80
+ ``source`` is the superseded content of the record.
81
+ ``cover`` is ``"span@stamp"`` for the region in the *immediately previous*
82
+ version that this line corresponds to, or ``None`` for the first version.
83
+ The stamp is that previous version's ``before`` boundary.
84
+
85
+ Cutting a migration at new-text newlines keeps every record line-sized,
86
+ so one old span expresses the line-to-line mapping exactly.
87
+ """
88
+
89
+ TYPE: ClassVar[str] = TYPE_SOURCE
90
+
91
+ source: str | None = None
92
+ cover: At | None = None
93
+ before: str | None = None
94
+
95
+ def validate(self):
96
+ Span.parse(self.at)
97
+ if self.cover is not None:
98
+ if not isinstance(self.cover, At):
99
+ raise ValueError("cover must be an At")
100
+ self.cover.validate()
101
+ if self.before is not None:
102
+ parse_time(self.before)
103
+ if not isinstance(self.source, str):
104
+ raise ValueError("a superseded source must carry its source")
105
+
106
+ def to_dict(self):
107
+ data = super().to_dict()
108
+ if self.cover is not None:
109
+ data["cover"] = str(self.cover)
110
+ return data
111
+
112
+ @classmethod
113
+ def _from_dict(cls, data: dict):
114
+ if "cover" in data:
115
+ data["cover"] = At.parse(data["cover"])
116
+ return cls(**data)
117
+
118
+
119
+ def _before(source: SourceRecord):
120
+ """Sort key placing a live source (no ``before``) after superseded ones.
121
+ old first, live the last.
122
+ """
123
+ return (source.before is None, source.before or "")
124
+
125
+
126
+ @dataclass
127
+ class ReviewRecord(Record):
128
+ """A range plus the time its comment was last edited."""
129
+
130
+ TYPE: ClassVar[str] = TYPE_REVIEW
131
+
132
+ time: str
133
+ edit: str | None = None
134
+ comment: str | None = None
135
+ coveredAt: list[At] | None = None
136
+ """Derived on load from ``time`` and the sources, then serialized:
137
+ ``"span@stamp"`` for each range of ``at`` superseded by a later version.
138
+ It is refreshed whenever written into the ``.tmd.py``,
139
+ html only reads it (at most to verify)."""
140
+
141
+ def validate(self):
142
+ parse_time(self.time)
143
+ Span.parse(self.at)
144
+ if self.coveredAt is not None:
145
+ if not isinstance(self.coveredAt, list):
146
+ raise ValueError("coveredAt must be a list of At values")
147
+ for cover in self.coveredAt:
148
+ if not isinstance(cover, At):
149
+ raise ValueError("coveredAt must be a list of At values")
150
+ cover.validate()
151
+
152
+ def to_dict(self):
153
+ data = super().to_dict()
154
+ if self.coveredAt is not None:
155
+ data["coveredAt"] = [str(entry) for entry in self.coveredAt]
156
+ return data
157
+
158
+ @classmethod
159
+ def _from_dict(cls, data: dict):
160
+ if "coveredAt" in data:
161
+ data["coveredAt"] = [At.parse(cover) for cover in data["coveredAt"]]
162
+ return cls(**data)
163
+
164
+
165
+ class ReviewIndex:
166
+ """The parsed records of a review block, indexed for lookup.
167
+
168
+ The original order is kept in :attr:`records` (the serialization source);
169
+ :attr:`sources` and :attr:`reviews` partition it, and
170
+ :attr:`sources_by_line` groups sources by the line they cover so a review's
171
+ ``coveredAt`` can be derived. The index is rebuilt on every load, never
172
+ stored.
173
+ """
174
+
175
+ def __init__(self, records: Iterable[Record]):
176
+ self.records = list(records)
177
+ self.sources: list[SourceRecord] = []
178
+ self.reviews: list[ReviewRecord] = []
179
+ self.sources_by_line: dict[int, list[SourceRecord]] = {}
180
+ for record in self.records:
181
+ record.validate()
182
+ if isinstance(record, SourceRecord):
183
+ self.sources.append(record)
184
+ for line in Span.parse(record.at).lines():
185
+ self.sources_by_line.setdefault(line, []).append(record)
186
+ elif isinstance(record, ReviewRecord):
187
+ self.reviews.append(record)
188
+ for bucket in self.sources_by_line.values():
189
+ bucket.sort(key=_before)
190
+ for record in self.reviews:
191
+ missing = set(Span.parse(record.at).lines()) - self.sources_by_line.keys()
192
+ if missing:
193
+ raise ValueError(
194
+ f"review at {record.at} is not covered by a source"
195
+ f" (lines {sorted(missing)})"
196
+ )
197
+ for review in self.reviews:
198
+ review.coveredAt = self.covered_at(review) or None
199
+
200
+ def covered_at(self, review: ReviewRecord):
201
+ """Derive a review's ``coveredAt`` entries from its creation version.
202
+
203
+ Each contiguous run of lines that shares the same source version becomes
204
+ one ``span@stamp`` value; a run still on the live version is omitted.
205
+ """
206
+ span = Span.parse(review.at)
207
+ moment = parse_time(review.time)
208
+ covered_at: list[At] = []
209
+ start: int | None = None
210
+ current: str | None = None
211
+ for line in span.lines():
212
+ source = self._live_at(line, moment)
213
+ before = None if source is None else source.before
214
+ if start is None: # the first line of review
215
+ start, current = line, before
216
+ elif before == current:
217
+ continue
218
+ else: # zone of current ends, record the span
219
+ if current is not None:
220
+ covered_at.append(At(Span(start, 0, line, 0), current))
221
+ start, current = line, before
222
+ if start is not None and current is not None:
223
+ covered_at.append(At(Span(start, 0, line + 1, 0), current))
224
+ return covered_at
225
+
226
+ def _live_at(self, line: int, moment: datetime):
227
+ """The source whose version was live at *moment* on *line*.
228
+
229
+ Find a line in the history: the first one whose boundary follows *moment*,
230
+ skipping a source that had not appeared yet. A source's birth is the
231
+ stamp of the zero-length ``cover`` an insertion carries; ``None`` means it
232
+ has always existed. Returns ``None`` when no source covers the line.
233
+ """
234
+ for source in self.sources_by_line.get(line, ()):
235
+ if source.cover is not None and parse_time(source.cover.time) > moment:
236
+ continue
237
+ if source.before is None or parse_time(source.before) > moment:
238
+ return source