173 lines
9.0 KiB
Python
173 lines
9.0 KiB
Python
"""The features task-bench has Haiku rebuild: those the project shipped, read from its history. A shipped feature is a chunk on
|
|
the base's first-parent line that took an item out of the plan, as branch_chunks cuts that line. Once its change is out of each
|
|
side's tree, it is a feature as task_bench.features.feature_tasks has it. `task-bench --help` says what Haiku is told and how a rebuild
|
|
is checked."""
|
|
import functools
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import shutil
|
|
import typing
|
|
|
|
from task_bench.features.feature_tasks import ACCEPTANCE, Feature, PATCH, why_passed_over
|
|
from task_bench.tasks import Bench, committed, on_disk, Planned, Side, SIDES, Task
|
|
from branch_chunks.read import cut_with_shipped, unsupported
|
|
from failure import Failure
|
|
from git_cli.git_repo import Git
|
|
from plan.todo_table import Item, tagline_text
|
|
from project_config.main import located
|
|
from task_bench.runs import of_tests
|
|
from project_config.settings import RECORDS
|
|
|
|
# Why a feature that landed by fast-forward is passed over: no earlier chunk says where its commits start, or its branch merged
|
|
# the default branch into itself, so its commits hold what other features built.
|
|
NO_START = "its branch landed by fast-forward, and nothing earlier marks where its commits start"
|
|
MERGED_IN = "its branch landed by fast-forward after merging the default branch into itself, so its commits hold other features' changes"
|
|
# What git titles a merge of the default branch into a feature branch, other than into main or master, which git leaves out of
|
|
# the title. A person's merge of a branch into another default branch has the same title; its feature is then passed over.
|
|
SYNC_MERGE = re.compile(r"Merge (?:remote-tracking )?branch '[^']+' into (?!main$|master$)\S+")
|
|
|
|
# The options that keep the checkout's diff config out of a patch. --no-renames writes a renamed file as one file removed and
|
|
# one added, so `git apply` doesn't have to detect the rename again.
|
|
PLAIN_DIFF = ("--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "--src-prefix=a/", "--dst-prefix=b/")
|
|
|
|
|
|
class Shipped(typing.NamedTuple):
|
|
"""A feature the project shipped: the name the report gives it, such as `item 7`, the tagline of each item its chunk took out
|
|
of the plan, a paragraph each, and the commits its change runs between. before is None where the history doesn't say where
|
|
the change starts, and passed_over then says why."""
|
|
|
|
name: str
|
|
told: str
|
|
before: str | None
|
|
tip: str
|
|
passed_over: str = ""
|
|
|
|
|
|
class ShippedFeatures(typing.NamedTuple):
|
|
"""The features a project shipped, newest first, and the paths of its plan and its records, each from the checkout's top. A
|
|
chunk's change to those paths is no part of its feature."""
|
|
|
|
found: list[Shipped]
|
|
records: list[str]
|
|
|
|
|
|
def read_shipped(home: pathlib.Path, checkout: str, base: str, git: Git) -> ShippedFeatures | Failure:
|
|
"""The features that the project in checkout shipped on the first-parent line of the commit base. A Failure where no config
|
|
names the checkout, where its config puts the plan or a record at a path branch_chunks doesn't read, where git fails, and
|
|
where that line shipped no item."""
|
|
in_checkout = functools.partial(git, cwd=checkout)
|
|
config = located(checkout, home, in_checkout)
|
|
if isinstance(config, Failure):
|
|
return config
|
|
if why := unsupported(checkout, home, in_checkout):
|
|
return Failure(f"task-bench cannot tell what the project shipped: {why}")
|
|
cut = cut_with_shipped(base, in_checkout, config.titles)
|
|
if isinstance(cut, Failure):
|
|
return cut
|
|
branch, shipped = cut
|
|
found: list[Shipped] = []
|
|
# The oldest chunk first, so each feature knows the commit that ends the chunk before it.
|
|
marked = None
|
|
merged_in = False
|
|
for chunk, items in reversed(list(zip(branch.chunks, shipped))):
|
|
if items:
|
|
# A fast-forwarded feature's commits are a chunk each, and this chunk holds only the last. The earlier ones follow the
|
|
# commit that ends the latest earlier chunk of another feature.
|
|
starts, why = chunk.before, ""
|
|
if chunk.landing == "push":
|
|
starts, why = (None, NO_START) if marked is None else (None, MERGED_IN) if merged_in else (marked, "")
|
|
told = "\n\n".join(tagline_text(item.tagline) for item in items)
|
|
found.append(Shipped(named(items), told, starts, chunk.tip, why))
|
|
if SYNC_MERGE.fullmatch(branch.commits[chunk.tip].title):
|
|
merged_in = True
|
|
elif items or chunk.landing != "push":
|
|
marked, merged_in = chunk.tip, False
|
|
found.reverse()
|
|
if not found:
|
|
return Failure("No chunk on the base's history took an item out of todo.md, so that history holds no shipped feature to rebuild.")
|
|
return ShippedFeatures(found, [path for path in map(config.tracked, ("plan", *RECORDS)) if path])
|
|
|
|
|
|
def named(items: tuple[Item, ...]) -> str:
|
|
"""What the report calls the feature that shipped items: `item 7`, or `items 7, 8`."""
|
|
return f"item{'s' * (len(items) > 1)} {', '.join(str(item.id) for item in items)}"
|
|
|
|
|
|
def shipped_tasks(bench: Bench, shipped: ShippedFeatures, count: int) -> Planned | Failure:
|
|
"""The task of rebuilding each feature of shipped that counts at the bench's commits, newest first, until there are count
|
|
tasks. The tasks are numbered from 1, and a line says why each feature on the way was passed over. A Failure where none
|
|
counts."""
|
|
noun = bench.asked.kind.noun
|
|
tasks: list[Task] = []
|
|
passed_over: list[str] = []
|
|
for feature in shipped.found:
|
|
if len(tasks) == count:
|
|
break
|
|
# A feature passed over leaves no folder, so the next one tried takes the same number.
|
|
folder = bench.folder / "shipped-features" / str(len(tasks) + 1)
|
|
taken_out = feature.passed_over if feature.before is None else on_disk(f"take {feature.name} out of the trees in {folder}", functools.partial(without, bench, feature, feature.before, shipped.records, folder))
|
|
why = taken_out if not isinstance(taken_out, TakenOut) else why_passed_over(bench, taken_out.trees, taken_out.feature)
|
|
if isinstance(why, Failure):
|
|
return why
|
|
if isinstance(taken_out, TakenOut) and why is None:
|
|
tasks.append(Task(len(tasks) + 1, feature.name, taken_out.trees, dict.fromkeys(SIDES, feature.told), acceptance=taken_out.feature.acceptance))
|
|
continue
|
|
shutil.rmtree(folder, ignore_errors=True)
|
|
passed_over.append(f"the {noun} {feature.name}: {why}.")
|
|
bench.say(f"task-bench: passed over {passed_over[-1]}")
|
|
if not tasks:
|
|
return Failure(f"No {noun} on the base's history counts; the lines above say why.")
|
|
return Planned(tasks, [f"Passed over {line}" for line in passed_over], {})
|
|
|
|
|
|
def held(path: str) -> bool:
|
|
"""Whether path is a file or a link, which copies as a test does; a folder doesn't."""
|
|
return os.path.islink(path) or os.path.isfile(path)
|
|
|
|
|
|
class TakenOut(typing.NamedTuple):
|
|
"""A shipped feature taken out of the bench's trees: each side's tree without it, committed once, and the feature that
|
|
builds it there again."""
|
|
|
|
trees: dict[Side, str]
|
|
feature: Feature
|
|
|
|
|
|
def without(bench: Bench, shipped: Shipped, before: str, records: list[str], folder: pathlib.Path) -> TakenOut | str | Failure:
|
|
"""shipped, as the commits from before to its tip, taken out of a copy of each side's tree, under folder, where its patch and its acceptance tests go too; or why it
|
|
cannot be, which ends a sentence that opens with its name. A Failure where git fails.
|
|
|
|
Raises OSError where a file cannot be copied."""
|
|
change = (before, shipped.tip, "--", ".", *(f":(exclude,literal){path}" for path in records))
|
|
# A name that is not UTF-8 is read with U+FFFD in it. The head's tree holds no file of that name, so the file is left out.
|
|
names = bench.git("diff", "--name-only", "-z", *change, cwd=bench.checkout, errors="replace")
|
|
if isinstance(names, Failure):
|
|
return names
|
|
tests = [path for path in names.split("\x00") if path and of_tests(path) and held(os.path.join(bench.trees["head"], path))]
|
|
if not tests:
|
|
return "its change holds no test that the head holds"
|
|
patch, acceptance = folder / PATCH, folder / ACCEPTANCE
|
|
for path in tests:
|
|
os.makedirs(os.path.dirname(acceptance / path), exist_ok=True)
|
|
shutil.copy2(os.path.join(bench.trees["head"], path), acceptance / path, follow_symlinks=False)
|
|
# --binary writes a binary file's bytes, which `git apply` needs. --output has git write them to the file, since bench.git
|
|
# would read them from its output as text.
|
|
diffed = bench.git("diff", "--binary", f"--output={patch}", *PLAIN_DIFF, *change, cwd=bench.checkout)
|
|
if isinstance(diffed, Failure):
|
|
return diffed
|
|
trees: dict[Side, str] = {}
|
|
for side in SIDES:
|
|
tree = str(folder / side)
|
|
shutil.copytree(bench.trees[side], tree, symlinks=True)
|
|
# In a repository of its own, the tree is where `git apply` reads the patch's paths from, whatever repository holds the
|
|
# bench's folder. git has run in this bench already, so a failure of the second command is the patch's.
|
|
if isinstance(made := bench.git("init", "--quiet", cwd=tree), Failure):
|
|
return made
|
|
if isinstance(bench.git("apply", "-R", str(patch), cwd=tree), Failure):
|
|
return f"its revert doesn't apply at the {side}"
|
|
if failure := committed(bench.git, tree):
|
|
return failure
|
|
trees[side] = tree
|
|
return TakenOut(trees, Feature(shipped.name, shipped.told, str(patch), str(acceptance)))
|