|
11 | 11 | import os |
12 | 12 | import re |
13 | 13 | import subprocess |
14 | | -import yaml |
15 | 14 | from datetime import datetime |
16 | 15 |
|
17 | 16 | import rlcr_sources |
18 | 17 |
|
| 18 | +try: |
| 19 | + import yaml |
| 20 | +except ModuleNotFoundError: # pragma: no cover - exercised by shell tests |
| 21 | + yaml = None |
| 22 | + |
19 | 23 | logger = logging.getLogger(__name__) |
20 | 24 |
|
21 | 25 |
|
| 26 | +def _coerce_yaml_scalar(value): |
| 27 | + """Parse the simple scalar values used in Humanize state frontmatter.""" |
| 28 | + value = value.strip() |
| 29 | + if value == '': |
| 30 | + return '' |
| 31 | + if (value.startswith('"') and value.endswith('"')) or ( |
| 32 | + value.startswith("'") and value.endswith("'") |
| 33 | + ): |
| 34 | + return value[1:-1] |
| 35 | + lowered = value.lower() |
| 36 | + if lowered == 'true': |
| 37 | + return True |
| 38 | + if lowered == 'false': |
| 39 | + return False |
| 40 | + if lowered in {'null', 'none', '~'}: |
| 41 | + return None |
| 42 | + if re.fullmatch(r'-?[0-9]+', value): |
| 43 | + try: |
| 44 | + return int(value) |
| 45 | + except ValueError: |
| 46 | + return value |
| 47 | + return value |
| 48 | + |
| 49 | + |
| 50 | +def _safe_load_frontmatter(text): |
| 51 | + """Load frontmatter, falling back to a small key/value parser without PyYAML.""" |
| 52 | + if yaml is not None: |
| 53 | + return yaml.safe_load(text) or {} |
| 54 | + |
| 55 | + meta = {} |
| 56 | + for raw_line in text.splitlines(): |
| 57 | + line = raw_line.strip() |
| 58 | + if not line or line.startswith('#') or ':' not in line: |
| 59 | + continue |
| 60 | + key, value = line.split(':', 1) |
| 61 | + key = key.strip() |
| 62 | + if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_-]*', key): |
| 63 | + continue |
| 64 | + meta[key] = _coerce_yaml_scalar(value) |
| 65 | + return meta |
| 66 | + |
| 67 | + |
22 | 68 | def _derive_project_root(session_dir): |
23 | 69 | """Return the project root for a ``.humanize/rlcr/<session>`` path.""" |
24 | 70 | rlcr_dir = os.path.dirname(session_dir) |
@@ -64,8 +110,8 @@ def parse_yaml_frontmatter(filepath): |
64 | 110 | return {}, content |
65 | 111 |
|
66 | 112 | try: |
67 | | - meta = yaml.safe_load(parts[1]) or {} |
68 | | - except yaml.YAMLError: |
| 113 | + meta = _safe_load_frontmatter(parts[1]) |
| 114 | + except Exception: |
69 | 115 | meta = {} |
70 | 116 |
|
71 | 117 | body = parts[2].strip() |
|
0 commit comments