erick.is/_utils.py

51 lines
1.1 KiB
Python
Raw Normal View History

from dataclasses import dataclass, field
import yaml
@dataclass
class Article:
metadata: dict = field(default_factory=dict)
content: str = ""
def load(file_name) -> Article:
content = ""
with open(file=file_name, mode="r", encoding="utf8") as file:
content = file.read()
return loads(content)
def loads(content: str) -> Article:
lines = content.splitlines()
start = -1
end = -1
for index, line in enumerate(lines):
if line.startswith("---"):
if start == -1:
start = index
elif end == -1:
end = index
break
if start == -1 or end == -1:
raise ValueError("Missing frontmatter delimiters")
metadata = lines[start + 1 : end]
content = lines[end + 1 :]
metadata = yaml.safe_load("\n".join(metadata))
if not metadata:
metadata = {}
return Article(
metadata=metadata,
content="\n".join(content),
)
def dumps(article: Article) -> str:
return f"""---\n{yaml.dump(article.metadata)}---\n{article.content}\n"""