"""The one way a tool reads or writes a project's plan: through the store its config names. The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store. A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends.""" import dataclasses import decimal import pathlib import typing from release_plan.todo_table import BLOCKED_BY, Item, item_details, items, MOVES, NoItemsTable, renames from failure import Failure from git_cli.git_repo import file_at, git, Git from record_store.stores import goals_store, store as record_store, RecordStore from plan_store import markdown_edits from project_config.settings import ProjectConfig from release_plan import ranking from release_plan.release import Release from text_files.file_writes import replace_file TAGLINE = "Tagline" # What a caller may set on an item, each as text in the format `rank_todo.py --help` states for the cell of that name. TAGLINE is the Item cell, bold or not. FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES) # What the reader of a missing todo.md is told. MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one" # What the reader of a missing or empty goals file is told. GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience" @dataclasses.dataclass(frozen=True) class Plan: """A plan as one read found it.""" # Each item with its detail, in the order the backend supplies: by release and then by rank for a markdown file, by backlog rank for a tracker. items: list[Item] # The releases the plan marks renamed. Such a release holds no item because its items moved, not because it is finished. renamed: frozenset[Release] = frozenset() @dataclasses.dataclass(frozen=True) class Written: """A write that landed.""" id: int # What the backend says of the plan after the write, for stderr, such as an item now under the bar. notes: tuple[str, ...] = () class PlanStore(typing.Protocol): """A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` reads and files, and fails an edit or a finish until todo.md's items 382 and 383. A write that fails leaves the plan as it was, except where its Failure says a tracker may hold the item all the same, as when Jira's answer to a new issue is lost.""" @property def label(self) -> str: """What a message calls the plan, such as its path.""" @property def tracked(self) -> str | None: """The plan's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a tracker.""" def read(self) -> Plan | Failure: """The plan as it stands. A NoItemsTable where the project has not set one up.""" def add(self, fields: dict[str, str], detail: str) -> Written | Failure: """Files an item under an ID the backend picks. fields holds each of FIELDS the caller sets; detail may be empty.""" def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure: """Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release.""" def finish(self, id_: int) -> Written | Failure: """Removes item id_ with its detail.""" @dataclasses.dataclass(frozen=True) class FilePlan: """A plan kept as a markdown file at path, in the shape `rank_todo.py --help` shows. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history.""" path: pathlib.Path tracked: str | None goals: RecordStore decisions: RecordStore history: RecordStore # The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much. floor: decimal.Decimal @property def label(self) -> str: return str(self.path) def read(self) -> Plan | Failure: if not self.path.exists(): return NoItemsTable(f"{self.path}: not found; {MISSING}") text = read_text(self.path, MISSING) return text if isinstance(text, Failure) else plan_of(text) def add(self, fields: dict[str, str], detail: str) -> Written | Failure: texts = self.texts() if isinstance(texts, Failure): return texts filed = markdown_edits.added(texts[0], cells(fields), detail, self.label) return filed if isinstance(filed, Failure) else self.kept(*filed, texts) def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure: texts = self.texts() if isinstance(texts, Failure): return texts text = markdown_edits.edited(texts[0], id_, cells(fields), detail, self.label) return text if isinstance(text, Failure) else self.kept(id_, text, texts) def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure: """Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above.""" ranked = ranking.rank(text, *texts[1:], self.floor) if isinstance(ranked, Failure): return ranked # The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar. if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]: return Failure(under[0]) return self.written(id_, ranked) def finish(self, id_: int) -> Written | Failure: texts = self.texts() if isinstance(texts, Failure): return texts text = markdown_edits.finished(texts[0], id_, self.label) if isinstance(text, Failure): return text ranked = ranking.rank(text, *texts[1:], self.floor) return ranked if isinstance(ranked, Failure) else self.written(id_, ranked) def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure: """Writes ranked's text to the file.""" unwritten = replace_file(self.path.resolve(), ranked.text.encode("utf-8")) if unwritten: return Failure(f"{self.path}: {unwritten.reason}") return Written(id_, tuple(f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar)) def texts(self) -> tuple[str, str, str, str] | Failure: """What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure.""" plan = read_text(self.path, MISSING) if isinstance(plan, Failure): return plan goals = self.goals.read() if isinstance(goals, Failure): return goals if not goals: return Failure(f"{self.goals.label}: missing or empty; {GOALS_HINT}") decisions = self.decisions.read() if isinstance(decisions, Failure): return decisions history = self.history.read() return history if isinstance(history, Failure) else (plan, goals, decisions, history) def store(config: ProjectConfig) -> PlanStore: """The store config names for the plan.""" if config.epic is None: return file_plan(config) # Imported here, since jira_epic builds on this module's Plan and Written. from plan_store.jira_epic import JiraPlan # load refuses a config that names an epic and no env-file. assert config.env_file is not None return JiraPlan(config.epic, config.env_file) def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan: """The markdown file config names as its plan, for a tool that works on the file itself, as ranking does. path stands in for the configured one where given.""" return FilePlan(path or config.paths["plan"], config.tracked("plan"), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), config.readability_floor) def held_at(revision: str, plan: PlanStore, cwd: str, run: Git = git) -> Plan | Failure: """plan at revision, read in the checkout at cwd, where its commits hold the plan; else as it stands. A NoItemsTable where there is no plan.""" if plan.tracked is None: return plan.read() text = file_at(revision, plan.tracked, cwd, run) return text if isinstance(text, Failure) else plan_of(text) def plan_of(todo: str) -> Plan | Failure: """The plan a todo.md's text holds.""" found = items(todo) if isinstance(found, Failure): return found details = item_details(todo) if isinstance(details, Failure): return details marked = renames(todo) if isinstance(marked, Failure): return marked return Plan([dataclasses.replace(item, detail=details.get(item.id, "")) for item in found], frozenset(marked)) def cells(fields: dict[str, str]) -> dict[str, str]: """fields by the items table's column names.""" unknown = set(fields) - set(FIELDS) if unknown: # A programming error, so nothing catches it: a caller takes its fields from FIELDS. raise ValueError(f"{', '.join(sorted(unknown))}: not a field; the fields are {', '.join(FIELDS)}") return {"Item" if name == TAGLINE else name: value for name, value in fields.items()} def read_text(path: pathlib.Path, missing: str) -> str | Failure: """path's text; where it is missing, a Failure saying missing.""" try: return path.read_text(encoding="utf-8") except FileNotFoundError: return Failure(f"{path}: not found; {missing}") except OSError as failure: return Failure(f"{path}: {failure.strerror}") except UnicodeDecodeError: return Failure(f"{path}: not UTF-8")