Answer stability round 1: 1 🔴, 3 🟡 (0 misread); reuse the markdown reader, list rival headings, test by table

This commit is contained in:
2026-11-17 11:52:36 +01:00
parent 1a9df179a8
commit 4cdc1c4be9
4 changed files with 79 additions and 98 deletions
+28 -32
View File
@@ -2,32 +2,31 @@
usage: markdown-section <file> <fragment>
The section runs from the first heading whose text holds the fragment, whatever its case, to the
line before the next heading of the same or a higher level, so it holds its sub-sections. The
heading's text is what follows its `#`s. A line inside a fenced code block is never a heading.
Print a record kept outside the checkout through the file `project-record open <record>` prints.
The section starts at the heading whose text holds the fragment, in any case, and ends before the
next heading of the same or a higher level, so it holds its sub-sections. A heading's text is what
follows its `#`s. A line inside a fenced code block is never a heading.
Where no heading holds the fragment, it fails saying so. Where another heading outside that section
holds it too, it fails listing each such heading with its line number, and prints no section: pass
more of the heading you want.
Where no heading holds the fragment, it fails saying so. Where several headings do, it fails
listing each with its line number and prints no section: pass more of the heading you want.
A heading whose text is the fragment, in any case, is the one picked even where longer headings
hold it too.
To read a record kept outside the checkout, pass the file `project-record open <record>` prints.
Exit 2 on bad arguments, and 1, saying why, on any other failure.
"""
import pathlib
import re
import sys
from failure import Failure
HEADING = re.compile(r"^ {0,3}(#{1,6})[ \t]+(.*?)[ \t]*$")
FENCE = re.compile(r"^ {0,3}(```|~~~)")
from text_files.markdown_text import fenced_lines, HEADING
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if len(argv) != 2:
if len(argv) != 2 or not argv[1].strip():
print("usage: markdown-section <file> <fragment>", file=sys.stderr)
return 2
try:
@@ -43,31 +42,28 @@ def main(argv: list[str]) -> int:
return 0
def headings(lines: list[str]) -> list[tuple[int, int, str]]:
"""Each heading outside a fenced code block, as its index in lines, its level and its text."""
def headings(text: str) -> list[tuple[int, int, str]]:
"""Each heading of text outside a fenced code block, as its line's index, its level and its text."""
found = []
fence = ""
for index, line in enumerate(lines):
opened = FENCE.match(line)
if opened and fence in ("", opened.group(1)):
fence = "" if fence else opened.group(1)
elif not fence and (heading := HEADING.match(line)):
for index, (line, fenced) in enumerate(fenced_lines(text)):
if not fenced and (heading := HEADING.match(line)):
found.append((index, len(heading.group(1)), heading.group(2)))
return found
def section(text: str, fragment: str) -> str | Failure:
"""The section of text under the first heading that holds fragment, or a Failure where none does or several do."""
lines = text.splitlines(keepends=True)
found = headings(lines)
matching = [at for at, (_, _, title) in enumerate(found) if fragment.lower() in title.lower()]
"""The section of text under the heading that fragment picks, or a Failure where no heading holds it or several do."""
found = headings(text)
wanted = fragment.strip().lower()
matching = [heading for heading in found if wanted in heading[2].lower()]
if len(matching) > 1:
matching = [heading for heading in matching if heading[2].lower() == wanted] or matching
if not matching:
return Failure(f"no heading holds '{fragment}'")
start, level, _ = found[matching[0]]
end = next((index for index, deeper, _ in found[matching[0] + 1:] if deeper <= level), len(lines))
# A matching heading inside the first one's section is part of what is printed, not a rival.
rivals = [at for at in matching if found[at][0] >= end]
if rivals:
listed = "\n".join(f"{found[at][0] + 1}: {lines[found[at][0]].rstrip()}" for at in [matching[0], *rivals])
return Failure(f"{len(rivals) + 1} headings hold '{fragment}', so use more of one:\n{listed}")
return "".join(lines[start:end]).rstrip("\n") + "\n"
lines = text.splitlines()
if len(matching) > 1:
listed = "\n".join(f"{index + 1}: {lines[index]}" for index, _, _ in matching)
return Failure(f"{len(matching)} headings hold '{fragment}', so use more of one:\n{listed}")
start, level, _ = matching[0]
end = next((index for index, deeper, _ in found if index > start and deeper <= level), len(lines))
return "\n".join(lines[start:end]).rstrip("\n") + "\n"