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

1"""Frontmatter parsing utilities for little-loops. 

2 

3Provides shared YAML-subset frontmatter parsing and stripping used by 

4issue_parser, sync, and issue_history modules. 

5""" 

6 

7from __future__ import annotations 

8 

9import re 

10from typing import Any 

11 

12 

13def parse_frontmatter(content: str, *, coerce_types: bool = False) -> dict[str, Any]: 

14 """Extract YAML frontmatter from content. 

15 

16 Looks for content between opening and closing '---' markers. 

17 Parses simple key: value pairs. Returns empty dict if no 

18 frontmatter found. 

19 

20 Args: 

21 content: File content to parse 

22 coerce_types: If True, coerce digit strings to int 

23 

24 Returns: 

25 Dictionary of frontmatter fields, or empty dict 

26 """ 

27 if not content or not content.startswith("---"): 

28 return {} 

29 

30 end_match = re.search(r"\n---\s*\n", content[3:]) 

31 if not end_match: 

32 return {} 

33 

34 frontmatter_text = content[4 : 3 + end_match.start()] 

35 

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 

52 

53 

54def strip_frontmatter(content: str) -> str: 

55 """Remove YAML frontmatter from content, returning the body. 

56 

57 Strips the ``---`` delimited frontmatter block (if present) and 

58 returns everything after the closing delimiter. 

59 

60 Args: 

61 content: File content possibly starting with frontmatter 

62 

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 

69 

70 end_match = re.search(r"\n---\s*\n", content[3:]) 

71 if not end_match: 

72 return content 

73 

74 return content[3 + end_match.end() :]