plain-parser 0.2.1.dev23__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/loaders.py CHANGED
@@ -1,151 +1,162 @@
1
+ """Looking up and loading files, linked resources and Liquid templates."""
2
+
1
3
  import os
2
4
  import re
3
- from typing import Optional
5
+ from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
4
6
 
5
- from liquid2 import Environment, FileSystemLoader, StrictUndefined
7
+ from liquid2 import Environment, FileSystemLoader, StrictUndefined, TemplateNotFoundError
6
8
  from liquid2.exceptions import LiquidSyntaxError, UndefinedError
7
9
 
8
- from plain_parser import plain_spec
9
10
  from plain_parser.exceptions import PlainSyntaxError, UnsupportedBase64Content, UnsupportedResourceType
10
11
  from plain_parser.liquid_nodes import Plain2CodeIncludeTag, Plain2CodeLoaderMixin
12
+ from plain_parser.plain_spec import code_variable_liquid_filter, prohibited_chars_liquid_filter
11
13
 
12
14
  MAX_BASE64_BLOB_LENGTH = 8192
13
15
 
14
- # Matches a long contiguous base64 / base64url run, optionally preceded by a data: URI header.
15
- _BASE64_BLOB_PATTERN = re.compile(
16
- r"(?:data:[\w.+-]+/[\w.+-]+;base64,)?[A-Za-z0-9+/_-]{%d,}={0,2}" % MAX_BASE64_BLOB_LENGTH
17
- )
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")
18
18
 
19
19
 
20
20
  def find_large_base64_blob(text: str) -> Optional[str]:
21
- """Return the first contiguous base64 blob at or above the threshold, or None."""
22
- match = _BASE64_BLOB_PATTERN.search(text)
23
- return match.group(0) if match else None
24
-
25
-
26
- def open_from(dirs, file_name):
27
- for dir in dirs:
28
- full_file_name = os.path.join(dir, file_name)
29
- if not os.path.isfile(full_file_name):
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:
30
24
  continue
31
-
32
- with open(full_file_name, "rb") as f:
33
- content = f.read()
34
- return content.decode("utf-8")
35
-
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]
36
32
  return None
37
33
 
38
34
 
39
- def find_resource_dir(dirs, file_name):
40
- """Return the first dir in which file_name exists, or None if not found.
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)
39
+ if os.path.isfile(path):
40
+ with open(path, encoding="utf-8", newline="") as file:
41
+ return file.read()
42
+ return None
41
43
 
42
- Mirrors the search order used by open_from so that validating a linked resource and
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
44
 
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)
49
50
  return None
50
51
 
51
52
 
52
- def resolve_linked_resource(dirs, file_name):
53
- """Return the first existing path for file_name across dirs, or None if not found."""
54
- resource_dir = find_resource_dir(dirs, file_name)
55
- return None if resource_dir is None else os.path.join(resource_dir, file_name)
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)
56
57
 
57
58
 
58
59
  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
- """
60
+ """Name a file of a resource directory relative to a base directory, with `/` as separator."""
65
61
  try:
66
- rel_dir = os.path.relpath(resource_dir, base_dir)
62
+ directory = os.path.relpath(resource_dir, base_dir)
67
63
  except ValueError:
68
- return os.path.join(resource_dir, target).replace(os.sep, "/")
69
- if rel_dir == os.curdir:
64
+ return os.path.join(os.path.abspath(resource_dir), target).replace(os.sep, "/")
65
+ if directory == os.curdir:
70
66
  return target
71
- return rel_dir.replace(os.sep, "/") + "/" + target
67
+ return directory.replace(os.sep, "/") + "/" + target
72
68
 
73
69
 
74
- def load_linked_resources(template_dirs: list[str], resources_list, module_name: str):
75
- linked_resources = {}
76
-
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] = {}
77
73
  for resource in resources_list:
78
- file_name = resource["target"]
79
- if file_name in linked_resources:
74
+ target = resource["target"]
75
+ if target in loaded:
80
76
  continue
81
-
82
77
  try:
