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.
@@ -1,62 +1,44 @@
1
- """Liquid include tag that indents the included template, and the loader mixin that does it."""
1
+ """Liquid include tag that indents the included template, and the loader mixin that does the indenting."""
2
2
 
3
- from typing import TextIO
3
+ from contextvars import ContextVar
4
+ from typing import TYPE_CHECKING, Any, TextIO
4
5
 
5
- from liquid2 import RenderContext
6
+ from liquid2 import TemplateSource
6
7
  from liquid2.builtin.tags.include_tag import IncludeNode, IncludeTag
7
- from liquid2.exceptions import TemplateNotFoundError
8
- from liquid2.loader import TemplateSource
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: strips trailing whitespace of a template and indents its lines after the first."""
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, indent=0, **kwargs):
15
- source = super().get_source(env, template_name, context=context, **kwargs) # type: ignore[misc]
16
- text = source.source.rstrip()
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
- __slots__ = ()
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
- return source[source.rfind("\n", 0, start) + 1 : start]
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.token.source[self.token.start : self.token.stop].replace('"', "'")
34
+ text = str(self)
34
35
  buffer.write(text)
35
36
  return len(text)
36
- indent = len(prefix) - len(prefix.lstrip(" "))
37
- name = str(self.name.evaluate(context))
37
+ reset = _include_indent.set(len(prefix) - len(prefix.lstrip(" ")))
38
38
  try:
39
- template = context.env.get_template(name, context=context, tag=self.tag, indent=indent)
40
- except TemplateNotFoundError as err:
41
- err.token = self.name.token
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
- """Resource loading helpers."""
1
+ """Looking up and loading files, linked resources and Liquid templates."""
2
2
 
3
3
  import os
4
4
  import re
5
- from pathlib import Path
5
+ from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
6
6
 
7
- from liquid2 import Environment, StrictUndefined
8
- from liquid2.builtin import FileSystemLoader
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
- _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
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 | None:
23
- match = _BLOB.search(text)
24
- return match.group(0) if match else None
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 | None:
28
- for d in dirs:
29
- path = os.path.join(d, file_name)
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 f:
32
- return f.read()
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 | None:
37
- for d in dirs:
38
- if os.path.exists(os.path.join(d, file_name)):
39
- return d
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 | None:
44
- d = find_resource_dir(dirs, file_name)
45
- return None if d is None else os.path.join(d, 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)
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
- rel = os.path.relpath(os.path.abspath(resource_dir), os.path.abspath(base_dir))
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 rel == ".":
65
+ if directory == os.curdir:
54
66
  return target
55
- return rel.replace(os.sep, "/") + "/" + target
67
+ return directory.replace(os.sep, "/") + "/" + target
56
68
 
57
69
 
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] = {}
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"] if isinstance(resource, dict) else resource
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 e:
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 e
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
- """Format a Liquid syntax error as a PlainSyntaxError message."""
88
- template = error.template_name
89
- position = ""
90
- token = error.token
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)
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
- elif template:
97
- position = f" in {template}"
98
- return f"Plain syntax error: Invalid Liquid{position}: {error.message}"
99
-
100
-
101
- class TrackingFileSystemLoader(Plain2CodeLoaderMixin, FileSystemLoader):
102
- """File system loader that records every loaded template source by name."""
103
-
104
- def __init__(self, search_path):
105
- super().__init__(search_path)
106
- self.loaded_templates: dict[str, str] = {}
107
- self._last_raw = ""
108
-
109
- def _read(self, source_path: Path):
110
- source, mtime = super()._read(source_path)
111
- self._last_raw = source
112
- return source, mtime
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
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
- template = env.from_string(plain_source, name=template_name or "")
132
- rendered = template.render(**({} if code_variables is None else {"code_variables": code_variables}))
133
- except LiquidSyntaxError as e:
134
- if not e.template_name and template_name:
135
- e.template_name = template_name
136
- raise PlainSyntaxError(liquid_error_message(e)) from e
137
- except UndefinedError as e:
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
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 _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)
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)