"""A Jira epic's description as the record of do-epic, the tool that drives one epic. The description holds a language line, a line that caps the chunks running at once, and the sections Goals, Audience, Scoring (the formula and the bar) and Decisions. They are read and written one at a time through `EpicDescription`, and a write leaves every other line of the markdown as it was. Goals and Audience change only where the human approved in an interrupt, which `write_section` takes as `approved`; `EpicDescription` refuses the change otherwise.""" import dataclasses import re import typing from record_store.jira_description import EpicDescription from failure import Failure from text_files.markdown_text import fenced_lines from record_store.held import Held from project_config.settings import language_fault SECTIONS = ("Goals", "Audience", "Scoring", "Decisions") LANGUAGE_LINE = re.compile(r"^\*\*Language:\*\* (.*?)\s*$") # The line that caps how many of the epic's chunks run at once. Three readers, seated as the human who writes an epic's description, picked this spelling from four candidates, 2-1 over `**Parallel chunks:**`, which reads as a count of what runs now. CAP = "**Max parallel chunks:**" CAP_LINE = re.compile(rf"^{re.escape(CAP)}(.*?)\s*$") # A line that opens with CAP's words in another spelling. It is refused, since the epic would otherwise run on the cap of 1 without a word. NEAR_CAP_LINE = re.compile(r"^[\s*_>#-]*max parallel chunks", re.IGNORECASE) def read_section(text: str, name: str) -> str | Failure: """The text under the one ## name heading, up to the next heading of level 1 or 2, without the blank lines around it; empty where there is no such heading.""" span = span_of(text, name) if isinstance(span, Failure): return span return "" if span is None else "\n".join(text.splitlines()[span[0] + 1 : span[1]]).strip("\n") def with_section(text: str, name: str, body: str) -> str | Failure: """text with the one ## name section holding body, put after the others where there is none. A section that already holds body leaves text as it is.""" span = span_of(text, name) if isinstance(span, Failure): return span if any(line.startswith(("# ", "## ")) and not fenced for line, fenced in fenced_lines(body)): return Failure(f"the body of ## {name} holds a level 1 or 2 heading, which would start another section") if span is None: return text.rstrip("\n") + "\n\n" * bool(text.strip()) + f"## {name}\n\n{body.strip()}\n" lines = text.splitlines() if read_section(text, name) == body.strip(): return text last = span[1] == len(lines) return "\n".join([*lines[: span[0] + 1], "", *body.strip().splitlines(), *([] if last else [""]), *lines[span[1] :]]) + "\n" def span_of(text: str, name: str) -> tuple[int, int] | None | Failure: """The index of the one ## name heading's line and of the line after its section; None where there is no such heading. A heading inside a code fence is ignored.""" if name not in SECTIONS: return Failure(f"{name} is not a section of an epic's description; the sections are {', '.join(SECTIONS)}") lines = fenced_lines(text) headings = [index for index, (line, fenced) in enumerate(lines) if not fenced and (line.startswith("# ") or line.startswith("## "))] starts = [index for index in headings if lines[index][0].startswith("## ") and lines[index][0][3:].strip() == name] if len(starts) > 1: return Failure(f"the epic's description has ## {name} more than once") return (starts[0], next((index for index in headings if index > starts[0]), len(lines))) if starts else None def language_in(text: str) -> str | None: """The language the description's language line names; None where it has none.""" for line, fenced in fenced_lines(text): if not fenced and (found := LANGUAGE_LINE.match(line)): return found.group(1) return None def parallel_chunks_in(text: str) -> int | Failure: """How many of the epic's chunks may run at once, as the description's CAP line says; 1 where it has none, as a project's `parallel-chunks` is where its config leaves it out.""" for line, fenced in fenced_lines(text): if not fenced and (found := CAP_LINE.match(line)): value = found.group(1).strip() if re.fullmatch(r"[1-9][0-9]*", value): return int(value) return Failure(f"the epic's description caps its chunks with `{CAP} {value}`, which is not a whole number of 1 or more, such as `{CAP} 2`") if not fenced and NEAR_CAP_LINE.match(line): return Failure(f"the epic's description holds the line `{line.strip()}`, which do-epic doesn't read as the epic's cap: write it as a line of its own, spelt `{CAP} 2`") return 1 def with_language(text: str, language: str) -> str | Failure: """text with its language line naming language, put first where there is none.""" if fault := language_fault(language): return Failure(f"cannot write the language {language!r}: {fault}") line = f"**Language:** {language}" lines = fenced_lines(text) for index, (old, fenced) in enumerate(lines): if not fenced and LANGUAGE_LINE.match(old): return "\n".join([*(old for old, _ in lines[:index]), line, *(old for old, _ in lines[index + 1 :])]) + "\n" return line + "\n" + "\n" * bool(text.strip()) + text @dataclasses.dataclass(frozen=True) class EpicRecord: """One epic's record, kept in its description.""" description: EpicDescription def section(self, name: str) -> str | Failure: text = self.description.read() return text if isinstance(text, Failure) else read_section(text, name) def language(self) -> str | None | Failure: text = self.description.read() return text if isinstance(text, Failure) else language_in(text) def parallel_chunks(self) -> int | Failure: text = self.description.read() return text if isinstance(text, Failure) else parallel_chunks_in(text) def write_section(self, name: str, body: str, approved: bool = False) -> Held | Failure: """Writes body as the ## name section. approved says the human approved the change in an interrupt, which Goals and Audience need.""" return self.written(lambda text: with_section(text, name, body), frozenset({name}) if approved else frozenset()) def write_language(self, language: str) -> Held | Failure: return self.written(lambda text: with_language(text, language), frozenset()) def written(self, change: typing.Callable[[str], str | Failure], approved: frozenset[str]) -> Held | Failure: held = self.description.held() if isinstance(held, Failure): return held text = change(held.text) if isinstance(text, Failure): return text return dataclasses.replace(self.description, approved=approved).write(text, held.version)