83
- content = open_from(template_dirs, file_name)
84
- except UnicodeDecodeError:
78
+ text = open_from(template_dirs, target)
79
+ except UnicodeDecodeError as error:
85
80
  raise UnsupportedResourceType(
86
- f"Referenced resource '{file_name}' in module '{module_name}' is a binary file. "
87
- f"Only text files (e.g. .md, .txt, .json, .yaml) can be referenced from a .plain file."
88
- )
89
-
90
- if content is None:
91
- raise FileNotFoundError(f"Resource file '{file_name}' referenced in module '{module_name}' not found.")
92
-
93
- blob = find_large_base64_blob(content)
81
+ f"Referenced resource '{target}' in module '{module_name}' is a binary file. "
82
+ "Only text files (e.g. .md, .txt, .json, .yaml) can be referenced from a .plain file."
83
+ ) from error
84
+ if text is None:
85
+ raise FileNotFoundError(f"Resource file '{target}' referenced in module '{module_name}' not found.")
86
+ blob = find_large_base64_blob(text)
94
87
  if blob is not None:
95
88
  raise UnsupportedBase64Content(
96
- f"Referenced resource '{file_name}' in module '{module_name}' contains a large "
97
- f"base64-encoded blob ({len(blob)} characters), such as an embedded image. Inline "
98
- "base64 data is not supported. Remove the data from the resource. "
99
- "If the data should be used by the end software, "
100
- "save the data to a separate file and include the file path in the specification without it being a reference file."
89
+ f"Referenced resource '{target}' in module '{module_name}' contains a large base64-encoded blob "
90
+ f"({len(blob)} characters), such as an embedded image. Inline base64 data is not supported. "
91
+ "Remove the data from the resource. If the data should be used by the end software, save the data "
92
+ "to a separate file and include the file path in the specification without it being a reference file."
101
93
  )
94
+ loaded[target] = text
95
+ return loaded
96
+
102
97
 
103
- linked_resources[file_name] = content
98
+ def liquid_error_message(error: LiquidSyntaxError) -> str:
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)
108
+ position = f" at {template}:{line}:{column}" if template else f" at {line}:{column}"
109
+ else:
110
+ position = f" in {template}" if template else ""
111
+ return f"Plain syntax error: Invalid Liquid{position}: {message}"
104
112
 
105
- return linked_resources
106
113
 
114
+ class _PlainTemplateNotFoundError(TemplateNotFoundError):
115
+ def __str__(self) -> str:
116
+ return str(self.args[0])
107
117
 
108
- class TrackingFileSystemLoader(Plain2CodeLoaderMixin, FileSystemLoader):
109
- def __init__(self, *args, **kwargs):
110
- super().__init__(*args, **kwargs)
111
- self.loaded_templates = {}
112
118
 
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
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] = {}
117
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
118
128
 
119
- def liquid_error_message(error: LiquidSyntaxError) -> str:
120
- # Built from attributes: str() of some liquid2 syntax errors (e.g. an unterminated `{{ x`) raises ValueError.
121
- template_name = error.template_name or None
122
- token = error.token
123
- if token is None or token.start < 0:
124
- where = f" in {template_name}" if template_name else ""
125
- else:
126
- line = token.source[: token.start].count("\n") + 1
127
- column = token.start - (token.source.rfind("\n", 0, token.start) + 1)
128
- where = f" at {template_name}:{line}:{column}" if template_name else f" at {line}:{column}"
129
- return f"Plain syntax error: Invalid Liquid{where}: {error.message}"
130
129
 
130
+ class TrackingFileSystemLoader(Plain2CodeLoaderMixin, _RecordingFileSystemLoader):
131
+ """File system loader that records every loaded template source by name and indents included templates."""
131
132
 
132
- def get_loaded_templates(source_path, plain_source, template_name=None):
133
- # Render the plain source with Liquid templating engine
134
- # to identify the templates that are being loaded
135
133
 
136
- liquid_loader = TrackingFileSystemLoader(source_path)
137
- liquid_env = Environment(loader=liquid_loader, undefined=StrictUndefined)
138
- liquid_env.tags["include"] = Plain2CodeIncludeTag(liquid_env)
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
139
141
 
140
- liquid_env.filters["code_variable"] = plain_spec.code_variable_liquid_filter
141
- liquid_env.filters["prohibited_chars"] = plain_spec.prohibited_chars_liquid_filter
142
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}
143
148
  try:
144
- plain_source_template = liquid_env.from_string(plain_source, name=template_name or "")
145
- plain_source = plain_source_template.render()
146
- except LiquidSyntaxError as e:
147
- raise PlainSyntaxError(liquid_error_message(e))
148
- except UndefinedError as e:
149
- raise Exception(f"Undefined liquid variable: {str(e)}")
150
-
151
- return plain_source, liquid_loader.loaded_templates
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
157
+ return rendered, loader.loaded_templates
158
+
159
+
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)