plain-parser 1.0.0.dev1__py3-none-any.whl → 1.0.0.dev2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plain_parser/__init__.py +3 -3
- plain_parser/cli.py +194 -163
- plain_parser/concept_utils.py +141 -124
- plain_parser/graph.py +145 -109
- plain_parser/liquid_nodes.py +25 -43
- plain_parser/loaders.py +103 -90
- plain_parser/plain_file.py +614 -530
- plain_parser/plain_spec.py +135 -134
- plain_parser/project.py +94 -80
- plain_parser/test_plain_file.py +195 -175
- {plain_parser-1.0.0.dev1.dist-info → plain_parser-1.0.0.dev2.dist-info}/METADATA +15 -2
- plain_parser-1.0.0.dev2.dist-info/RECORD +16 -0
- plain_parser-1.0.0.dev2.dist-info/licenses/LICENSE +21 -0
- plain_parser-1.0.0.dev1.dist-info/RECORD +0 -15
- {plain_parser-1.0.0.dev1.dist-info → plain_parser-1.0.0.dev2.dist-info}/WHEEL +0 -0
- {plain_parser-1.0.0.dev1.dist-info → plain_parser-1.0.0.dev2.dist-info}/entry_points.txt +0 -0
plain_parser/liquid_nodes.py
CHANGED
|
@@ -1,62 +1,44 @@
|
|
|
1
|
-
"""Liquid include tag that indents the included template, and the loader mixin that does
|
|
1
|
+
"""Liquid include tag that indents the included template, and the loader mixin that does the indenting."""
|
|
2
2
|
|
|
3
|
-
from
|
|
3
|
+
from contextvars import ContextVar
|
|
4
|
+
from typing import TYPE_CHECKING, Any, TextIO
|
|
4
5
|
|
|
5
|
-
from liquid2 import
|
|
6
|
+
from liquid2 import TemplateSource
|
|
6
7
|
from liquid2.builtin.tags.include_tag import IncludeNode, IncludeTag
|
|
7
|
-
|
|
8
|
-
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from liquid2 import RenderContext
|
|
11
|
+
|
|
12
|
+
_include_indent: ContextVar[int] = ContextVar("plain_include_indent", default=0)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def indent_template(source: str, indent: int) -> str:
|
|
16
|
+
"""Drop the trailing whitespace of a template source and indent every line after the first."""
|
|
17
|
+
return source.rstrip().replace("\n", "\n" + " " * indent)
|
|
9
18
|
|
|
10
19
|
|
|
11
20
|
class Plain2CodeLoaderMixin:
|
|
12
|
-
"""Loader mixin:
|
|
21
|
+
"""Loader mixin: the template sources it loads are indented for the include tag being rendered."""
|
|
13
22
|
|
|
14
|
-
def get_source(self, env, template_name, *, context=None,
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
if indent:
|
|
18
|
-
text = text.replace("\n", "\n" + " " * indent)
|
|
19
|
-
return TemplateSource(text, source.name, source.uptodate, source.matter)
|
|
23
|
+
def get_source(self, env: Any, template_name: str, *, context: Any = None, **kwargs: object) -> TemplateSource:
|
|
24
|
+
loaded = super().get_source(env, template_name, context=context, **kwargs) # type: ignore[misc]
|
|
25
|
+
return loaded._replace(source=indent_template(loaded.source, _include_indent.get()))
|
|
20
26
|
|
|
21
27
|
|
|
22
28
|
class Plain2CodeIncludeNode(IncludeNode):
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def _line_prefix(self) -> str:
|
|
29
|
+
def render_to_output(self, context: "RenderContext", buffer: TextIO) -> int:
|
|
26
30
|
source = self.token.source
|
|
27
31
|
start = self.token.start
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
def render_to_output(self, context: RenderContext, buffer: TextIO) -> int:
|
|
31
|
-
prefix = self._line_prefix()
|
|
32
|
+
prefix = source[source.rfind("\n", 0, start) + 1 : start]
|
|
32
33
|
if ">" in prefix:
|
|
33
|
-
text = self
|
|
34
|
+
text = str(self)
|
|
34
35
|
buffer.write(text)
|
|
35
36
|
return len(text)
|
|
36
|
-
|
|
37
|
-
name = str(self.name.evaluate(context))
|
|
37
|
+
reset = _include_indent.set(len(prefix) - len(prefix.lstrip(" ")))
|
|
38
38
|
try:
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
err.template_name = context.template.full_name()
|
|
43
|
-
raise
|
|
44
|
-
namespace = dict(arg.evaluate(context) for arg in self.args)
|
|
45
|
-
with context.extend(namespace, template=template):
|
|
46
|
-
if self.var:
|
|
47
|
-
val = self.var.evaluate(context)
|
|
48
|
-
key = self.alias or template.name.split(".")[0]
|
|
49
|
-
if isinstance(val, (list, tuple)):
|
|
50
|
-
count = 0
|
|
51
|
-
for item in val:
|
|
52
|
-
namespace[key] = item
|
|
53
|
-
count += template.render_with_context(context, buffer, partial=True)
|
|
54
|
-
return count
|
|
55
|
-
namespace[key] = val
|
|
56
|
-
return template.render_with_context(context, buffer, partial=True)
|
|
57
|
-
|
|
58
|
-
async def render_to_output_async(self, context: RenderContext, buffer: TextIO) -> int:
|
|
59
|
-
return self.render_to_output(context, buffer)
|
|
39
|
+
return super().render_to_output(context, buffer)
|
|
40
|
+
finally:
|
|
41
|
+
_include_indent.reset(reset)
|
|
60
42
|
|
|
61
43
|
|
|
62
44
|
class Plain2CodeIncludeTag(IncludeTag):
|
plain_parser/loaders.py
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Looking up and loading files, linked resources and Liquid templates."""
|
|
2
2
|
|
|
3
3
|
import os
|
|
4
4
|
import re
|
|
5
|
-
from
|
|
5
|
+
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
|
|
6
6
|
|
|
7
|
-
from liquid2 import Environment, StrictUndefined
|
|
8
|
-
from liquid2.
|
|
9
|
-
from liquid2.exceptions import LiquidSyntaxError, TemplateNotFoundError, UndefinedError
|
|
7
|
+
from liquid2 import Environment, FileSystemLoader, StrictUndefined, TemplateNotFoundError
|
|
8
|
+
from liquid2.exceptions import LiquidSyntaxError, UndefinedError
|
|
10
9
|
|
|
11
10
|
from plain_parser.exceptions import PlainSyntaxError, UnsupportedBase64Content, UnsupportedResourceType
|
|
12
11
|
from plain_parser.liquid_nodes import Plain2CodeIncludeTag, Plain2CodeLoaderMixin
|
|
@@ -14,61 +13,74 @@ from plain_parser.plain_spec import code_variable_liquid_filter, prohibited_char
|
|
|
14
13
|
|
|
15
14
|
MAX_BASE64_BLOB_LENGTH = 8192
|
|
16
15
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
)
|
|
16
|
+
_BASE64_RUN = re.compile(r"[A-Za-z0-9+/_-]+")
|
|
17
|
+
_BASE64_HEADER = re.compile(r"data:[A-Za-z0-9.+-]+/[A-Za-z0-9.+-]+;base64,\Z")
|
|
20
18
|
|
|
21
19
|
|
|
22
|
-
def find_large_base64_blob(text: str) -> str
|
|
23
|
-
|
|
24
|
-
|
|
20
|
+
def find_large_base64_blob(text: str) -> Optional[str]:
|
|
21
|
+
"""Return the first base64 blob of a text, header included, or None."""
|
|
22
|
+
for run in _BASE64_RUN.finditer(text):
|
|
23
|
+
if run.end() - run.start() < MAX_BASE64_BLOB_LENGTH:
|
|
24
|
+
continue
|
|
25
|
+
start, end = run.start(), run.end()
|
|
26
|
+
while end < len(text) and end - run.end() < 2 and text[end] == "=":
|
|
27
|
+
end += 1
|
|
28
|
+
header = _BASE64_HEADER.search(text, max(0, start - 256), start)
|
|
29
|
+
if header:
|
|
30
|
+
start = header.start()
|
|
31
|
+
return text[start:end]
|
|
32
|
+
return None
|
|
25
33
|
|
|
26
34
|
|
|
27
|
-
def open_from(dirs, file_name) -> str
|
|
28
|
-
|
|
29
|
-
|
|
35
|
+
def open_from(dirs: Iterable[Union[str, "os.PathLike[str]"]], file_name: str) -> Optional[str]:
|
|
36
|
+
"""Return the UTF-8 text of the first regular file of that name in the directories, or None."""
|
|
37
|
+
for directory in dirs:
|
|
38
|
+
path = os.path.join(directory, file_name)
|
|
30
39
|
if os.path.isfile(path):
|
|
31
|
-
with open(path, encoding="utf-8", newline="") as
|
|
32
|
-
return
|
|
40
|
+
with open(path, encoding="utf-8", newline="") as file:
|
|
41
|
+
return file.read()
|
|
33
42
|
return None
|
|
34
43
|
|
|
35
44
|
|
|
36
|
-
def find_resource_dir(dirs, file_name) -> str
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
45
|
+
def find_resource_dir(dirs: Iterable[Union[str, "os.PathLike[str]"]], file_name: str) -> Optional[str]:
|
|
46
|
+
"""Return the first directory in which the name exists as a file or a directory, or None."""
|
|
47
|
+
for directory in dirs:
|
|
48
|
+
if os.path.exists(os.path.join(directory, file_name)):
|
|
49
|
+
return os.fspath(directory)
|
|
40
50
|
return None
|
|
41
51
|
|
|
42
52
|
|
|
43
|
-
def resolve_linked_resource(dirs, file_name) -> str
|
|
44
|
-
|
|
45
|
-
|
|
53
|
+
def resolve_linked_resource(dirs: Iterable[Union[str, "os.PathLike[str]"]], file_name: str) -> Optional[str]:
|
|
54
|
+
"""Return the directory that holds the name, joined with the name as written, or None."""
|
|
55
|
+
directory = find_resource_dir(dirs, file_name)
|
|
56
|
+
return None if directory is None else os.path.join(directory, file_name)
|
|
46
57
|
|
|
47
58
|
|
|
48
59
|
def relative_resource_path(base_dir: str, resource_dir: str, target: str) -> str:
|
|
60
|
+
"""Name a file of a resource directory relative to a base directory, with `/` as separator."""
|
|
49
61
|
try:
|
|
50
|
-
|
|
62
|
+
directory = os.path.relpath(resource_dir, base_dir)
|
|
51
63
|
except ValueError:
|
|
52
64
|
return os.path.join(os.path.abspath(resource_dir), target).replace(os.sep, "/")
|
|
53
|
-
if
|
|
65
|
+
if directory == os.curdir:
|
|
54
66
|
return target
|
|
55
|
-
return
|
|
67
|
+
return directory.replace(os.sep, "/") + "/" + target
|
|
56
68
|
|
|
57
69
|
|
|
58
|
-
def load_linked_resources(template_dirs:
|
|
59
|
-
"""Read every linked file
|
|
60
|
-
loaded:
|
|
70
|
+
def load_linked_resources(template_dirs: List[str], resources_list, module_name: str) -> Dict[str, str]:
|
|
71
|
+
"""Read every linked file of a module and return a mapping from target to text."""
|
|
72
|
+
loaded: Dict[str, str] = {}
|
|
61
73
|
for resource in resources_list:
|
|
62
|
-
target = resource["target"]
|
|
74
|
+
target = resource["target"]
|
|
63
75
|
if target in loaded:
|
|
64
76
|
continue
|
|
65
77
|
try:
|
|
66
78
|
text = open_from(template_dirs, target)
|
|
67
|
-
except UnicodeDecodeError as
|
|
79
|
+
except UnicodeDecodeError as error:
|
|
68
80
|
raise UnsupportedResourceType(
|
|
69
81
|
f"Referenced resource '{target}' in module '{module_name}' is a binary file. "
|
|
70
82
|
"Only text files (e.g. .md, .txt, .json, .yaml) can be referenced from a .plain file."
|
|
71
|
-
) from
|
|
83
|
+
) from error
|
|
72
84
|
if text is None:
|
|
73
85
|
raise FileNotFoundError(f"Resource file '{target}' referenced in module '{module_name}' not found.")
|
|
74
86
|
blob = find_large_base64_blob(text)
|
|
@@ -84,66 +96,67 @@ def load_linked_resources(template_dirs: list[str], resources_list, module_name:
|
|
|
84
96
|
|
|
85
97
|
|
|
86
98
|
def liquid_error_message(error: LiquidSyntaxError) -> str:
|
|
87
|
-
"""
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
token = error
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
99
|
+
"""Build the message of a Liquid syntax error, with its position when it is known."""
|
|
100
|
+
message = str(error.args[0]) if error.args else ""
|
|
101
|
+
template = getattr(error, "template_name", None)
|
|
102
|
+
token = getattr(error, "token", None)
|
|
103
|
+
source = getattr(token, "source", None)
|
|
104
|
+
start = getattr(token, "start", None)
|
|
105
|
+
if source is not None and start is not None:
|
|
106
|
+
line = source.count("\n", 0, start) + 1
|
|
107
|
+
column = start - (source.rfind("\n", 0, start) + 1)
|
|
95
108
|
position = f" at {template}:{line}:{column}" if template else f" at {line}:{column}"
|
|
96
|
-
|
|
97
|
-
position = f" in {template}"
|
|
98
|
-
return f"Plain syntax error: Invalid Liquid{position}: {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
class
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
109
|
+
else:
|
|
110
|
+
position = f" in {template}" if template else ""
|
|
111
|
+
return f"Plain syntax error: Invalid Liquid{position}: {message}"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class _PlainTemplateNotFoundError(TemplateNotFoundError):
|
|
115
|
+
def __str__(self) -> str:
|
|
116
|
+
return str(self.args[0])
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class _RecordingFileSystemLoader(FileSystemLoader):
|
|
120
|
+
def __init__(self, search_path: Any, **kwargs: Any) -> None:
|
|
121
|
+
super().__init__(search_path, **kwargs)
|
|
122
|
+
self.loaded_templates: Dict[str, str] = {}
|
|
123
|
+
|
|
124
|
+
def get_source(self, env: Any, template_name: str, *, context: Any = None, **kwargs: object):
|
|
125
|
+
loaded = super().get_source(env, template_name, context=context, **kwargs)
|
|
126
|
+
self.loaded_templates[template_name] = loaded.source
|
|
127
|
+
return loaded
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class TrackingFileSystemLoader(Plain2CodeLoaderMixin, _RecordingFileSystemLoader):
|
|
131
|
+
"""File system loader that records every loaded template source by name and indents included templates."""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def make_environment(loader: Any) -> Environment:
|
|
135
|
+
"""Build the Liquid environment of plain-parser around a loader."""
|
|
136
|
+
environment = Environment(loader=loader, undefined=StrictUndefined)
|
|
137
|
+
environment.tags["include"] = Plain2CodeIncludeTag(environment)
|
|
138
|
+
environment.filters["code_variable"] = code_variable_liquid_filter
|
|
139
|
+
environment.filters["prohibited_chars"] = prohibited_chars_liquid_filter
|
|
140
|
+
return environment
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _render(source_path, plain_source, template_name=None, code_variables=None) -> Tuple[str, Dict[str, str]]:
|
|
144
|
+
search_path = [source_path] if isinstance(source_path, (str, os.PathLike)) else list(source_path)
|
|
145
|
+
loader = TrackingFileSystemLoader(search_path)
|
|
146
|
+
environment = make_environment(loader)
|
|
147
|
+
variables = {} if code_variables is None else {"code_variables": code_variables}
|
|
130
148
|
try:
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
raise
|
|
139
|
-
except TemplateNotFoundError as e:
|
|
140
|
-
name = _missing_name(e)
|
|
141
|
-
raise TemplateNotFoundError(f"Template not found: {name}", filename=name) from e
|
|
149
|
+
rendered = environment.from_string(plain_source, name=template_name).render(**variables)
|
|
150
|
+
except LiquidSyntaxError as error:
|
|
151
|
+
raise PlainSyntaxError(liquid_error_message(error)) from error
|
|
152
|
+
except UndefinedError as error:
|
|
153
|
+
raise Exception(f"Undefined liquid variable: {error.args[0] if error.args else error}") from error
|
|
154
|
+
except TemplateNotFoundError as error:
|
|
155
|
+
name = error.args[0] if error.args else template_name
|
|
156
|
+
raise _PlainTemplateNotFoundError(f"Template not found: {name}", filename=str(name)) from error
|
|
142
157
|
return rendered, loader.loaded_templates
|
|
143
158
|
|
|
144
159
|
|
|
145
|
-
def
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
return str(getattr(token, "value", token))
|
|
149
|
-
return str(error.args[0]) if error.args else str(error.template_name)
|
|
160
|
+
def get_loaded_templates(source_path, plain_source, template_name=None) -> Tuple[str, Dict[str, str]]:
|
|
161
|
+
"""Render a text with Liquid; return the rendered text and the sources of the templates it loaded."""
|
|
162
|
+
return _render(source_path, plain_source, template_name)
|