-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase_parsers.py
77 lines (57 loc) · 2.1 KB
/
base_parsers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# ruff: noqa: F821
import pathlib
import frontmatter
def parse_content(content: str) -> tuple[dict, str]:
"""Fetching content and atttributes from a content_path"""
p = frontmatter.parse(content)
return p
class BasePageParser:
"""
The default Parser for Page objects.
This yields attributes and content using frontmatter.
The content is not modified.
"""
@staticmethod
def parse_content_path(content_path: str) -> tuple[dict, str]:
"""
Fetches content from `Page.content_path` and sets attributes.
This is a separate method so that it can be overridden by subclasses.
params:
content_path:
The path to the file that will be used to generate the Page's `content`.
Should be a valid path to a file or a url.
"""
return parse_content(pathlib.Path(content_path).read_text())
@staticmethod
def parse_content(content: str) -> tuple[dict, str]:
"""
Fetches content from `Page.content` and returns attributes and content.
This is a separate method so that it can be overridden by subclasses.
params:
content:
The path to the file that will be used to generate the Page's `content`.
Should be a valid path to a file or a url.
"""
return parse_content(content)
@staticmethod
def parse(
content: str,
extras: dict[str, any] | None = None,
) -> str:
"""
Parses content to be rendered into HTML
In the base parser, this returns the content as is.
params:
content: content to be rendered into HTML
extras: dictionary with extras to augment attributes
"""
return content
@staticmethod
def create_entry(*, content: str = None, **kwargs) -> str:
"""
Writes the content type that would be parsed to the content_path.
"""
post = frontmatter.Post(content=content or "")
for key, val in kwargs.items():
post[key] = val
return frontmatter.dumps(post)