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/loaders.py CHANGED
@@ -1,151 +1,149 @@
1
+ """Resource loading helpers."""
2
+
1
3
  import os
2
4
  import re
3
- from typing import Optional
5
+ from pathlib import Path
4
6
 
5
- from liquid2 import Environment, FileSystemLoader, StrictUndefined
6
- from liquid2.exceptions import LiquidSyntaxError, UndefinedError
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
- # 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
+ _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) -> Optional[str]:
21
- """Return the first contiguous base64 blob at or above the threshold, or None."""
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 dir in dirs:
28
- full_file_name = os.path.join(dir, file_name)
29
- if not os.path.isfile(full_file_name):
30
- continue
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
- """Return the first dir in which file_name exists, or None if not found.
41
-
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
-
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
- """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)
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
- rel_dir = os.path.relpath(resource_dir, base_dir)
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 rel_dir == os.curdir:
52
+ return os.path.join(os.path.abspath(resource_dir), target).replace(os.sep, "/")
53
+ if rel == ".":
70
54
  return target
71
- return rel_dir.replace(os.sep, "/") + "/" + target
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
- file_name = resource["target"]
79
- if file_name in linked_resources:
62
+ target = resource["target"] if isinstance(resource, dict) else resource
63
+ if target in loaded:
80
64
  continue
81
-
82
65
  try:
83
- content = open_from(template_dirs, file_name)
84
- except UnicodeDecodeError:
66
+ text = open_from(template_dirs, target)
67
+ except UnicodeDecodeError as e:
85
68
  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)
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 '{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."
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
- linked_resources[file_name] = content
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
- # Built from attributes: str() of some liquid2 syntax errors (e.g. an unterminated `{{ x`) raises ValueError.
121
- template_name = error.template_name or None
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 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}"
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
- 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
101
+ class TrackingFileSystemLoader(Plain2CodeLoaderMixin, FileSystemLoader):
102
+ """File system loader that records every loaded template source by name."""
135
103
 
136
- liquid_loader = TrackingFileSystemLoader(source_path)
137
- liquid_env = Environment(loader=liquid_loader, undefined=StrictUndefined)
138
- liquid_env.tags["include"] = Plain2CodeIncludeTag(liquid_env)
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
- liquid_env.filters["code_variable"] = plain_spec.code_variable_liquid_filter
141
- liquid_env.filters["prohibited_chars"] = plain_spec.prohibited_chars_liquid_filter
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
- plain_source_template = liquid_env.from_string(plain_source, name=template_name or "")
145
- plain_source = plain_source_template.render()
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
- raise PlainSyntaxError(liquid_error_message(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
148
137
  except UndefinedError as e:
149
- raise Exception(f"Undefined liquid variable: {str(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
142
+ return rendered, loader.loaded_templates
150
143
 
151
- return plain_source, liquid_loader.loaded_templates
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)