wdb/d_wiki/yaml_compat.py
2026-05-28 19:02:16 +08:00

71 lines
2.2 KiB
Python

from __future__ import annotations
from typing import Any
try:
import yaml as _yaml # type: ignore
except Exception: # pragma: no cover - exercised in environments without PyYAML
_yaml = None
def safe_load(text: str) -> Any:
if _yaml is not None:
return _yaml.safe_load(text)
lines = [
(len(line) - len(line.lstrip(" ")), line.strip())
for line in text.splitlines()
if line.strip() and not line.strip().startswith("#")
]
value, _index = _parse_node(lines, 0, 0)
return value
def _parse_node(lines: list[tuple[int, str]], index: int, indent: int) -> tuple[Any, int]:
if index >= len(lines):
return {}, index
if lines[index][0] < indent:
return {}, index
if lines[index][1].startswith("- "):
values: list[Any] = []
while index < len(lines) and lines[index][0] == indent and lines[index][1].startswith("- "):
values.append(_scalar(lines[index][1][2:].strip()))
index += 1
return values, index
mapping: dict[str, Any] = {}
while index < len(lines):
current_indent, stripped = lines[index]
if current_indent < indent:
break
if current_indent > indent:
break
if ":" not in stripped:
index += 1
continue
key, raw_value = stripped.split(":", 1)
key = key.strip()
raw_value = raw_value.strip()
index += 1
if raw_value:
mapping[key] = _scalar(raw_value)
continue
child, index = _parse_node(lines, index, indent + 2)
mapping[key] = child
return mapping, index
def _scalar(value: str) -> Any:
if value in {"null", "None", "~"}:
return None
if value in {"true", "True"}:
return True
if value in {"false", "False"}:
return False
if value.startswith("[") and value.endswith("]"):
inner = value[1:-1].strip()
if not inner:
return []
return [_scalar(item.strip()) for item in inner.split(",")]
if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")):
return value[1:-1]
return value