Answer stability round 1: 0 🔴, 6 🟡 (0 misread); leave blank lines and empty files out of what a chunk touched, spell a name that holds a backtick as Markdown does, pin two mutants, and sort a chunk's IDs
This commit is contained in:
@@ -101,7 +101,7 @@ def bundled(plan: Plan) -> list[str]:
|
||||
|
||||
|
||||
def beside(plan: Plan) -> list[str]:
|
||||
"""The items that may start chunks while first's runs, by touch_predictions' pick; no line where the release's items predict nothing."""
|
||||
"""The items that may start chunks while first's runs, by touch_predictions' pick; no line where none of the release's items holds a prediction."""
|
||||
first = plan.first
|
||||
found = chunks_beside(plan.items, first)
|
||||
if found is None:
|
||||
@@ -112,7 +112,7 @@ def beside(plan: Plan) -> list[str]:
|
||||
refused = f" Not beside it: {'; '.join(found.refused)}." if found.refused else ""
|
||||
if not found.picked:
|
||||
return [f"{none}.{refused}"]
|
||||
return [f"- The items of release {version(first.release)} that may start chunks beside item {first.id}'s, since none is predicted to touch a part that item {first.id} or an item named before it touches: {', '.join(map(str, found.picked))}. An item this chunk takes starts none.{refused}"]
|
||||
return [f"- The items of release {version(first.release)} that may start chunks beside item {first.id}'s: {', '.join(map(str, found.picked))}. None is predicted to touch a part that item {first.id} touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own.{refused}"]
|
||||
|
||||
|
||||
def named_lines(named: list[NamedPath] | Failure) -> list[str]:
|
||||
|
||||
@@ -43,12 +43,13 @@ and prints that the release reviews and the cuts are the human's to call. It pri
|
||||
- the items of that release that a chunk taking the item may take too, each with its L, E + I,
|
||||
S and tagline: those that are not questions, that have R 5 or less, and that no item outside
|
||||
the chunk blocks; none where the item's own R is above 5;
|
||||
- where an item of that release that doesn't wait holds a prediction, the bullets under a
|
||||
`Touches:` line in its detail that `touch-predictions --help` describes: the items of the release
|
||||
that may start chunks while the item's chunk runs. Those are the items that don't wait and are
|
||||
predicted to touch no part that the item, or an item picked before them, touches too, taken in
|
||||
the plan's order; a part either side marks (small) doesn't count. Then why each other item may
|
||||
not. The plan and the records belong in no prediction, since every chunk writes them;
|
||||
- the other items of that release that may start chunks while the item's chunk runs, then why each
|
||||
of the rest may not. An item's prediction is the bullets under a `Touches:` line in its detail,
|
||||
which `touch-predictions --help` describes. Another item may start a chunk where it doesn't
|
||||
wait and its prediction shares no part with the item's, or with that of an item picked before
|
||||
it in the plan's order. A part either prediction marks (small) doesn't count. This line is left
|
||||
out where no item of the release that doesn't wait holds a prediction. The plan and the records
|
||||
belong in no prediction, since every chunk writes them;
|
||||
- each file or folder git tracks that the item's tagline or detail names in backticks, with a
|
||||
file's lines or a folder's files, then the item's tagline and detail, then the detail of each
|
||||
of the first {JOINING_DETAILS} items that may join, or that one has none;
|
||||
|
||||
@@ -639,11 +639,11 @@ class BesideTest(unittest.TestCase):
|
||||
|
||||
def test_names_the_items_that_may_start_chunks_beside_it_and_why_the_others_may_not(self):
|
||||
todo = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + self.DETAILS
|
||||
self.assertEqual(self.said(todo), ["- The items of release 0.2.0 that may start chunks beside item 3's, since none is predicted to touch a part that item 3 or an item named before it touches: 4. An item this chunk takes starts none. Not beside it: item 6, which overlaps item 3 at `src/app.py` `run`."])
|
||||
self.assertEqual(self.said(todo), ["- The items of release 0.2.0 that may start chunks beside item 3's: 4. None is predicted to touch a part that item 3 touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own. Not beside it: item 6, which overlaps item 3 at `src/app.py` `run`."])
|
||||
|
||||
def test_names_each_item_that_may_and_stops_there_when_none_is_refused(self):
|
||||
todo = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + self.DETAILS.removesuffix("`run`\n") + "`other`\n"
|
||||
self.assertEqual(self.said(todo), ["- The items of release 0.2.0 that may start chunks beside item 3's, since none is predicted to touch a part that item 3 or an item named before it touches: 4, 6. An item this chunk takes starts none."])
|
||||
self.assertEqual(self.said(todo), ["- The items of release 0.2.0 that may start chunks beside item 3's: 4, 6. None is predicted to touch a part that item 3 touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own."])
|
||||
|
||||
def test_says_when_none_may(self):
|
||||
todo = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + self.DETAILS.replace("`stop`", "`run`")
|
||||
|
||||
@@ -36,7 +36,7 @@ a path that starts with / or ~/ and lies outside the checkout and the config's f
|
||||
"~/.claude-projects/acme-billing.env". Where it is left out, the project has no credentials file, and
|
||||
a tool that needs one fails naming the setting. It is printed with the others only where it is set.
|
||||
|
||||
`touch-predictions` is an optional setting, a path spelt as the settings above: the record where
|
||||
`touch-predictions` is an optional setting, a path spelt as `changelog`'s is: the record where
|
||||
`touch-predictions record` appends what each chunk was predicted to touch beside what it touched. Left
|
||||
out, the project keeps no such record. It is printed with the others only where it is set.
|
||||
|
||||
@@ -96,7 +96,7 @@ Exit 1, naming each fault on stderr, where no config names the checkout, or its
|
||||
setting, names an unknown one, misspells a path, a language or a template, sets `wait-for-approval` or
|
||||
`tooling-on-host` to anything but true or false, sets `notifier` to anything but mattermost or slack or
|
||||
without `env-file`, or sets `readability-floor` to anything but a number
|
||||
from 1 to 10, and where `env-file` or `notifier` is asked for and not set. No path setting has a default.
|
||||
from 1 to 10, and where `env-file`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
|
||||
"""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
@@ -37,7 +37,7 @@ LANGUAGE = "language"
|
||||
COMMIT_TITLE = "commit-title"
|
||||
PULL_REQUEST_TITLE = "pull-request-title"
|
||||
BRANCH = "branch"
|
||||
# An optional path setting, spelt as SETTINGS' are: the record of what each chunk was predicted to touch beside what it touched. A project that leaves it out keeps no such record. Three readers, seated as the human who writes the config, picked the name from four candidates.
|
||||
# An optional path setting: main's help says what it places.
|
||||
TOUCH_PREDICTIONS = "touch-predictions"
|
||||
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
|
||||
# What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it.
|
||||
|
||||
@@ -14,9 +14,9 @@ class Beside:
|
||||
|
||||
|
||||
def chunks_beside(found: list[Item], first: Item) -> Beside | str | None:
|
||||
"""The items of first's release that don't wait and overlap neither first nor an item picked before them, taken in the plan's order.
|
||||
"""The items that may start chunks while first's runs, with why each other item may not. Else why no item may, as a sentence's end; None where no item of first's release that doesn't wait holds a prediction, as in a project that doesn't write any.
|
||||
|
||||
The plan's order decides, not the largest set: a larger set could start a low-ranked item in place of one ranked above it. An item first's chunk takes starts no chunk of its own. Else why no item may, as a sentence's end; None where no such item's detail holds a prediction, as in a project that writes none."""
|
||||
An item may where it names first's release, doesn't wait, and overlaps neither first nor an item picked before it in the plan's order. The plan's order decides, not the largest set: a larger set could start a low-ranked item in place of one ranked above it. It cannot know which items first's chunk takes, so chunk-preflight's line tells its reader to leave those out."""
|
||||
waits = waiting(found, set())
|
||||
ready = [item for item in found if item.release == first.release and item.id not in waits]
|
||||
if not any(LABEL in item.detail.splitlines() for item in ready):
|
||||
|
||||
@@ -27,19 +27,30 @@ def touched(base: str, head: str, cwd: str, skipped: set[str], run: Git = git) -
|
||||
|
||||
|
||||
def modified(base: str, head: str, path: str, cwd: str, run: Git) -> tuple[Part, ...] | Failure:
|
||||
"""The parts of path whose lines the diff removed, in base's text, or added, in head's; line ranges of head's text where either text has no names."""
|
||||
"""The parts of path whose lines the diff removed, in base's text, or added, in head's; line ranges of head's text where either text has no names. A separator, as file_parts defines it, names its part only where the diff changed no other line."""
|
||||
diff = run("diff", "--no-renames", "-U0", base, head, "--", path, cwd=cwd, errors="replace")
|
||||
if isinstance(diff, Failure):
|
||||
return diff
|
||||
hunks = [(int(old), int(olds or 1), int(new), int(news or 1)) for old, olds, new, news in HUNK.findall(diff)]
|
||||
names: set[str] | None = set()
|
||||
sides = []
|
||||
for revision, lines in ((base, [line for old, olds, _, _ in hunks for line in range(old, old + olds)]), (head, [line for _, _, new, news in hunks for line in range(new, new + news)])):
|
||||
text = run("show", f"{revision}:{path}", cwd=cwd, errors="replace")
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
found = part_names(path, text, lines)
|
||||
names = None if names is None or found is None else names | found
|
||||
sides.append((text, lines))
|
||||
names = named(path, sides, separators=False) or named(path, sides, separators=True)
|
||||
if names is None:
|
||||
# A hunk that only deletes names the line it left, or the first where it left none.
|
||||
# A hunk that only deletes lines counts as the line above them, or as line 1 where it deleted the file's first lines.
|
||||
return tuple(Part(f"lines {max(new, 1)}-{max(new + max(news, 1) - 1, 1)}") for _, _, new, news in hunks)
|
||||
return tuple(Part(name) for name in sorted(names))
|
||||
|
||||
|
||||
def named(path: str, sides: list[tuple[str, list[int]]], separators: bool) -> set[str] | None:
|
||||
"""The parts the lines of each side lie in, each side a text and its lines; None where either text has no names."""
|
||||
names: set[str] = set()
|
||||
for text, lines in sides:
|
||||
found = part_names(path, text, lines, separators)
|
||||
if found is None:
|
||||
return None
|
||||
names |= found
|
||||
return names
|
||||
|
||||
@@ -4,46 +4,52 @@ Where each language's boundaries come from:
|
||||
|
||||
- Python, a path ending .py: the standard `ast` module. A part is a function or class, named with the classes and functions around it, as in `Plan.branch`; a top-level assignment, by the name it sets; or `(module)` for any other top-level line.
|
||||
- Markdown, a path ending .md: the heading lines outside fenced code. A part is the nearest heading above, spelt as its line, as in `## Goals`; `(top)` before the first.
|
||||
- Any other file, and Python that doesn't parse: no names, so diff_parts falls back to line ranges."""
|
||||
- Any other file, and Python that doesn't parse: no names, so diff_parts falls back to line ranges.
|
||||
|
||||
A separator is a blank line that Python holds between two statements, or Markdown anywhere. It names no part: git ends the hunk of an inserted function with the blank lines after it, and opens an appended section's with the one before it."""
|
||||
import ast
|
||||
import io
|
||||
import re
|
||||
import typing
|
||||
|
||||
MODULE = "(module)"
|
||||
TOP = "(top)"
|
||||
HEADING = re.compile(r"#{1,6} \S")
|
||||
FENCE = re.compile(r" {0,3}(```|~~~)")
|
||||
FENCE = re.compile(r" {0,3}(`{3,}|~{3,})(.*)")
|
||||
DEFINITION = ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef
|
||||
|
||||
|
||||
def part_names(path: str, text: str, lines: typing.Iterable[int]) -> set[str] | None:
|
||||
"""The part each of lines, counted from 1, lies in; None where the file's kind has no names."""
|
||||
def part_names(path: str, text: str, lines: typing.Iterable[int], separators: bool = False) -> set[str] | None:
|
||||
"""The part each of lines, counted from 1, lies in; None where the file's kind has no names. A separator among lines names its part only where separators is set."""
|
||||
if path.endswith(".py"):
|
||||
return python_parts(text, lines)
|
||||
return python_parts(text, lines, separators)
|
||||
if path.endswith(".md"):
|
||||
return markdown_parts(text, lines)
|
||||
return markdown_parts(text, lines, separators)
|
||||
return None
|
||||
|
||||
|
||||
def python_parts(text: str, lines: typing.Iterable[int]) -> set[str] | None:
|
||||
def python_parts(text: str, lines: typing.Iterable[int], separators: bool) -> set[str] | None:
|
||||
try:
|
||||
tree = ast.parse(text)
|
||||
except (SyntaxError, ValueError):
|
||||
return None
|
||||
if not tree.body:
|
||||
return {MODULE}
|
||||
# Each top-level statement's first and last line, then each part's with its name.
|
||||
statements = [(first_line(statement), statement.end_lineno or statement.lineno) for statement in tree.body]
|
||||
spans = [(*lines_, assigned(statement)) for lines_, statement in zip(statements, tree.body) if not isinstance(statement, DEFINITION)]
|
||||
spans.extend(nested(tree, ""))
|
||||
|
||||
def name(line: int) -> str:
|
||||
# A line between two statements, such as a comment, goes with the one below it; one after the last, with the last.
|
||||
blank = {number for number, row in enumerate(io.StringIO(text), 1) if not row.strip()}
|
||||
names: set[str] = set()
|
||||
for line in lines:
|
||||
if not any(first <= line <= last for first, last in statements):
|
||||
if line in blank and not separators:
|
||||
continue
|
||||
if not statements:
|
||||
names.add(MODULE)
|
||||
continue
|
||||
# A line between two statements, such as a comment, goes with the one below it; one after the last, with the last.
|
||||
line = min((first for first, _ in statements if first > line), default=statements[-1][0])
|
||||
return max((span for span in spans if span[0] <= line <= span[1]), key=lambda span: span[0])[2]
|
||||
|
||||
return {name(line) for line in lines}
|
||||
names.add(max((span for span in spans if span[0] <= line <= span[1]), key=lambda span: span[0])[2])
|
||||
return names
|
||||
|
||||
|
||||
def nested(node: ast.AST, prefix: str) -> list[tuple[int, int, str]]:
|
||||
@@ -69,15 +75,21 @@ def assigned(statement: ast.stmt) -> str:
|
||||
return targets[0].id if len(targets) == 1 and isinstance(targets[0], ast.Name) else MODULE
|
||||
|
||||
|
||||
def markdown_parts(text: str, lines: typing.Iterable[int]) -> set[str]:
|
||||
def markdown_parts(text: str, lines: typing.Iterable[int], separators: bool) -> set[str]:
|
||||
wanted, names = set(lines), set()
|
||||
heading, fenced = TOP, False
|
||||
# fence is the run of characters that opened the fenced code a line lies in, and empty outside one.
|
||||
heading, fence = TOP, ""
|
||||
for number, line in enumerate(text.splitlines(), 1):
|
||||
if FENCE.match(line):
|
||||
fenced = not fenced
|
||||
elif not fenced and HEADING.match(line):
|
||||
found = FENCE.match(line)
|
||||
if fence:
|
||||
# CommonMark: a fence closes on a run of its own character, at least as long, with no text after it.
|
||||
if found and found.group(1).startswith(fence) and not found.group(2).strip():
|
||||
fence = ""
|
||||
elif found:
|
||||
fence = found.group(1)
|
||||
elif HEADING.match(line):
|
||||
heading = line.rstrip()
|
||||
if number in wanted:
|
||||
if number in wanted and (separators or line.strip()):
|
||||
names.add(heading)
|
||||
# A line past the end, as a deletion at the end names, lies under the last heading.
|
||||
return names | ({heading} if any(line > len(text.splitlines()) for line in wanted) else set())
|
||||
|
||||
@@ -14,9 +14,10 @@ per file, as in
|
||||
- `bin/run.sh`: lines 10-20
|
||||
- `docs/new.md`
|
||||
|
||||
A path alone is the whole file, and (small) marks a part the item changes only a little. It names
|
||||
what the branch touched the same way, from the diff between the branch's merge base with the
|
||||
default branch and HEAD:
|
||||
A path alone is the whole file, and (small) marks a part the item changes only a little. A path or
|
||||
a name that holds a backtick takes a longer run of backticks with a space inside each end, as a
|
||||
Markdown code span does: `` ## The `foo` tool ``. It names what the branch touched the same way,
|
||||
from the diff between the branch's merge base with the default branch and HEAD:
|
||||
|
||||
- in a .py file, by Python's `ast` module: the innermost function or class a changed line lies in,
|
||||
named with those around it; a top-level assignment by the name it sets; `(module)` for any other
|
||||
@@ -28,14 +29,18 @@ default branch and HEAD:
|
||||
- a file the branch added or deleted, or changed without text hunks, as the path alone. A rename
|
||||
reads as a file deleted and one added.
|
||||
|
||||
It leaves out the plan and the project's records, which every chunk writes. It appends
|
||||
`## Chunk <IDs>, <UTC time>, at <commit>` with both lists to the record the project's config names
|
||||
as `touch-predictions`, in place of an entry the record already holds for the same items. Commit
|
||||
the record with the chunk. Where the config leaves the setting out, it says so and exits 0.
|
||||
A changed blank line names no part where the file has other changed lines, unless it lies inside a
|
||||
Python statement.
|
||||
|
||||
Exit 1, saying why, on any other arguments, when no config names the checkout, the plan or the
|
||||
record cannot be read or written, the plan holds no item <ID>, a `Touches:` list cannot be read, or
|
||||
git cannot name the merge base or the diff.
|
||||
It leaves out the plan and the project's records, which every chunk writes. It appends
|
||||
`## Chunk <IDs>, <UTC time>, at <commit>`, the IDs in rising order, with both lists to the record
|
||||
the project's config names as `touch-predictions`, in place of an entry the record already holds
|
||||
for the same items. Commit the record with the chunk. Where the config leaves the setting out, it
|
||||
says so and exits 0.
|
||||
|
||||
Exit 1, saying why: on any other arguments; when no config names the checkout; when the plan or
|
||||
the record cannot be read or written; when the plan holds no item <ID>; when a `Touches:` list
|
||||
cannot be read; or when git cannot name the merge base or the diff.
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
@@ -60,7 +65,7 @@ def main(argv: list[str]) -> int:
|
||||
print("usage: touch-predictions record <ID>...", file=sys.stderr)
|
||||
return 1
|
||||
config = project()
|
||||
done = config if isinstance(config, Failure) else recorded(config, [int(id_) for id_ in argv[1:]])
|
||||
done = config if isinstance(config, Failure) else recorded(config, sorted({int(id_) for id_ in argv[1:]}))
|
||||
if isinstance(done, Failure):
|
||||
print(f"touch-predictions: {done.reason}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -82,7 +87,7 @@ def recorded(config: ProjectConfig, ids: list[int]) -> str | Failure:
|
||||
head = base if isinstance(base, Failure) else git("rev-parse", "--short", "HEAD", cwd=cwd)
|
||||
if isinstance(base, Failure) or isinstance(head, Failure):
|
||||
return head if isinstance(head, Failure) else base
|
||||
# Every chunk writes the plan and the records, so they tell no two chunks apart.
|
||||
# Every chunk writes the plan and the records, so they are left out of what a chunk touched.
|
||||
skipped = {path for name in ("plan", *RECORDS, TOUCH_PREDICTIONS) if (path := config.tracked(name))}
|
||||
touches = touched(base.strip(), "HEAD", cwd, skipped)
|
||||
if isinstance(touches, Failure):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""An item's prediction of the files and parts it will touch, as its detail spells it, and where two predictions overlap.
|
||||
|
||||
The spelling, which three readers seated as the project's audience picked from four candidates:
|
||||
The spelling, which the decision `todo.md: an item of the next release predicts the files and parts it will touch …` gives the reasons for:
|
||||
|
||||
Touches:
|
||||
|
||||
@@ -8,16 +8,18 @@ The spelling, which three readers seated as the project's audience picked from f
|
||||
- `bin/run.sh`: lines 10-20
|
||||
- `docs/new.md`
|
||||
|
||||
A path alone is the whole file, and (small) marks a part the item changes only a little. file_parts says how a part is named."""
|
||||
A path alone is the whole file, and (small) marks a part the item changes only a little. file_parts says how a part is named.
|
||||
|
||||
A path or a name that holds a backtick is spelt as a Markdown code span that holds one: in a longer run of backticks than any it holds, with a space inside each end, as in `` ## The `foo` tool ``. So every path and name on one line has a spelling."""
|
||||
import dataclasses
|
||||
import re
|
||||
|
||||
from failure import Failure
|
||||
|
||||
LABEL = "Touches:"
|
||||
SMALL = " (small)"
|
||||
RANGE = re.compile(r"lines (\d+)-(\d+)")
|
||||
PART = re.compile(r"(`[^`]+`|lines \d+-\d+)( \(small\))?")
|
||||
BULLET = re.compile(rf"- `([^`\s]+)`(?:: ({PART.pattern}(?:, {PART.pattern})*))?")
|
||||
BACKTICKS = re.compile(r"`+")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -42,21 +44,66 @@ def predicted(detail: str) -> Touches | None | Failure:
|
||||
continue
|
||||
if not line.startswith("- "):
|
||||
break
|
||||
bullet = BULLET.fullmatch(line)
|
||||
parts = tuple(Part(name.strip("`"), bool(small)) for name, small in PART.findall(bullet.group(2) or "")) if bullet else ()
|
||||
if bullet is None or any(span and span[0] > span[1] for span in map(line_range, parts)):
|
||||
return Failure(f"the bullet {line!r} under `{LABEL}` is not a path in backticks, then optionally a colon and its parts, each a name in backticks or `lines <first>-<last>`, and optionally ` (small)`")
|
||||
touches = together([touches, {bullet.group(1): parts}])
|
||||
read = bullet(line)
|
||||
if read is None:
|
||||
return Failure(f"the bullet {line!r} under `{LABEL}` is not a path in backticks, then optionally a colon and its parts, each a name in backticks or `lines <first>-<last>`, and optionally `{SMALL}`")
|
||||
if any(span and span[0] > span[1] for span in map(line_range, read[1])):
|
||||
return Failure(f"the bullet {line!r} under `{LABEL}` holds a line range whose first line comes after its last")
|
||||
touches = together([touches, {read[0]: read[1]}])
|
||||
return touches or Failure(f"no bullet follows `{LABEL}`")
|
||||
|
||||
|
||||
def bullet(line: str) -> tuple[str, tuple[Part, ...]] | None:
|
||||
"""The path and the parts a bullet names; None where it is not spelt as one."""
|
||||
path = code_span(line, len("- "))
|
||||
if path is None:
|
||||
return None
|
||||
parts = []
|
||||
at, separator = path[1], ": "
|
||||
while at < len(line):
|
||||
if not line.startswith(separator, at):
|
||||
return None
|
||||
found = RANGE.match(line, at + len(separator))
|
||||
part = (found.group(), found.end()) if found else code_span(line, at + len(separator))
|
||||
if part is None:
|
||||
return None
|
||||
small = line.startswith(SMALL, part[1])
|
||||
parts.append(Part(part[0], small))
|
||||
at, separator = part[1] + len(SMALL) * small, ", "
|
||||
return path[0], tuple(parts)
|
||||
|
||||
|
||||
def code_span(line: str, at: int) -> tuple[str, int] | None:
|
||||
"""The text of the code span that opens at index at of line, and the index after it; None where none does. The span ends at the next run of as many backticks as open it."""
|
||||
opened = BACKTICKS.match(line, at)
|
||||
run = opened.group() if opened else ""
|
||||
closed = re.search(rf"(?<!`){run}(?!`)", line[opened.end():]) if opened else None
|
||||
if opened is None or closed is None:
|
||||
return None
|
||||
text = line[opened.end():opened.end() + closed.start()]
|
||||
if len(run) > 1:
|
||||
# A longer run holds a space inside each end, which keeps a backtick at either end of the text apart from the run.
|
||||
if len(text) < 3 or not text.startswith(" ") or not text.endswith(" "):
|
||||
return None
|
||||
text = text[1:-1]
|
||||
return (text, opened.end() + closed.end()) if text else None
|
||||
|
||||
|
||||
def rendered(touches: Touches) -> str:
|
||||
"""touches as the bullets predicted reads."""
|
||||
return "\n".join(f"- `{path}`" + (": " + ", ".join(shown(part) + " (small)" * part.small for part in parts) if parts else "") for path, parts in touches.items())
|
||||
return "\n".join(f"- {code(path)}" + (": " + ", ".join(shown(part) + SMALL * part.small for part in parts) if parts else "") for path, parts in touches.items())
|
||||
|
||||
|
||||
def shown(part: Part) -> str:
|
||||
return part.name if line_range(part) else f"`{part.name}`"
|
||||
return part.name if line_range(part) else code(part.name)
|
||||
|
||||
|
||||
def code(text: str) -> str:
|
||||
"""text as the code span code_span reads."""
|
||||
if "`" not in text:
|
||||
return f"`{text}`"
|
||||
run = "`" * (1 + max(map(len, BACKTICKS.findall(text))))
|
||||
return f"{run} {text} {run}"
|
||||
|
||||
|
||||
def line_range(part: Part) -> tuple[int, int] | None:
|
||||
@@ -92,7 +139,7 @@ def overlaps(ours: Touches, theirs: Touches) -> list[str]:
|
||||
|
||||
|
||||
def same_part(one: Part, other: Part) -> bool:
|
||||
"""Whether two parts of one file share lines, as far as their names tell: line ranges that share a line, a line range beside a name, equal names, or a class and what it holds."""
|
||||
"""Whether two parts of one file share lines, as far as their names tell: line ranges that share a line, a line range and a name, since the name doesn't say which lines it holds, equal names, or a class and what it holds."""
|
||||
spans = line_range(one), line_range(other)
|
||||
if spans[0] and spans[1]:
|
||||
return spans[0][0] <= spans[1][1] and spans[1][0] <= spans[0][1]
|
||||
|
||||
@@ -103,6 +103,30 @@ class PredictedTest(unittest.TestCase):
|
||||
assert isinstance(touches, dict)
|
||||
self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches)
|
||||
|
||||
def test_a_name_that_holds_backticks_takes_a_longer_run_with_a_space_inside_each_end(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```, `` `x` ``\n"), {"a.md": (Part("## The `foo` tool", small=True), Part("``"), Part("`x`"))})
|
||||
self.assertEqual(rendered({"a.md": (Part("## The `foo` tool", small=True), Part("``"))}), "- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```")
|
||||
|
||||
def test_a_name_ends_only_at_a_run_as_long_as_the_one_that_opens_it(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `a.md`: `` a ``` b ``, `c``d`\n"), {"a.md": (Part("a ``` b"), Part("c``d"))})
|
||||
|
||||
def test_a_path_holds_any_character_and_a_single_backtick_keeps_a_names_spaces(self) -> None:
|
||||
self.assertEqual(predicted("Touches:\n- `my file.md`: ` x `\n- `` a`b.md ``\n"), {"my file.md": (Part(" x "),), "a`b.md": ()})
|
||||
|
||||
def test_rendered_reads_back_whatever_a_path_or_a_name_holds(self) -> None:
|
||||
touches = {"my file.md": (Part("## todo.md: under `Touches:` in its detail"), Part("## ``a`` and `b`", small=True), Part("`"), Part("## ends in `x`"), Part(" x "), Part("lines 2-3")), "a`b.md": (), "c, d: e.md": (Part("# T"),)}
|
||||
self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches)
|
||||
|
||||
def test_a_longer_run_without_its_spaces_or_its_end_or_a_name_is_a_failure(self) -> None:
|
||||
for bullet in ("- `a.md`: ``## A``", "- `a.md`: `` ## A", "- `a.md`: `` ## A `", "- `a.md`: `` ``", "- `a.md`: ", "- `a.md`:", "- `a.md`: `f`, ", "- `a.md`: `f`,`g`", "- ``", "- `a.md` (small)", "- `a.md`: `f` (small) (small)"):
|
||||
with self.subTest(bullet):
|
||||
self.assertIsInstance(predicted(f"Touches:\n\n{bullet}\n"), Failure)
|
||||
|
||||
def test_a_range_that_runs_backwards_is_a_failure_that_says_so(self) -> None:
|
||||
found = predicted("Touches:\n\n- `bin/a.py`: `f`, lines 20-10\n")
|
||||
assert isinstance(found, Failure)
|
||||
self.assertEqual(found.reason, "the bullet '- `bin/a.py`: `f`, lines 20-10' under `Touches:` holds a line range whose first line comes after its last")
|
||||
|
||||
def test_together_joins_items_and_keeps_small_only_where_each_says_so(self) -> None:
|
||||
joined = together([{"a.py": (Part("f", small=True), Part("g", small=True))}, {"a.py": (Part("f"),), "b.md": ()}, {"b.md": (Part("# T"),)}])
|
||||
self.assertEqual(joined, {"a.py": (Part("f"), Part("g", small=True)), "b.md": ()})
|
||||
@@ -162,6 +186,28 @@ class FilePartsTest(unittest.TestCase):
|
||||
self.assertEqual(self.names("a.py", PYTHON, 99), {"(module)"})
|
||||
self.assertEqual(self.names("a.py", "", 1), {"(module)"})
|
||||
|
||||
def test_python_names_no_part_for_a_blank_line_between_statements(self) -> None:
|
||||
text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n# end\n\n"
|
||||
self.assertEqual(self.names("a.py", text, 1, 2, 3, 4), {"a"})
|
||||
self.assertEqual(self.names("a.py", text, 3, 4), set())
|
||||
self.assertEqual(self.names("a.py", text, 7, 9), set())
|
||||
self.assertEqual(self.names("a.py", text, 8), {"b"})
|
||||
self.assertEqual(self.names("a.py", "# only\n\n", 2), set())
|
||||
|
||||
def test_python_names_the_part_a_blank_line_inside_a_statement_lies_in(self) -> None:
|
||||
self.assertEqual(self.names("a.py", "def a():\n\tx = 1\n\n\treturn x\n\nT = \"\"\"\n\n\"\"\"\n", 3, 7), {"a", "T"})
|
||||
|
||||
def test_blank_lines_name_their_parts_where_separators_count(self) -> None:
|
||||
text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n"
|
||||
self.assertEqual(file_parts.part_names("a.py", text, [3, 7], separators=True), {"b"})
|
||||
self.assertEqual(file_parts.part_names("a.py", "# only\n\n", [2], separators=True), {"(module)"})
|
||||
self.assertEqual(file_parts.part_names("a.md", "# A\n\n", [2], separators=True), {"# A"})
|
||||
|
||||
def test_python_without_statements_names_the_module_only_for_a_line(self) -> None:
|
||||
self.assertEqual(self.names("a.py", ""), set())
|
||||
self.assertEqual(self.names("a.py", "# only a comment\n"), set())
|
||||
self.assertEqual(self.names("a.py", "# only a comment\n", 1), {"(module)"})
|
||||
|
||||
def test_python_that_does_not_parse_has_no_names(self) -> None:
|
||||
self.assertIsNone(self.names("a.py", "def (:\n", 1))
|
||||
|
||||
@@ -171,6 +217,7 @@ class FilePartsTest(unittest.TestCase):
|
||||
|
||||
def test_python_gives_a_line_after_the_last_statement_to_it(self) -> None:
|
||||
self.assertEqual(self.names("a.py", "A = 1\nB = 2\nC = 3\n# end\n", 4), {"C"})
|
||||
self.assertEqual(self.names("a.py", "class A:\n\tdef f(self):\n\t\tpass\n\n# end\n", 5), {"A"})
|
||||
|
||||
def test_markdown_drops_a_headings_trailing_space_and_puts_a_line_past_the_end_under_the_last_heading(self) -> None:
|
||||
self.assertEqual(self.names("a.md", "# A \ntext\n## B\n", 2, 4), {"# A", "## B"})
|
||||
@@ -180,6 +227,15 @@ class FilePartsTest(unittest.TestCase):
|
||||
self.assertEqual(self.names("a.md", MARKDOWN, 3, 5, 8), {"# Title"})
|
||||
self.assertEqual(self.names("a.md", MARKDOWN, 13), {"## Goals"})
|
||||
|
||||
def test_markdown_names_no_part_for_a_blank_line(self) -> None:
|
||||
self.assertEqual(self.names("a.md", "# A\ntext\n\n## End\nmore\n", 3, 4, 5), {"## End"})
|
||||
self.assertEqual(self.names("a.md", "# A\n \t\n", 2), set())
|
||||
|
||||
def test_markdown_closes_a_fence_only_on_its_own_character_at_least_as_long(self) -> None:
|
||||
self.assertEqual(self.names("a.md", "# A\n````\n```\n# not\n````\n# B\ntext\n", 4, 7), {"# A", "# B"})
|
||||
self.assertEqual(self.names("a.md", "# A\n```\n~~~\n# not\n```\n# B\ntext\n", 4, 7), {"# A", "# B"})
|
||||
self.assertEqual(self.names("a.md", "# A\n~~~\n~~~ not the end\n# not\n~~~~~ \n# B\ntext\n", 4, 7), {"# A", "# B"})
|
||||
|
||||
def test_any_other_file_has_no_names(self) -> None:
|
||||
self.assertIsNone(self.names("run.sh", "echo\n", 1))
|
||||
|
||||
@@ -303,6 +359,31 @@ class TouchedTest(unittest.TestCase):
|
||||
self.repo.commit({"gone.py": "x = 2\ny = 3\n", "run.sh": "one\n"})
|
||||
self.assertEqual(diff_parts.touched(self.base, head, self.repo.folder, set()), {"gone.py": (Part("x"),)})
|
||||
|
||||
def test_reads_the_diff_up_to_head_whatever_the_work_tree_holds(self) -> None:
|
||||
text = "def f():\n\treturn 1\n\n\ndef g():\n\treturn 2\n"
|
||||
self.base = self.repo.commit({"gone.py": text})
|
||||
head = self.repo.commit({"gone.py": text.replace("return 2", "return 3")})
|
||||
pathlib.Path(self.repo.folder, "gone.py").write_text("def new():\n\treturn 0\n\n\n" + text.replace("return 2", "return 3"), encoding="utf-8")
|
||||
self.assertEqual(diff_parts.touched(self.base, head, self.repo.folder, set()), {"gone.py": (Part("g"),)})
|
||||
|
||||
def test_an_inserted_function_or_section_does_not_name_its_neighbours(self) -> None:
|
||||
text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n\ndef c():\n\treturn 3\n"
|
||||
self.base = self.repo.commit({"m.py": text, "m.md": "# A\ntext\n\n## B\ntext\n", "pkg.py": "", "c.py": "# only a comment\n"})
|
||||
self.assertEqual(self.touched({"m.py": text.replace("def b", "def new():\n\treturn 9\n\n\ndef b"), "m.md": "# A\ntext\n\n## B\ntext\n\n## End\nmore\n", "pkg.py": "def f():\n\treturn 1\n", "c.py": "# only a comment\n\n\ndef g():\n\treturn 1\n"}), {
|
||||
"c.py": (Part("g"),),
|
||||
"m.md": (Part("## End"),),
|
||||
"m.py": (Part("new"),),
|
||||
"pkg.py": (Part("f"),),
|
||||
})
|
||||
|
||||
def test_a_deleted_function_does_not_name_the_next_one(self) -> None:
|
||||
text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n\ndef c():\n\treturn 3\n"
|
||||
self.base = self.repo.commit({"m.py": text})
|
||||
self.assertEqual(self.touched({"m.py": text.replace("def b():\n\treturn 2\n\n\n", "")}), {"m.py": (Part("b"),)})
|
||||
|
||||
def test_a_change_of_blank_lines_alone_names_the_part_they_go_with(self) -> None:
|
||||
self.assertEqual(self.touched({"a.py": PYTHON.replace("\n\nclass Plan", "\n\n\nclass Plan"), "a.md": MARKDOWN.replace("Text.\n", "Text.\n\n")}), {"a.md": (Part("# Title"),), "a.py": (Part("Plan"),)})
|
||||
|
||||
def test_reads_text_that_is_not_utf_8(self) -> None:
|
||||
self.repo.commit({"n.md": b"# T\ncaf\xe9\n"})
|
||||
self.base = self.repo.run("rev-parse", "HEAD")
|
||||
@@ -379,6 +460,13 @@ class RecordCommandTest(unittest.TestCase):
|
||||
self.assertEqual(text.count("## Chunk 3, "), 1)
|
||||
self.assertNotIn("touch-predictions.md", text)
|
||||
|
||||
def test_names_a_chunk_by_its_ids_in_order_each_once(self) -> None:
|
||||
path = self.set_record()
|
||||
self.record("record", "3", "4")
|
||||
ran = self.record("record", "4", "3", "4")
|
||||
self.assertEqual(ran.stdout, f"Recorded what chunk 3, 4 was predicted to touch, and what it touched, in {path}.\n")
|
||||
self.assertEqual(re.findall(r"^## Chunk ([\d, ]+), \d{4}", path.read_text(encoding="utf-8"), re.M), ["3, 4"])
|
||||
|
||||
def test_records_nothing_where_the_config_leaves_the_setting_out(self) -> None:
|
||||
ran = self.record("record", "3")
|
||||
self.assertEqual((ran.returncode, ran.stdout), (0, "The project's config sets no `touch-predictions`, so nothing is recorded.\n"))
|
||||
|
||||
Reference in New Issue
Block a user