Answer architecture round 1: 4 🔴, 5 🟡 (0 misread); one-way plan packages with a plan core and an Atlassian client, one parse and print of an item's cells, a pure chunk-start decision, a settings table, one plan read and one standing per pick, one config load in chunk-pr, notifier backends in notifier, and the bin regroup filed as item 392

This commit is contained in:
2026-11-16 14:47:46 +01:00
parent 3f7d85c48e
commit f58250d0ce
103 changed files with 1299 additions and 1044 deletions
+3 -3
View File
@@ -1,10 +1,10 @@
"""What every plan backend must hold, as tests. A backend's test case inherits PlanStoreContract and unittest.TestCase, and builds its store in new_store. record_store.contract is its twin for records."""
import typing
from release_plan.todo_table import BLOCKED_BY, Item, MOVES
from plan.todo_table import BLOCKED_BY, Item, MOVES
from failure import Failure
from plan_store.stores import Plan, PlanStore, TAGLINE, Written
from release_plan.release import release_of
from plan_store.plans import Plan, PlanStore, TAGLINE, Written
from plan.release import release_of
FIRST = {"Release": "0.1.0", TAGLINE: "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", MOVES: "1 by 9"}
SECOND = {"Release": "0.2.0", TAGLINE: "Ship the later thing.", "L": "2", "E": "1", "I": "1", "S": "2", MOVES: "1 by 8", "Exempt": "owner"}
+2 -2
View File
@@ -2,9 +2,9 @@
import dataclasses
from plan_store.markdown_edits import bold_cell, plain
from plan_store.stores import cells, Plan, Written
from plan_store.plans import cells, Plan, Written
from failure import Failure
from release_plan.todo_table import Item, parse_row, SHAPE, Table
from plan.todo_table import Item, parse_row, SHAPE, Table
@dataclasses.dataclass
+26 -81
View File
@@ -3,30 +3,24 @@
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a person filed holds none, and reads as an item without scores.
`add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, but never its links. Of an issue a person filed it sets only the scores, with a comment that tells the team why."""
import base64
import dataclasses
import pathlib
import re
import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from release_plan.todo_table import BLOCKED_BY, EXEMPTIONS, is_exempt, Item, MOVES, parse_ids, parse_moves, parse_scores, SHAPE
from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from plan.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SHAPE
from plan_store.markdown_edits import bold_cell, plain, unfit_text
from plan_store.stores import cells, Plan, Written
from plan_store.plans import cells, Plan, Written
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from failure import Failure
from rest_client import json_request
from release_plan.release import parsed, Release, tagged
from release_plan import ranking
from rest_client.env_file import read_env
from plan.release import parsed, Release, tagged
from plan import ranking
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
# The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}.
PROPERTY = "plan-item"
ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)")
# Seconds each connect and each read may wait.
TIMEOUT = 30
PAGE = 100
# The pages one read asks for at most, so an answer that never names a last page ends the read.
MAX_PAGES = 100
@@ -50,30 +44,12 @@ SET_SCORES = tuple(name for name in SHAPE.score_columns if name not in SHAPE.der
# The fields of PROPERTY's value that an edit may set.
SCORED = (*SET_SCORES, MOVES, "Exempt")
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
class ReadsScoring(typing.Protocol):
def read(self) -> ranking.Scoring | Failure:
"""The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give."""
def http_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
def error_message(answer: object) -> str:
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
if not isinstance(answer, dict):
return ""
messages, errors = answer.get("errorMessages"), answer.get("errors")
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
return "; ".join(text for text in found if isinstance(text, str))
@dataclasses.dataclass(frozen=True)
class Issue:
"""A child issue as Jira answered it, checked to hold what an item is read from."""
@@ -96,7 +72,7 @@ class JiraPlan:
"""The plan under epic, read and written with the credentials env_file holds."""
epic: Epic
env_file: pathlib.Path
http: Http = http_json
http: Http = jira_json
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
# How a finished item moves; None where the config doesn't say, and then `finish` is a Failure.
@@ -285,27 +261,16 @@ def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failu
if unfit := unfit_text(summary, detail):
return unfit
release = named.get("Release", "")
version = parsed(release)
if version is None:
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
# Named so the shared messages read "item to file's L": they open with "item" and an ID, which this item has none of yet.
levels = parse_scores("to file", named, SHAPE.score_columns)
if isinstance(levels, Failure):
return levels
moves, exempt = named.get(MOVES, ""), named.get("Exempt", "")
if isinstance(parsed_moves := parse_moves("to file", moves), Failure):
return parsed_moves
if not is_exempt(exempt):
return Failure(f"the item's Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
blockers = parse_ids(named.get(BLOCKED_BY, ""))
if blockers is None:
return Failure(f"the item's {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
checked = item_fields(named | {"Release": release}, "the item to file")
if isinstance(checked, Failure):
return checked
assert checked.release is not None, "item_fields refuses an empty Release"
project = project_of(epic.key)
issue_fields: dict[str, typing.Any] = {"project": {"key": project}, "parent": {"key": epic.key}, "issuetype": {"name": ISSUE_TYPE}, "summary": summary}
if exempt == SECURITY:
if checked.exempt == SECURITY:
issue_fields["labels"] = [SECURITY]
value = levels | {MOVES: moves, "Exempt": exempt, FILED_BY[0]: FILED_BY[1]}
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers), Item(0, version, exempt, summary, levels, parsed_moves, blockers))
value = checked.scores | {MOVES: named.get(MOVES, ""), "Exempt": checked.exempt, FILED_BY[0]: FILED_BY[1]}
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in checked.blocked_by), Item(0, checked.release, checked.exempt, summary, checked.scores, checked.moves, checked.blocked_by))
def filed_score(item: Item, scoring: ranking.Scoring) -> float | Failure:
@@ -332,14 +297,13 @@ def placing(answered: list[object], new: Item, value: float, scoring: ranking.Sc
scored = scores(issue.key, issue.scores)
if isinstance(scored, Failure):
return scored
levels, moves, exempt = scored
if missing := next((name for name in SET_SCORES if name not in levels), None):
if missing := next((name for name in SET_SCORES if name not in scored.scores), None):
return Failure(f"{issue.key} holds no {missing}")
# Only the scores and the moves change a score.
other = ranking.item_score(dataclasses.replace(new, scores=levels, moves=moves), scoring, issue.key)
other = ranking.item_score(dataclasses.replace(new, scores=scored.scores, moves=scored.moves), scoring, issue.key)
if isinstance(other, Failure):
return other
if (ranking.FIRST.get(exempt, len(ranking.FIRST)), -other) > place:
if (ranking.FIRST.get(scored.exempt, len(ranking.FIRST)), -other) > place:
return issue.key
return None
@@ -376,21 +340,19 @@ def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment
if unfit := unfit_text(named.get("Item", ""), detail or ""):
return unfit
release = named.get("Release")
if release is not None and parsed(release) is None:
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
if not is_exempt(named.get("Exempt", "")):
return Failure(f"the item's Exempt {named['Exempt']!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if isinstance(checked := item_fields({name: named[name] for name in ("Release", "Exempt") if name in named}, "the item"), Failure):
return checked
if any(name in named for name in SCORED):
texts = {name: str(value) for name, value in held.items()} | {name: named[name] for name in SCORED if name in named}
scored = scores(issue.key, texts)
if isinstance(scored, Failure):
return scored
if scored[0] and any(name not in scored[0] for name in SET_SCORES):
if scored.scores and any(name not in scored.scores for name in SET_SCORES):
return Failure(f"{issue.key} would hold some of {', '.join(SET_SCORES)} and not the rest: set them together")
value = held | scored[0] | {MOVES: texts.get(MOVES, ""), "Exempt": scored[2]}
value = held | scored.scores | {MOVES: texts.get(MOVES, ""), "Exempt": scored.exempt}
body["properties"] = [{"key": PROPERTY, "value": value}]
if own and (scored[2] == SECURITY) != (held.get("Exempt") == SECURITY):
body["update"] = {"labels": [{"add" if scored[2] == SECURITY else "remove": SECURITY}]}
if own and (scored.exempt == SECURITY) != (held.get("Exempt") == SECURITY):
body["update"] = {"labels": [{"add" if scored.exempt == SECURITY else "remove": SECURITY}]}
return Revision(body, release)
@@ -428,14 +390,6 @@ def project_of(key: str) -> str:
return key.rpartition("-")[0]
def basic_auth(env_file: pathlib.Path) -> str | Failure:
"""The Authorization header for the email and API token that env_file holds."""
values = read_env(env_file, KEYS, "an API token")
if isinstance(values, Failure):
return values
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure:
"""The epic's open child issues in backlog order, which the team ranks, apart from where add ranks an issue it files. An issue in a done status is a finished item, so it is no longer in the plan."""
# The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart.
@@ -518,7 +472,7 @@ def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
if isinstance(scored, Failure):
return scored
blockers = {number(key) for key in issue.blockers if project_of(key) == project}
return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "")
return Item(issue.number, release, scored.exempt, bold_cell(issue.summary), scored.scores, scored.moves, tuple(sorted(blockers & ids)), "")
def earliest_release(names: tuple[str, ...]) -> Release | None:
@@ -527,18 +481,9 @@ def earliest_release(names: tuple[str, ...]) -> Release | None:
return min(releases, default=None)
def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.Any] | Failure:
def scores(key: str, held: object) -> ItemFields | Failure:
"""The scores, Moves and Exempt that an issue's PROPERTY value holds, each in the format the items table of a todo.md takes."""
if not isinstance(held, dict):
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
named = {name: str(value) for name, value in held.items()}
levels = parse_scores(key, named, SHAPE.score_columns)
if isinstance(levels, Failure):
return levels
moves = parse_moves(key, named.get(MOVES, ""))
if isinstance(moves, Failure):
return moves
exempt = named.get("Exempt", "")
if not is_exempt(exempt):
return Failure(f"{key}'s issue property {PROPERTY} holds the Exempt {exempt!r}, which is not empty or one of {', '.join(EXEMPTIONS[1:])}")
return levels, moves, exempt
named = {name: str(value) for name, value in held.items() if name in (*SHAPE.score_columns, MOVES, "Exempt")}
return item_fields(named, f"item {key}")
+4 -4
View File
@@ -1,9 +1,9 @@
"""The text edits behind the markdown plan: filing an item in todo.md, changing one and removing one. Each returns new text; ranking.rank then orders the table and details and writes the derived cells."""
import re
from release_plan.todo_table import cells, DETAILS, item_details, items_table, Table
from plan.todo_table import cells, detail_heading, DETAILS, item_details, items_table, Table, tagline_text
from failure import Failure
from release_plan.ranking import stated
from plan.ranking import stated
# A line that would end ## Details (##) or could open another item's detail (###).
HEADING = re.compile(r"^#{2,3} ", re.M)
@@ -47,7 +47,7 @@ def edited(todo: str, id_: int, named: dict[str, str], detail: str | None, label
if isinstance(details, Failure):
return details
row = dict(zip(table.columns, held))
tagline = plain(named["Item"]) if "Item" in named else plain(row["Item"]).replace("\\|", "|")
tagline = plain(named["Item"]) if "Item" in named else tagline_text(row["Item"])
kept = details.get(id_, "") if detail is None else detail
if unfit := unfit_text(tagline, "" if detail is None else detail):
return unfit
@@ -90,7 +90,7 @@ def with_detail(text: str, id_: int, tagline: str, detail: str) -> str:
"""text with detail first under ## Details, headed by id_ and tagline; text itself where detail is blank."""
if not detail.strip():
return text
entry = f"### {id_}. {tagline}\n\n{detail.strip()}\n"
entry = f"{detail_heading(id_, tagline)}\n\n{detail.strip()}\n"
section = DETAILS.search(text)
if section is None:
return text.rstrip("\n") + f"\n\n## Details\n\n{entry}"
+63
View File
@@ -0,0 +1,63 @@
"""What every plan backend reads and writes: a Plan, a Written, the PlanStore protocol they all meet, and the fields a caller may set on an item."""
import dataclasses
import typing
from plan.todo_table import BLOCKED_BY, Item, MOVES
from failure import Failure
from plan.release import Release
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)
@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` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish 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, comment: str | None = 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.
comment tells the plan's other readers why, in the project's language. A tracker posts it on the item's issue; a backend with no place for comments drops it."""
def finish(self, id_: int) -> Written | Failure:
"""Removes item id_ with its detail."""
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()}
+39
View File
@@ -0,0 +1,39 @@
"""The goal weights a plan is ranked by, read from the goals file, the decision log and the comprehension history, for the markdown plan and for the scoring of a plan in Jira."""
import dataclasses
import decimal
from failure import Failure
from project_config.settings import JiraScoring
from plan import ranking
from record_store.stores import RecordStore
# 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 StatedScoring:
"""The scoring of a plan in Jira: the formula and bar the project's config states, with goal weights that ranking reads from the goals file, the decision log and the comprehension history."""
stated: JiraScoring
goals: RecordStore
decisions: RecordStore
history: RecordStore
floor: decimal.Decimal
def read(self) -> ranking.Scoring | Failure:
weighing = weighing_texts(self.goals, self.decisions, self.history)
return weighing if isinstance(weighing, Failure) else ranking.config_scoring(self.stated.formula, self.stated.bar, *weighing, self.floor)
def weighing_texts(goals: RecordStore, decisions: RecordStore, history: RecordStore) -> tuple[str, str, str] | Failure:
"""What ranking weighs the goals by: the goals file, the decision log and the comprehension history. The last two are empty when missing; a goals file that is missing or empty is a Failure."""
goals_text = goals.read()
if isinstance(goals_text, Failure):
return goals_text
if not goals_text:
return Failure(f"{goals.label}: missing or empty; {GOALS_HINT}")
decisions_text = decisions.read()
if isinstance(decisions_text, Failure):
return decisions_text
history_text = history.read()
return history_text if isinstance(history_text, Failure) else (goals_text, decisions_text, history_text)
+8 -201
View File
@@ -1,182 +1,24 @@
"""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.
The config's `plan` setting names the backend. A path names a markdown file, todo.md, which `todo_md` keeps. `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
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `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 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 project_config.settings import JiraScoring, ProjectConfig
from plan_store import markdown_edits
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` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish 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, comment: str | None = 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.
comment tells the plan's other readers why, in the project's language. A tracker posts it on the item's issue; a backend with no place for comments drops it."""
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, 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 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
weighing = weighing_texts(self.goals, self.decisions, self.history)
return weighing if isinstance(weighing, Failure) else (plan, *weighing)
@dataclasses.dataclass(frozen=True)
class StatedScoring:
"""The scoring of a plan in Jira: the formula and bar the project's config states, with goal weights that ranking reads from the goals file, the decision log and the comprehension history."""
stated: JiraScoring
goals: RecordStore
decisions: RecordStore
history: RecordStore
floor: decimal.Decimal
def read(self) -> ranking.Scoring | Failure:
weighing = weighing_texts(self.goals, self.decisions, self.history)
return weighing if isinstance(weighing, Failure) else ranking.config_scoring(self.stated.formula, self.stated.bar, *weighing, self.floor)
def weighing_texts(goals: RecordStore, decisions: RecordStore, history: RecordStore) -> tuple[str, str, str] | Failure:
"""What ranking weighs the goals by: the goals file, the decision log and the comprehension history. The last two are empty when missing; a goals file that is missing or empty is a Failure."""
goals_text = goals.read()
if isinstance(goals_text, Failure):
return goals_text
if not goals_text:
return Failure(f"{goals.label}: missing or empty; {GOALS_HINT}")
decisions_text = decisions.read()
if isinstance(decisions_text, Failure):
return decisions_text
history_text = history.read()
return history_text if isinstance(history_text, Failure) else (goals_text, decisions_text, history_text)
from plan_store.todo_md import FilePlan, plan_of
from record_store.stores import goals_store, store as record_store
from plan_store.jira_epic import JiraPlan
from plan_store.plans import Plan, PlanStore
from project_config.settings import ProjectConfig
from plan_store.scoring import StatedScoring
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
# load refuses a config that names an epic and no formula or bar.
@@ -196,38 +38,3 @@ def held_at(revision: str, plan: PlanStore, cwd: str, run: Git = git) -> Plan |
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")
+10 -28
View File
@@ -9,13 +9,13 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import DEFAULT_FLOOR, Epic, Finish
from release_plan.todo_table import EXEMPTIONS
from plan.todo_table import EXEMPTIONS
from failure import Failure
from plan_store import jira_epic
from plan_store.stores import Plan, Written
from release_plan import ranking
from plan_store.plans import Plan, Written
from plan import ranking
from adf_codec.convert import Refused
from release_plan.release import release_of
from plan.release import release_of
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql"
@@ -144,7 +144,7 @@ class JiraPlan(unittest.TestCase):
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
def test_an_exempt_out_of_format_fails_naming_the_reasons_it_may_hold(self):
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("ABC-34's issue property plan-item holds the Exempt 'because', which is not empty or one of decision, defect, owner, principle, question, security"))
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("item ABC-34's Exempt 'because' is not empty or one of decision, defect, owner, principle, question, security"))
def test_reads_every_page(self):
self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}]
@@ -315,9 +315,9 @@ class Filing(unittest.TestCase):
def test_each_field_out_of_format_fails_saying_how(self):
cases = (
({"Tagline": "** **"}, "the item has no tagline"),
({"L": "9"}, "item to file's L '9' is not a whole number from 1 to 4"),
({"Exempt": "whim"}, f"the item's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Blocked by": "ABC-34"}, "the item's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
({"L": "9"}, "the item to file's L '9' is not a whole number from 1 to 4"),
({"Exempt": "whim"}, f"the item to file's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Blocked by": "ABC-34"}, "the item to file's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
)
for change, reason in cases:
with self.subTest(change=change):
@@ -334,7 +334,7 @@ class Filing(unittest.TestCase):
self.add(FIELDS | {"Colour": "red"})
def test_an_item_without_a_release_fails_naming_the_field(self):
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item's Release '' is not a version such as 1.2.0"))
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item to file's Release '' is not a semver version, such as 1.2.0"))
def test_a_detail_that_does_not_convert_fails_before_any_request(self):
self.to_adf = lambda markdown: Failure("docker is not running") # type: ignore[method-assign]
@@ -598,7 +598,7 @@ class Editing(unittest.TestCase):
({"L": "9"}, None, "item ABC-34's L '9' is not a whole number from 1 to 4"),
({"Moves": "much"}, None, "item ABC-34's Moves 'much' is not"),
({"Exempt": "tired"}, None, f"the item's Exempt 'tired' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Release": "soon"}, None, "the item's Release 'soon' is not a version such as 1.2.0"),
({"Release": "soon"}, None, "the item's Release 'soon' is not a semver version, such as 1.2.0"),
({"Tagline": " "}, None, "the item has no tagline"),
({"Tagline": "Count\nruns."}, None, "the tagline holds a line break; keep it on one line"),
({}, "## Why", "the detail holds a ## or ### heading"),
@@ -724,24 +724,6 @@ class Finishing(unittest.TestCase):
self.assertEqual(self.calls, [])
class Requests(unittest.TestCase):
def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self):
with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent:
self.assertEqual(jira_epic.http_json("POST", SEARCH, AUTHORIZATION, {"jql": "x"}), {"issues": []})
sent.assert_called_once_with("POST", SEARCH, AUTHORIZATION, {"jql": "x"}, 30, jira_epic.error_message)
def test_reads_jiras_messages_from_an_error_answer(self):
cases = (
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
({"errorMessages": "One.", "errors": ["Two."]}, ""),
({"errorMessages": [7, "One."]}, "One."),
(["One."], ""),
)
for answer, message in cases:
with self.subTest(answer=answer):
self.assertEqual(jira_epic.error_message(answer), message)
if __name__ == "__main__":
unittest.main()
+22 -22
View File
@@ -15,16 +15,16 @@ from plan_store.contract import FIRST, MOVES, PlanStoreContract, SECOND
from plan_store.jira_epic import JiraPlan
from plan_store.fakes import MemoryPlan
from record_store.fakes import MemoryStore
from release_plan.todo_table import NoItemsTable
from release_plan.test_ranking import README, SCORED, VOID
from release_plan.release import release_of
from plan_store import stores
from plan.todo_table import NoItemsTable
from plan_store import plans, scoring, stores, todo_md
from plan.test_ranking import README, SCORED, VOID
from plan.release import release_of
EMPTY = "# todo\n\n## Scoring\n\n`Score = 100 * V / 2**S`\n\n`Bar = 2`\n\n`Next ID = 1`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
class MemoryPlanContract(PlanStoreContract, unittest.TestCase):
def new_store(self) -> stores.PlanStore:
def new_store(self) -> plans.PlanStore:
return MemoryPlan()
@@ -32,10 +32,10 @@ class FilePlanContract(PlanStoreContract, unittest.TestCase):
def setUp(self) -> None:
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
def new_store(self) -> stores.FilePlan:
def new_store(self) -> todo_md.FilePlan:
(self.folder / "todo.md").write_text(EMPTY)
(self.folder / "README.md").write_text(README)
return stores.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
return todo_md.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
class FilePlan(FilePlanContract):
@@ -62,7 +62,7 @@ class FilePlan(FilePlanContract):
def test_an_edited_tagline_heads_the_detail_too(self):
store = self.new_store()
id_ = self.filed(store, FIRST, "Why it counts.")
store.edit(id_, {stores.TAGLINE: "Count `a | b` runs."}, None)
store.edit(id_, {plans.TAGLINE: "Count `a | b` runs."}, None)
text = (self.folder / "todo.md").read_text()
self.assertIn("| **Count `a \\| b` runs.** |", text)
self.assertIn(f"### {id_}. Count `a | b` runs.\n\nWhy it counts.\n", text)
@@ -84,7 +84,7 @@ class FilePlan(FilePlanContract):
self.assertEqual(self.filed(store, FIRST), 10)
todo.write_text("".join(line.replace("| 4 | 1 | 1 by 9 |", "| 4 | 10 | 1 by 9 |") if line.startswith("| 10 ") else line for line in todo.read_text().splitlines(keepends=True)))
written = store.edit(first, {"E": "2"}, None)
assert isinstance(written, stores.Written), written
assert isinstance(written, plans.Written), written
self.assertIn("item 10 ", written.notes[0])
def test_an_id_it_holds_no_item_for_fails_naming_the_file(self):
@@ -118,7 +118,7 @@ class FilePlan(FilePlanContract):
def test_reads_the_releases_marked_renamed(self):
store = self.new_store()
(self.folder / "todo.md").write_text(EMPTY + "\n## Renamed\n\n- 0.2.1 renamed to 0.3.0\n")
self.assertEqual(store.read(), stores.Plan([], frozenset({release_of("0.2.1")})))
self.assertEqual(store.read(), plans.Plan([], frozenset({release_of("0.2.1")})))
def test_a_field_it_does_not_know_is_a_programming_error(self):
with self.assertRaises(ValueError):
@@ -130,9 +130,9 @@ class FilePlan(FilePlanContract):
id_ = self.filed(store, FIRST)
before = (self.folder / "todo.md").read_text()
broken, split = "the tagline holds a line break; keep it on one line", "the detail holds a ## or ### heading, which would split ## Details; use #### or drop the #s"
self.assertEqual(store.add(FIRST | {stores.TAGLINE: "Count\nthe runs."}, ""), Failure(broken))
self.assertEqual(store.add(FIRST | {plans.TAGLINE: "Count\nthe runs."}, ""), Failure(broken))
self.assertEqual(store.add(FIRST, "## Why\n"), Failure(split))
self.assertEqual(store.edit(id_, {stores.TAGLINE: "Count\nthe runs."}, None), Failure(broken))
self.assertEqual(store.edit(id_, {plans.TAGLINE: "Count\nthe runs."}, None), Failure(broken))
self.assertEqual(store.edit(id_, {}, "### Why\n"), Failure(split))
self.assertEqual((self.folder / "todo.md").read_text(), before)
@@ -157,7 +157,7 @@ class FilePlan(FilePlanContract):
(self.folder / "README.md").write_text(README.replace(VOID, ""))
kept, finished = self.filed(store, FIRST | {MOVES: "code health by 1"}), self.filed(store, SECOND)
row = [line for line in (self.folder / "todo.md").read_text().splitlines() if line.startswith(f"| {kept} ")]
self.assertIsInstance(store.finish(finished), stores.Written)
self.assertIsInstance(store.finish(finished), plans.Written)
self.assertIn(row[0], (self.folder / "todo.md").read_text())
return row[0]
self.assertNotEqual(health_row("6.0"), health_row("7.0"))
@@ -200,7 +200,7 @@ class Store(unittest.TestCase):
def test_a_path_picks_the_markdown_file(self):
config = self.config()
picked = stores.store(dataclasses.replace(config, paths=config.paths | {"plan": pathlib.Path("/checkout/todo.md")}))
self.assertEqual((type(picked), picked.label, picked.tracked), (stores.FilePlan, "/checkout/todo.md", "todo.md"))
self.assertEqual((type(picked), picked.label, picked.tracked), (todo_md.FilePlan, "/checkout/todo.md", "todo.md"))
def test_the_markdown_file_ranks_with_the_configs_floor(self):
self.assertEqual(stores.file_plan(self.config(readability_floor=decimal.Decimal("6.5")), pathlib.Path("/checkout/todo.md")).floor, decimal.Decimal("6.5"))
@@ -218,26 +218,26 @@ class Store(unittest.TestCase):
def test_an_epic_scores_by_the_configs_formula_and_bar_and_the_projects_records(self):
config = self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_scoring=JiraScoring("V / 2**S", 1.5), readability_floor=decimal.Decimal("6.5"))
picked = stores.store(config)
self.assertEqual(picked.scoring, stores.StatedScoring(JiraScoring("V / 2**S", 1.5), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), decimal.Decimal("6.5")))
self.assertEqual(picked.scoring, scoring.StatedScoring(JiraScoring("V / 2**S", 1.5), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), decimal.Decimal("6.5")))
class StatedScoring(unittest.TestCase):
def test_weighs_the_goals_the_goals_file_holds(self):
scoring = stores.StatedScoring(JiraScoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
assert not isinstance(scoring, Failure), scoring
self.assertEqual((scoring.bar, list(scoring.goals)), (1.5, ["1", "2", "2.1"]))
weighed = scoring.StatedScoring(JiraScoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
assert not isinstance(weighed, Failure), weighed
self.assertEqual((weighed.bar, list(weighed.goals)), (1.5, ["1", "2", "2.1"]))
def test_weighs_code_health_by_the_history_and_the_floor_it_is_given(self):
for floor, under in ((DEFAULT_FLOOR, True), (decimal.Decimal("6.0"), False)):
with self.subTest(floor=floor):
scoring = stores.StatedScoring(JiraScoring("V", 1), MemoryStore("## Goals\n\n1. **Achieve:** A.\n"), MemoryStore(), MemoryStore(SCORED.format(overall="6.99")), floor).read()
assert not isinstance(scoring, Failure), scoring
self.assertEqual(scoring.weights["code health"] > scoring.weights["1"] * 2, under)
weighed = scoring.StatedScoring(JiraScoring("V", 1), MemoryStore("## Goals\n\n1. **Achieve:** A.\n"), MemoryStore(), MemoryStore(SCORED.format(overall="6.99")), floor).read()
assert not isinstance(weighed, Failure), weighed
self.assertEqual(weighed.weights["code health"] > weighed.weights["1"] * 2, under)
def test_a_goals_file_that_is_empty_or_cannot_be_read_fails(self):
for goals, reason in ((MemoryStore(), "the record in memory: missing or empty"), (MemoryStore(fails="Jira answered 403"), "Jira answered 403")):
with self.subTest(reason=reason):
read = stores.StatedScoring(JiraScoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
read = scoring.StatedScoring(JiraScoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
assert isinstance(read, Failure), read
self.assertTrue(read.reason.startswith(reason), read.reason)
+141
View File
@@ -0,0 +1,141 @@
"""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 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, or an item scores under the bar."""
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]
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 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")