Skip to content

Commit 434c25a

Browse files
committed
Add minimal frontmatter module for tests
1 parent 65427a3 commit 434c25a

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

frontmatter/__init__.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import re
2+
3+
class Post(dict):
4+
"""Simple container for front matter metadata and content."""
5+
def __init__(self, content='', **metadata):
6+
super().__init__(metadata)
7+
self.content = content
8+
9+
def _parse_yaml(yaml_str):
10+
data = {}
11+
for line in yaml_str.splitlines():
12+
line = line.strip()
13+
if not line:
14+
continue
15+
if ':' in line:
16+
key, value = line.split(':', 1)
17+
data[key.strip()] = value.strip().strip('"').strip("'")
18+
return data
19+
20+
def _to_yaml(data):
21+
lines = [f"{k}: {v}" for k, v in data.items()]
22+
return '\n'.join(lines)
23+
24+
def dumps(post):
25+
fm = _to_yaml(dict(post))
26+
return f"---\n{fm}\n---\n{post.content}"
27+
28+
def load(fp):
29+
if hasattr(fp, 'read'):
30+
text = fp.read()
31+
else:
32+
with open(fp, 'r', encoding='utf-8') as f:
33+
text = f.read()
34+
match = re.match(r'^---\n(.*?)\n---\n?(.*)', text, re.DOTALL)
35+
if match:
36+
fm_yaml, body = match.group(1), match.group(2)
37+
metadata = _parse_yaml(fm_yaml)
38+
else:
39+
body = text
40+
metadata = {}
41+
return Post(content=body, **metadata)

0 commit comments

Comments
 (0)