Files

69 lines
2.7 KiB
Python

"""Print one section of a markdown file, picked by a fragment of its heading.
usage: markdown-section <file> <fragment>
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 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 sys
from failure import Failure
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 or not argv[1].strip():
print("usage: markdown-section <file> <fragment>", file=sys.stderr)
return 2
try:
text = pathlib.Path(argv[0]).read_text()
except (OSError, UnicodeDecodeError) as error:
print(f"markdown-section: {error}", file=sys.stderr)
return 1
found = section(text, argv[1])
if isinstance(found, Failure):
print(f"markdown-section: {found.reason}", file=sys.stderr)
return 1
print(found, end="")
return 0
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 = []
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 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()]
matching = [heading for heading in matching if heading[2].lower() == wanted] or matching
if not matching:
return Failure(f"no heading holds '{fragment}'")
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), None)
return "\n".join(lines[start:end]).rstrip("\n") + "\n"