fix(docs/manualtools.py): use removeprefix instead of lstrip for frontmatter parsing
Replace .lstrip('\n') with .removeprefix("\n") to preserve body text that
legitimately starts with blank lines. The serialize() function inserts exactly
one separator newline; removing only that one newline (via removeprefix) rather
than all leading newlines (via lstrip) maintains parse/serialize roundtrip
losslessness.
Adds regression test to verify bodies with leading blank lines roundtrip
correctly.
This commit is contained in:
+1
-1
@@ -29,7 +29,7 @@ def parse(path: Path) -> tuple[dict, str]:
|
|||||||
if end == -1:
|
if end == -1:
|
||||||
return {}, text.rstrip()
|
return {}, text.rstrip()
|
||||||
fm = yaml.safe_load(text[4:end]) or {}
|
fm = yaml.safe_load(text[4:end]) or {}
|
||||||
return fm, text[end + 5 :].lstrip('\n').rstrip()
|
return fm, text[end + 5 :].removeprefix("\n").rstrip()
|
||||||
|
|
||||||
|
|
||||||
def serialize(fm: dict, body: str) -> str:
|
def serialize(fm: dict, body: str) -> str:
|
||||||
|
|||||||
@@ -72,6 +72,18 @@ def test_walk_nests_directory_after_its_index():
|
|||||||
assert got == expected, f"wrong nesting: {got}"
|
assert got == expected, f"wrong nesting: {got}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_roundtrip_body_with_leading_blank_line():
|
||||||
|
fm = {"title": "Test"}
|
||||||
|
body = "\nContent starts after blank line."
|
||||||
|
text = mt.serialize(fm, body)
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
p = Path(d) / "t.md"
|
||||||
|
p.write_text(text)
|
||||||
|
got_fm, got_body = mt.parse(p)
|
||||||
|
assert got_fm == fm, f"frontmatter mismatch: {got_fm!r}"
|
||||||
|
assert got_body == body, f"body mismatch: expected {body!r}, got {got_body!r}"
|
||||||
|
|
||||||
|
|
||||||
TESTS = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
TESTS = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user