import dataclasses import re from failure import Failure EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security") ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |" @dataclasses.dataclass(frozen=True) class Item: id: int release: tuple[int, int, int] exempt: str tagline: str scores: dict[str, int] goals: tuple[str, ...] @dataclasses.dataclass(frozen=True) class Table: """Body rows of a markdown table, and the index of the first row in the file's lines.""" start: int rows: list[str] def items(todo: str) -> list[Item] | Failure: """Each row of a todo.md's items table.""" table = table_rows(todo.splitlines(), ITEMS_HEADER) if isinstance(table, Failure): return table items = [] for row in table.rows: item = parse_row(row) if isinstance(item, Failure): return item items.append(item) return items def table_rows(lines: list[str], header: str) -> Table | Failure: if lines.count(header) != 1: return Failure(f"todo.md needs the table header {header} once") start = lines.index(header) + 2 if start > len(lines) or not re.fullmatch(r"\|(-+\|)+", lines[start - 1].replace(" ", "")): return Failure(f"the table under {header} has no |---| divider line") end = start while end < len(lines) and lines[end].startswith("|"): end += 1 return Table(start, lines[start:end]) def cells(row: str, count: int) -> list[str] | Failure: found = [cell.strip() for cell in re.split(r"(? Item | Failure: """An item row, every cell checked but the goals it cites.""" found = cells(row, 10) if isinstance(found, Failure): return found id_, release, exempt, tagline, r, s, a, g, goals, _ = found if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1: return Failure(f"the ID {id_!r} is not a positive whole number: {row}") if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release): return Failure(f"item {id_}'s release {release!r} is not a semver version") if exempt not in EXEMPTIONS: return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}") if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline): return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}") scores = {} for name, value in zip("RSAG", (r, s, a, g)): if not re.fullmatch(r"[0-9]+", value) or not 1 <= int(value) <= 10: return Failure(f"item {id_}'s {name} {value!r} is not a whole number from 1 to 10") scores[name] = int(value) cited = tuple(goal.strip() for goal in goals.split(",")) major, minor, patch = (int(part) for part in release.split(".")) return Item(int(id_), (major, minor, patch), exempt, tagline, scores, cited)