151 lines
6.5 KiB
Python
151 lines
6.5 KiB
Python
"""A plan kept as a markdown file, todo.md, in the shape `rank_todo.py --help` shows: read, filed into, edited, finished, and ranked or checked in place."""
|
|
import dataclasses
|
|
import decimal
|
|
import pathlib
|
|
|
|
from plan_store.plans import cells, Plan, Written
|
|
from failure import Failure
|
|
from plan.todo_table import item_details, items, NoItemsTable, renames
|
|
from plan_store import markdown_edits
|
|
from plan.touches import predicted
|
|
from plan import ranking
|
|
from record_store.stores import RecordStore
|
|
from text_files.file_writes import replace_file
|
|
from plan_store.scoring import weighing_texts
|
|
|
|
# What the reader of a missing todo.md is told.
|
|
MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one"
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class FilePlan:
|
|
"""A plan kept as a markdown file at path. 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, comment: str | None = 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 rank(self) -> ranking.Ranked | Failure:
|
|
"""Ranks the file in place, writing it where ranking changed it. The caller prints `reported`'s lines."""
|
|
texts = self.texts()
|
|
if isinstance(texts, Failure):
|
|
return texts
|
|
ranked = ranking.rank(*texts, self.floor)
|
|
if isinstance(ranked, Failure):
|
|
return ranked
|
|
if ranked.text != texts[0] and (unwritten := self.replaced(ranked.text)):
|
|
return unwritten
|
|
return ranked
|
|
|
|
def check(self) -> list[str]:
|
|
"""Why `rank_todo.py --check` fails on the file, empty when it passes: the file is not ranked, an item scores under the bar, or touch-predictions cannot read an item's `Touches:` list."""
|
|
texts = self.texts()
|
|
if isinstance(texts, Failure):
|
|
return [texts.reason]
|
|
ranked = ranking.rank(*texts, self.floor)
|
|
if isinstance(ranked, Failure):
|
|
return [ranked.reason]
|
|
unranked = [] if ranked.text == texts[0] else [f"{self.path}: not ranked; run rank_todo.py on it"]
|
|
return unranked + [f"{self.path}: {line}" for line in ranked.under_bar + unreadable_touches(texts[0])]
|
|
|
|
def reported(self, ranked: ranking.Ranked) -> list[str]:
|
|
"""Ranking's notes and under-bar lines, each prefixed with the file's path, as a tool prints them on stderr."""
|
|
return [f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar]
|
|
|
|
def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure:
|
|
"""Writes ranked's text to the file."""
|
|
return self.replaced(ranked.text) or Written(id_, tuple(self.reported(ranked)))
|
|
|
|
def replaced(self, text: str) -> Failure | None:
|
|
unwritten = replace_file(self.path.resolve(), text.encode("utf-8"))
|
|
return Failure(f"{self.path}: {unwritten.reason}") if unwritten else None
|
|
|
|
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
|
|
weighing = weighing_texts(self.goals, self.decisions, self.history)
|
|
return weighing if isinstance(weighing, Failure) else (plan, *weighing)
|
|
|
|
|
|
def unreadable_touches(todo: str) -> list[str]:
|
|
"""One line per item whose `Touches:` list touch-predictions cannot read, saying why. Every item is read, not only the next release's: a later item moves into the next release with its detail, and the list is fixed most cheaply where it was written."""
|
|
details = item_details(todo)
|
|
if isinstance(details, Failure):
|
|
return [details.reason]
|
|
return [f"item {id_}: {read.reason}" for id_, detail in details.items() if isinstance(read := predicted(detail), Failure)]
|
|
|
|
|
|
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 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")
|