plain-parser 0.2.1.dev22__py3-none-any.whl → 1.0.0.dev1__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 +163 -220
- plain_parser/concept_utils.py +147 -200
- plain_parser/exceptions.py +3 -11
- plain_parser/graph.py +112 -144
- plain_parser/liquid_nodes.py +46 -92
- plain_parser/loaders.py +100 -102
- plain_parser/plain_file.py +556 -801
- plain_parser/plain_spec.py +168 -228
- plain_parser/project.py +93 -98
- plain_parser/test_plain_file.py +162 -179
- plain_parser-1.0.0.dev1.dist-info/METADATA +15 -0
- plain_parser-1.0.0.dev1.dist-info/RECORD +15 -0
- plain_parser-0.2.1.dev22.dist-info/METADATA +0 -145
- plain_parser-0.2.1.dev22.dist-info/RECORD +0 -16
- plain_parser-0.2.1.dev22.dist-info/licenses/LICENSE +0 -21
- {plain_parser-0.2.1.dev22.dist-info → plain_parser-1.0.0.dev1.dist-info}/WHEEL +0 -0
- {plain_parser-0.2.1.dev22.dist-info → plain_parser-1.0.0.dev1.dist-info}/entry_points.txt +0 -0
plain_parser/loaders.py
CHANGED
|
@@ -1,151 +1,149 @@
|
|
|
1
|
+
"""Resource loading helpers."""
|
|
2
|
+
|
|
1
3
|
import os
|
|
2
4
|
import re
|
|
3
|
-
from
|
|
5
|
+
from pathlib import Path
|
|
4
6
|
|
|
5
|
-
from liquid2 import Environment,
|
|
6
|
-
from liquid2.
|
|
7
|
+
from liquid2 import Environment, StrictUndefined
|
|
8
|
+
from liquid2.builtin import FileSystemLoader
|
|
9
|
+
from liquid2.exceptions import LiquidSyntaxError, TemplateNotFoundError, UndefinedError
|
|
7
10
|
|
|
8
|
-
from plain_parser import plain_spec
|
|
9
11
|
from plain_parser.exceptions import PlainSyntaxError, UnsupportedBase64Content, UnsupportedResourceType
|
|
10
12
|
from plain_parser.liquid_nodes import Plain2CodeIncludeTag, Plain2CodeLoaderMixin
|
|
13
|
+
from plain_parser.plain_spec import code_variable_liquid_filter, prohibited_chars_liquid_filter
|
|
11
14
|
|
|
12
15
|
MAX_BASE64_BLOB_LENGTH = 8192
|
|
13
16
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
r"(?:data:[\w.+-]+/[\w.+-]+;base64,)?[A-Za-z0-9+/_-]{%d,}={0,2}" % MAX_BASE64_BLOB_LENGTH
|
|
17
|
+
_BLOB = re.compile(
|
|
18
|
+
r"(?:data:[A-Za-z0-9.+_-]+/[A-Za-z0-9.+_-]+;base64,)?[A-Za-z0-9+/_-]{%d,}={0,2}" % MAX_BASE64_BLOB_LENGTH
|
|
17
19
|
)
|
|
18
20
|
|
|
19
21
|
|
|
20
|
-
def find_large_base64_blob(text: str) ->
|
|
21
|
-
|
|
22
|
-
match = _BASE64_BLOB_PATTERN.search(text)
|
|
22
|
+
def find_large_base64_blob(text: str) -> str | None:
|
|
23
|
+
match = _BLOB.search(text)
|
|
23
24
|
return match.group(0) if match else None
|
|
24
25
|
|
|
25
26
|
|
|
26
|
-
def open_from(dirs, file_name):
|
|
27
|
-
for
|
|
28
|
-
|
|
29
|
-
if
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
with open(full_file_name, "rb") as f:
|
|
33
|
-
content = f.read()
|
|
34
|
-
return content.decode("utf-8")
|
|
35
|
-
|
|
27
|
+
def open_from(dirs, file_name) -> str | None:
|
|
28
|
+
for d in dirs:
|
|
29
|
+
path = os.path.join(d, file_name)
|
|
30
|
+
if os.path.isfile(path):
|
|
31
|
+
with open(path, encoding="utf-8", newline="") as f:
|
|
32
|
+
return f.read()
|
|
36
33
|
return None
|
|
37
34
|
|
|
38
35
|
|
|
39
|
-
def find_resource_dir(dirs, file_name):
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
loading it can never disagree.
|
|
44
|
-
"""
|
|
45
|
-
for dir in dirs:
|
|
46
|
-
if os.path.exists(os.path.join(dir, file_name)):
|
|
47
|
-
return dir
|
|
48
|
-
|
|
36
|
+
def find_resource_dir(dirs, file_name) -> str | None:
|
|
37
|
+
for d in dirs:
|
|
38
|
+
if os.path.exists(os.path.join(d, file_name)):
|
|
39
|
+
return d
|
|
49
40
|
return None
|
|
50
41
|
|
|
51
42
|
|
|
52
|
-
def resolve_linked_resource(dirs, file_name):
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
return None if resource_dir is None else os.path.join(resource_dir, file_name)
|
|
43
|
+
def resolve_linked_resource(dirs, file_name) -> str | None:
|
|
44
|
+
d = find_resource_dir(dirs, file_name)
|
|
45
|
+
return None if d is None else os.path.join(d, file_name)
|
|
56
46
|
|
|
57
47
|
|
|
58
48
|
def relative_resource_path(base_dir: str, resource_dir: str, target: str) -> str:
|
|
59
|
-
"""The path of target in resource_dir, relative to base_dir, with `/` as separator.
|
|
60
|
-
|
|
61
|
-
The dir part is computed lexically (symlinks not resolved) and the target is appended as written (`..` kept),
|
|
62
|
-
so joining the result onto base_dir names the same file as os.path.join(resource_dir, target). When no relative
|
|
63
|
-
path exists (another drive on Windows), the absolute path is returned instead, still with `/`.
|
|
64
|
-
"""
|
|
65
49
|
try:
|
|
66
|
-
|
|
50
|
+
rel = os.path.relpath(os.path.abspath(resource_dir), os.path.abspath(base_dir))
|
|
67
51
|
except ValueError:
|
|
68
|
-
return os.path.join(resource_dir, target).replace(os.sep, "/")
|
|
69
|
-
if
|
|
52
|
+
return os.path.join(os.path.abspath(resource_dir), target).replace(os.sep, "/")
|
|
53
|
+
if rel == ".":
|
|
70
54
|
return target
|
|
71
|
-
return
|
|
72
|
-
|
|
55
|
+
return rel.replace(os.sep, "/") + "/" + target
|
|
73
56
|
|
|
74
|
-
def load_linked_resources(template_dirs: list[str], resources_list, module_name: str):
|
|
75
|
-
linked_resources = {}
|
|
76
57
|
|
|
58
|
+
def load_linked_resources(template_dirs: list[str], resources_list, module_name: str) -> dict[str, str]:
|
|
59
|
+
"""Read every linked file from template_dirs; return a mapping from target to text, each target read once."""
|
|
60
|
+
loaded: dict[str, str] = {}
|
|
77
61
|
for resource in resources_list:
|
|
78
|
-
|
|
79
|
-
if
|
|
62
|
+
target = resource["target"] if isinstance(resource, dict) else resource
|
|
63
|
+
if target in loaded:
|
|
80
64
|
continue
|
|
81
|
-
|
|
82
65
|
try:
|
|
83
|
-
|
|
84
|
-
except UnicodeDecodeError:
|
|
66
|
+
text = open_from(template_dirs, target)
|
|
67
|
+
except UnicodeDecodeError as e:
|
|
85
68
|
raise UnsupportedResourceType(
|
|
86
|
-
f"Referenced resource '{
|
|
87
|
-
|
|
88
|
-
)
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
blob = find_large_base64_blob(content)
|
|
69
|
+
f"Referenced resource '{target}' in module '{module_name}' is a binary file. "
|
|
70
|
+
"Only text files (e.g. .md, .txt, .json, .yaml) can be referenced from a .plain file."
|
|
71
|
+
) from e
|
|
72
|
+
if text is None:
|
|
73
|
+
raise FileNotFoundError(f"Resource file '{target}' referenced in module '{module_name}' not found.")
|
|
74
|
+
blob = find_large_base64_blob(text)
|
|
94
75
|
if blob is not None:
|
|
95
76
|
raise UnsupportedBase64Content(
|
|
96
|
-
f"Referenced resource '{
|
|
97
|
-
f"
|
|
98
|
-
"
|
|
99
|
-
"
|
|
100
|
-
"save the data to a separate file and include the file path in the specification without it being a reference file."
|
|
77
|
+
f"Referenced resource '{target}' in module '{module_name}' contains a large base64-encoded blob "
|
|
78
|
+
f"({len(blob)} characters), such as an embedded image. Inline base64 data is not supported. "
|
|
79
|
+
"Remove the data from the resource. If the data should be used by the end software, save the data "
|
|
80
|
+
"to a separate file and include the file path in the specification without it being a reference file."
|
|
101
81
|
)
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
return linked_resources
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
class TrackingFileSystemLoader(Plain2CodeLoaderMixin, FileSystemLoader):
|
|
109
|
-
def __init__(self, *args, **kwargs):
|
|
110
|
-
super().__init__(*args, **kwargs)
|
|
111
|
-
self.loaded_templates = {}
|
|
112
|
-
|
|
113
|
-
def get_source(self, env, template_name, **kwargs):
|
|
114
|
-
source = super().get_source(env, template_name, **kwargs)
|
|
115
|
-
self.loaded_templates[template_name] = source.source
|
|
116
|
-
return source
|
|
82
|
+
loaded[target] = text
|
|
83
|
+
return loaded
|
|
117
84
|
|
|
118
85
|
|
|
119
86
|
def liquid_error_message(error: LiquidSyntaxError) -> str:
|
|
120
|
-
|
|
121
|
-
|
|
87
|
+
"""Format a Liquid syntax error as a PlainSyntaxError message."""
|
|
88
|
+
template = error.template_name
|
|
89
|
+
position = ""
|
|
122
90
|
token = error.token
|
|
123
|
-
if token is None
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
91
|
+
if token is not None and token.start >= 0:
|
|
92
|
+
source = token.source
|
|
93
|
+
line = source.count("\n", 0, token.start) + 1
|
|
94
|
+
column = token.start - (source.rfind("\n", 0, token.start) + 1)
|
|
95
|
+
position = f" at {template}:{line}:{column}" if template else f" at {line}:{column}"
|
|
96
|
+
elif template:
|
|
97
|
+
position = f" in {template}"
|
|
98
|
+
return f"Plain syntax error: Invalid Liquid{position}: {error.message}"
|
|
130
99
|
|
|
131
100
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
# to identify the templates that are being loaded
|
|
101
|
+
class TrackingFileSystemLoader(Plain2CodeLoaderMixin, FileSystemLoader):
|
|
102
|
+
"""File system loader that records every loaded template source by name."""
|
|
135
103
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
104
|
+
def __init__(self, search_path):
|
|
105
|
+
super().__init__(search_path)
|
|
106
|
+
self.loaded_templates: dict[str, str] = {}
|
|
107
|
+
self._last_raw = ""
|
|
139
108
|
|
|
140
|
-
|
|
141
|
-
|
|
109
|
+
def _read(self, source_path: Path):
|
|
110
|
+
source, mtime = super()._read(source_path)
|
|
111
|
+
self._last_raw = source
|
|
112
|
+
return source, mtime
|
|
142
113
|
|
|
114
|
+
def get_source(self, env, template_name, **kwargs):
|
|
115
|
+
result = super().get_source(env, template_name, **kwargs)
|
|
116
|
+
self.loaded_templates[template_name] = self._last_raw
|
|
117
|
+
return result
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def get_loaded_templates(
|
|
121
|
+
source_path, plain_source, template_name=None, code_variables=None
|
|
122
|
+
) -> tuple[str, dict[str, str]]:
|
|
123
|
+
"""Render plain_source with Liquid; return the text and a mapping of loaded template name to source."""
|
|
124
|
+
dirs = [source_path] if isinstance(source_path, (str, os.PathLike)) else list(source_path)
|
|
125
|
+
loader = TrackingFileSystemLoader(dirs)
|
|
126
|
+
env = Environment(loader=loader, undefined=StrictUndefined)
|
|
127
|
+
env.tags["include"] = Plain2CodeIncludeTag(env)
|
|
128
|
+
env.filters["code_variable"] = code_variable_liquid_filter
|
|
129
|
+
env.filters["prohibited_chars"] = prohibited_chars_liquid_filter
|
|
143
130
|
try:
|
|
144
|
-
|
|
145
|
-
|
|
131
|
+
template = env.from_string(plain_source, name=template_name or "")
|
|
132
|
+
rendered = template.render(**({} if code_variables is None else {"code_variables": code_variables}))
|
|
146
133
|
except LiquidSyntaxError as e:
|
|
147
|
-
|
|
134
|
+
if not e.template_name and template_name:
|
|
135
|
+
e.template_name = template_name
|
|
136
|
+
raise PlainSyntaxError(liquid_error_message(e)) from e
|
|
148
137
|
except UndefinedError as e:
|
|
149
|
-
raise Exception(f"Undefined liquid variable: {
|
|
138
|
+
raise Exception(f"Undefined liquid variable: {e.message}") from e
|
|
139
|
+
except TemplateNotFoundError as e:
|
|
140
|
+
name = _missing_name(e)
|
|
141
|
+
raise TemplateNotFoundError(f"Template not found: {name}", filename=name) from e
|
|
142
|
+
return rendered, loader.loaded_templates
|
|
150
143
|
|
|
151
|
-
|
|
144
|
+
|
|
145
|
+
def _missing_name(error: TemplateNotFoundError) -> str:
|
|
146
|
+
token = error.token
|
|
147
|
+
if token is not None:
|
|
148
|
+
return str(getattr(token, "value", token))
|
|
149
|
+
return str(error.args[0]) if error.args else str(error.template_name)
|