151 lines
6.5 KiB
Python
151 lines
6.5 KiB
Python
"""What the preflight gathers, and the pure choices its steps act on; facts.render states it."""
|
|
import dataclasses
|
|
import pathlib
|
|
import re
|
|
import typing
|
|
|
|
from todo_table import chunk_item, Item, item_details, items, LastCut
|
|
from failure import Failure
|
|
|
|
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
|
|
Forge = typing.Literal["gh", "tea"]
|
|
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
|
|
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Ran:
|
|
"""A command that ran to its end: its exit code and what it printed."""
|
|
code: int
|
|
stdout: str
|
|
stderr: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Plan:
|
|
"""The default branch's todo.md items, and `first`: the item the next chunk takes first."""
|
|
items: list[Item]
|
|
first: Item
|
|
# first's tagline and detail.
|
|
text: str
|
|
|
|
@property
|
|
def branch(self) -> str:
|
|
"""The branch first's worktree is on."""
|
|
return f"item-{self.first.id}"
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class NoItem:
|
|
"""Why the plan names no item for the next chunk, as a sentence the worker reads."""
|
|
why: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Worktree:
|
|
path: pathlib.Path
|
|
# How it came to be, as the worker reads it.
|
|
how: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class NamedPath:
|
|
"""A tracked file or folder the item names, with how many tracked files it holds."""
|
|
span: str
|
|
files: int
|
|
# A file's lines, or why they cannot be read; None for a folder.
|
|
lines: int | Failure | None
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class ItemFacts:
|
|
"""What the preflight found or made for the plan's first item."""
|
|
plan: Plan
|
|
worktree: Worktree | Failure
|
|
# The forge whose CLI listed the open pull requests, and how it ran; None without an origin remote.
|
|
pulls: tuple[Forge, Ran | Failure] | None
|
|
named: list[NamedPath] | Failure
|
|
# Each tool run in the worktree, by its command line, and how it ran; none without a worktree.
|
|
tools: list[tuple[str, Ran | Failure]]
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Gathered:
|
|
"""Everything the preflight read and ran, for facts.render to state."""
|
|
# The default branch's ref, such as origin/main.
|
|
default: str
|
|
# Why origin reads as last fetched; None after a fetch.
|
|
note: str | None
|
|
cut: LastCut
|
|
# What was found or made for the plan's first item; else why the plan names none.
|
|
item: ItemFacts | NoItem
|
|
|
|
|
|
def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem:
|
|
"""The plan in todo, the default branch's todo.md, with the item the next chunk takes first, todo_table.chunk_item's pick; else why there is none."""
|
|
where = f"{default}'s todo.md"
|
|
if isinstance(todo, Failure):
|
|
return NoItem(f"{where} cannot be read: {todo.reason}.")
|
|
found = items(todo)
|
|
if isinstance(found, Failure):
|
|
return NoItem(f"{where} cannot be read: {found.reason}.")
|
|
if found is None:
|
|
return NoItem(f"{where} holds no items table.")
|
|
earliest = min((item.release for item in found), default=None)
|
|
stands, first = chunk_item(found, cut)
|
|
if earliest is not None and stands == "cut":
|
|
return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {cut.tag}; ask the human which release they belong to.")
|
|
gap = f"{where} holds no item for the next release after the last cut, {cut.tag}, and"
|
|
if stands == "finished":
|
|
return NoItem(f"{gap} work has landed since, so that release is finished and ready to cut, and the working loop stops here.")
|
|
if stands == "unplanned":
|
|
return NoItem(f"{gap} no work has landed since, so that release is to be planned first.")
|
|
if stands == "unknown":
|
|
return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: todo.md's texts since then, or the count of work landed since then, cannot be read. Find the next release yourself.")
|
|
if first is None:
|
|
return NoItem(f"every item of release {version(earliest)} in {where} waits." if earliest is not None else f"{where}'s items table holds no item.")
|
|
details = item_details(todo)
|
|
detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})"
|
|
return Plan(found, first, f"{first.tagline}\n\n{detail}".strip())
|
|
|
|
|
|
def version(release: tuple[int, int, int]) -> str:
|
|
return ".".join(map(str, release))
|
|
|
|
|
|
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
|
|
"""The worktree on branch, in what `git worktree list --porcelain` printed; None where none is."""
|
|
for block in porcelain.split("\n\n"):
|
|
fields = dict(line.partition(" ")[::2] for line in block.splitlines())
|
|
if fields.get("branch") == f"refs/heads/{branch}":
|
|
return pathlib.Path(fields["worktree"])
|
|
return None
|
|
|
|
|
|
def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]:
|
|
"""The git arguments that add branch's worktree at path, and how it comes to be: on the local branch, else on a new one tracking origin's, else on a new one off default."""
|
|
if local:
|
|
return ["worktree", "add", "--quiet", str(path), branch], f"added on the branch {branch}, which existed already."
|
|
if pushed:
|
|
return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"added on the new branch {branch}, made off origin/{branch}."
|
|
# --no-track: tracking the default branch would point a bare `git push` at it.
|
|
return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"added on the new branch {branch}, made off {default}."
|
|
|
|
|
|
def forge_of(origin_url: str) -> Forge:
|
|
return "gh" if "github.com" in origin_url else "tea"
|
|
|
|
|
|
def pulls_command(forge: Forge, branch: str) -> list[str]:
|
|
"""The command that lists open pull requests: gh only branch's, by number and URL; tea every one, by index, head and URL, for facts.open_pulls to pick branch's."""
|
|
if forge == "gh":
|
|
return [*PULLS_LIST["gh"], "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"]
|
|
return [*PULLS_LIST["tea"], "--fields", "index,head,url", "--output", "tsv"]
|
|
|
|
|
|
def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]:
|
|
"""Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file."""
|
|
spans = dict.fromkeys(span.removesuffix("/") for span in re.findall(r"`([^`\s]+)`", text))
|
|
held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans)
|
|
return [(span, count) for span, count in held if count]
|