Coverage for little_loops / frontmatter.py: 16%
32 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
1"""Frontmatter parsing utilities for little-loops.
3Provides shared YAML-subset frontmatter parsing and stripping used by
4issue_parser, sync, and issue_history modules.
5"""
7from __future__ import annotations
9import re
10from typing import Any
13def parse_frontmatter(content: str, *, coerce_types: bool = False) -> dict[str, Any]:
14 """Extract YAML frontmatter from content.
16 Looks for content between opening and closing '---' markers.
17 Parses simple key: value pairs. Returns empty dict if no
18 frontmatter found.
20 Args:
21 content: File content to parse
22 coerce_types: If True, coerce digit strings to int
24 Returns:
25 Dictionary of frontmatter fields, or empty dict
26 """
27 if not content or not content.startswith("---"):
28 return {}
30 end_match = re.search(r"\n---\s*\n", content[3:])
31 if not end_match:
32 return {}
34 frontmatter_text = content[4 : 3 + end_match.start()]
36 result: dict[str, Any] = {}
37 for line in frontmatter_text.split("\n"):
38 line = line.strip()
39 if not line or line.startswith("#"):
40 continue
41 if ":" in line:
42 key, value = line.split(":", 1)
43 key = key.strip()
44 value = value.strip()
45 if value.lower() in ("null", "~", ""):
46 result[key] = None
47 elif coerce_types and value.isdigit():
48 result[key] = int(value)
49 else:
50 result[key] = value
51 return result
54def strip_frontmatter(content: str) -> str:
55 """Remove YAML frontmatter from content, returning the body.
57 Strips the ``---`` delimited frontmatter block (if present) and
58 returns everything after the closing delimiter.
60 Args:
61 content: File content possibly starting with frontmatter
63 Returns:
64 Content with frontmatter removed. Returns original content
65 unchanged if no valid frontmatter block is found.
66 """
67 if not content or not content.startswith("---"):
68 return content
70 end_match = re.search(r"\n---\s*\n", content[3:])
71 if not end_match:
72 return content
74 return content[3 + end_match.end() :]