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 CHANGED
@@ -1,7 +1,7 @@
1
- """Parser for ***plain specification files."""
1
+ """plain-parser."""
2
2
 
3
- from plain_parser import concept_utils, exceptions, loaders, plain_file, plain_spec, project, test_plain_file
4
- from plain_parser.plain_file import (
3
+ from . import concept_utils, exceptions, loaders, plain_file, plain_spec, project, test_plain_file
4
+ from .plain_file import (
5
5
  PlainFileParseResult,
6
6
  get_filename_from_module_name,
7
7
  get_module_name_from_filename,
plain_parser/cli.py CHANGED
@@ -1,20 +1,17 @@
1
- """Command-line entry point: ``plain-parser {check,parse} <file.plain> [--template-dir DIR] [--tests-folder DIR]...
2
- [--config-name NAME]``."""
1
+ """Command line of plain-parser."""
3
2
 
4
3
  import argparse
5
4
  import json
6
5
  import os
7
6
  import sys
8
7
  from dataclasses import dataclass, field
8
+ from typing import Any
9
9
 
10
10
  import yaml
11
11
 
12
- from plain_parser import loaders, plain_spec, project
12
+ from . import loaders, plain_spec, project
13
13
 
14
14
  DEFAULT_CONFIG_NAME = "config.yaml"
15
- TEMPLATE_DIR_CONFIG_KEYS = ("template_dir", "template-dir")
16
- TESTS_FOLDER_CONFIG_KEYS = ("tests_folder", "tests-folder")
17
- CONFORMANCE_TESTS_SCRIPT_CONFIG_KEYS = ("conformance_tests_script", "conformance-tests-script")
18
15
  PARSE_FORMAT_VERSION = 2
19
16
 
20
17
 
@@ -22,110 +19,78 @@ class AmbiguousConfigFileError(Exception):
22
19
  pass
23
20
 
24
21
 
25
- def build_parser() -> argparse.ArgumentParser:
26
- parser = argparse.ArgumentParser(prog="plain-parser", description="Tools for ***plain specification files.")
27
- subparsers = parser.add_subparsers(dest="command", required=True)
28
-
29
- check_parser = subparsers.add_parser(
30
- "check",
31
- help="Validate a .plain module, its requires chain and its test plain files, and read every linked file: "
32
- "binary files and large base64 blobs are rejected.",
33
- )
34
- parse_parser = subparsers.add_parser(
35
- "parse",
36
- help="Print the parse result of a .plain module, its requires chain and its test plain files as JSON. "
37
- "Linked files are located but never read.",
38
- )
39
- for subparser in (check_parser, parse_parser):
40
- subparser.add_argument("plain_file", help="Path to the .plain module.")
41
- subparser.add_argument(
42
- "--template-dir",
43
- help="Directory searched for modules and templates after the .plain file's own directory. "
44
- "Overrides the template-dir value of the config file.",
45
- )
46
- subparser.add_argument(
47
- "--tests-folder",
48
- action="append",
49
- metavar="DIR",
50
- help="Directory scanned for test plain files; repeat the option for more than one. Overrides the "
51
- "tests-folder value of the config file. Without both, no test plain files are read.",
52
- )
53
- subparser.add_argument(
54
- "--config-name",
55
- default=DEFAULT_CONFIG_NAME,
56
- help="Name of the config file to read template-dir, tests-folder and conformance-tests-script from. "
57
- "Looked up in the .plain file's directory and the current working directory. Defaults to %(default)s.",
58
- )
59
- return parser
60
-
61
-
62
- def resolve_config_file(config_name: str, plain_file_path: str) -> str | None:
63
- """The config file next to the .plain file, else the one in the working directory, else None."""
64
- plain_file_dir = os.path.dirname(os.path.abspath(plain_file_path))
65
- plain_dir_config = os.path.normpath(os.path.join(plain_file_dir, config_name))
66
- cwd_config = os.path.normpath(os.path.join(os.getcwd(), config_name))
67
-
68
- in_plain_dir = os.path.exists(plain_dir_config)
69
- in_cwd = os.path.exists(cwd_config)
70
- if in_plain_dir and in_cwd and plain_dir_config != cwd_config:
71
- raise AmbiguousConfigFileError(
72
- f"Config file '{config_name}' was found in two locations:\n"
73
- f" - Plain file directory: {plain_file_dir}\n"
74
- f" - Current working directory: {os.getcwd()}\n"
75
- f"Remove the config file from one of these locations to resolve the ambiguity."
76
- )
77
- if in_plain_dir:
78
- return plain_dir_config
79
- if in_cwd:
80
- return cwd_config
81
- return None
22
+ class ConfigReadError(Exception):
23
+ pass
82
24
 
83
25
 
84
26
  @dataclass
85
27
  class Config:
86
28
  template_dir: str | None = None
87
- tests_folders: list[str] | None = None # None when the config does not set tests-folder.
88
- conformance_tests_enabled: bool = False # Whether the config names a conformance-tests-script.
29
+ tests_folders: list[str] | None = None
30
+ conformance_tests_enabled: bool = False
89
31
 
90
32
 
91
- def _config_value(config: dict, keys: tuple[str, ...]):
92
- """The first value set under one of the key spellings, or None."""
93
- return next((config[key] for key in keys if config.get(key)), None)
33
+ @dataclass
34
+ class ParseResult:
35
+ modules: list[tuple[str, dict]]
36
+ resources: dict[str, str]
37
+ test_plain_files: dict[str, dict] = field(default_factory=dict)
94
38
 
95
39
 
96
- def read_config(config_file: str) -> Config:
97
- """The values plain-parser reads from the config file, paths resolved against the file's directory. Other keys
98
- are ignored."""
99
- with open(config_file) as f:
100
- config = yaml.safe_load(f) or {}
40
+ def build_parser() -> argparse.ArgumentParser:
41
+ parser = argparse.ArgumentParser(prog="plain-parser")
42
+ sub = parser.add_subparsers(dest="command", required=True)
43
+ for name in ("check", "parse"):
44
+ p = sub.add_parser(name)
45
+ p.add_argument("filename")
46
+ p.add_argument("--template-dir", dest="template_dir", metavar="DIR", default=None)
47
+ p.add_argument("--tests-folder", dest="tests_folder", metavar="DIR", action="append", default=None)
48
+ p.add_argument("--config-name", dest="config_name", metavar="NAME", default=DEFAULT_CONFIG_NAME)
49
+ return parser
101
50
 
102
- def resolve(value) -> str:
103
- value = os.path.expanduser(str(value))
104
- return value if os.path.isabs(value) else os.path.join(os.path.dirname(config_file), value)
105
51
 
106
- result = Config()
107
- template_dir = _config_value(config, TEMPLATE_DIR_CONFIG_KEYS)
108
- if template_dir:
109
- result.template_dir = resolve(template_dir)
110
- tests_folder = _config_value(config, TESTS_FOLDER_CONFIG_KEYS)
111
- if tests_folder:
112
- result.tests_folders = [
113
- resolve(value) for value in (tests_folder if isinstance(tests_folder, list) else [tests_folder])
114
- ]
115
- result.conformance_tests_enabled = bool(_config_value(config, CONFORMANCE_TESTS_SCRIPT_CONFIG_KEYS))
116
- return result
52
+ def resolve_config_file(config_name: str, plain_file_path: str) -> str | None:
53
+ candidates = []
54
+ for base in (os.path.dirname(os.path.abspath(plain_file_path)), os.getcwd()):
55
+ path = os.path.join(base, config_name)
56
+ if os.path.isfile(path) and path not in candidates:
57
+ candidates.append(path)
58
+ if len(candidates) > 1:
59
+ dirs = " and ".join(os.path.dirname(c) for c in candidates)
60
+ raise AmbiguousConfigFileError(f"Config file {config_name} found in two locations: {dirs}")
61
+ return candidates[0] if candidates else None
62
+
63
+
64
+ def _key(data: dict, name: str) -> Any:
65
+ for k in (name, name.replace("-", "_")):
66
+ if data.get(k):
67
+ return data[k]
68
+ return None
117
69
 
118
70
 
119
- @dataclass
120
- class ParseResult:
121
- modules: list[
122
- tuple[str, dict]
123
- ] # (module name, plain source tree) for the chain, deepest ancestor first, entry last.
124
- # Each link target in the chain, as written, to the path it resolves to, relative to the entry module's dir
125
- # with `/` as separator (loaders.relative_resource_path).
126
- resources: dict[str, str]
127
- # Each test plain file, by its path relative to the entry module's dir with `/`, to the functionality it binds to.
128
- test_plain_files: dict[str, dict] = field(default_factory=dict)
71
+ def read_config(config_file: str) -> Config:
72
+ try:
73
+ with open(config_file, encoding="utf-8") as f:
74
+ data: Any = yaml.safe_load(f) or {}
75
+ if not isinstance(data, dict):
76
+ raise ValueError("config file is not a mapping")
77
+ except (OSError, UnicodeDecodeError, ValueError, yaml.YAMLError) as e:
78
+ raise ConfigReadError(f"Error reading config file: {e}") from e
79
+ base = os.path.dirname(os.path.abspath(config_file))
80
+
81
+ def rel(p: str) -> str:
82
+ p = os.path.expanduser(str(p))
83
+ return p if os.path.isabs(p) else os.path.join(base, p)
84
+
85
+ folders = _key(data, "tests-folder")
86
+ if isinstance(folders, str):
87
+ folders = [folders]
88
+ template_dir = _key(data, "template-dir")
89
+ return Config(
90
+ template_dir=rel(template_dir) if template_dir else None,
91
+ tests_folders=[rel(p) for p in folders if p] if folders else None,
92
+ conformance_tests_enabled=bool(_key(data, "conformance-tests-script")),
93
+ )
129
94
 
130
95
 
131
96
  def parse_spec(
@@ -135,48 +100,29 @@ def parse_spec(
135
100
  tests_folders: list[str] | None = None,
136
101
  require_test_plain_files: bool = False,
137
102
  ) -> ParseResult:
138
- """Parse the module, its requires chain and its test plain files, resolve the links, and walk the entry's
139
- FRIDs; raise on the first error.
140
-
141
- Without ``tests_folders`` no test plain files are read. With ``require_test_plain_files``, every functionality needs a
142
- test plain file bound to it. With ``load_resources``, each module's linked files are
143
- also read and checked (text only, no large base64 blob) right after that module's links are collected, so a
144
- resource error is reported before a FRID-walk error.
145
- """
146
- # Absolute, so the chain parse and the resource paths below search the same directories.
147
103
  entry_dir = os.path.dirname(os.path.abspath(plain_file_path))
148
- template_dirs = [entry_dir]
104
+ dirs = [entry_dir]
149
105
  if template_dir:
150
- template_dirs.append(os.path.abspath(template_dir))
151
- tests_folders = [os.path.abspath(tests_folder) for tests_folder in tests_folders or []]
152
-
153
- parsed = project.parse_project(
154
- os.path.basename(plain_file_path), template_dirs, tests_folders, require_test_plain_files
155
- )
156
- chain = parsed.chain
157
-
158
- # The target joined as written onto its template dir (`..` kept, symlinks not resolved), made relative to the
159
- # entry module's dir so the result does not depend on where the project sits on the machine.
106
+ dirs.append(os.path.abspath(template_dir))
107
+ result = project.parse_project(os.path.basename(plain_file_path), dirs, tests_folders or [], require_test_plain_files)
160
108
  resources: dict[str, str] = {}
161
- for module_name, plain_source_tree in chain:
162
- resources_list: list[dict] = []
163
- plain_spec.collect_linked_resources(plain_source_tree, resources_list, None, True)
109
+ for name, tree in result.chain:
110
+ registry: list[dict] = []
111
+ plain_spec.collect_linked_resources(tree, registry, None, True)
164
112
  if load_resources:
165
- loaders.load_linked_resources(template_dirs, resources_list, module_name)
166
- for resource in resources_list:
167
- target = resource["target"]
168
- resource_dir = loaders.find_resource_dir(template_dirs, target)
169
- resources[target] = loaders.relative_resource_path(template_dirs[0], resource_dir, target)
170
-
171
- _, top_plain_source_tree = chain[-1]
172
- for frid in plain_spec.get_frids(top_plain_source_tree):
173
- plain_spec.get_specifications_for_frid(top_plain_source_tree, frid)
174
-
175
- test_plain_files = {
176
- bound.name: {"module": bound.parsed.module, "func_id": bound.parsed.func_id}
177
- for bound in parsed.test_plain_files
178
- }
179
- return ParseResult(chain, resources, test_plain_files)
113
+ loaders.load_linked_resources(dirs, registry, name)
114
+ for link in registry:
115
+ target = link["target"]
116
+ if target in resources:
117
+ continue
118
+ found = loaders.find_resource_dir(dirs, target)
119
+ if found is not None:
120
+ resources[target] = loaders.relative_resource_path(entry_dir, found, target)
121
+ entry_tree = result.chain[-1][1]
122
+ for frid in plain_spec.get_frids(entry_tree):
123
+ plain_spec.get_specifications_for_frid(entry_tree, frid)
124
+ bound = {b.name: {"module": b.parsed.module, "func_id": b.parsed.func_id} for b in result.test_plain_files}
125
+ return ParseResult(result.chain, resources, bound)
180
126
 
181
127
 
182
128
  def check(
@@ -185,119 +131,116 @@ def check(
185
131
  tests_folders: list[str] | None = None,
186
132
  require_test_plain_files: bool = False,
187
133
  ) -> None:
188
- """Raise if the module, its requires chain, its test plain files, or its linked resources are invalid."""
189
134
  parse_spec(plain_file_path, template_dir, True, tests_folders, require_test_plain_files)
190
135
 
191
136
 
192
- def _error_output(type_name: str, message: str) -> dict:
193
- return {"format_version": PARSE_FORMAT_VERSION, "type": type_name, "message": message}
194
-
195
-
196
- def _escape(text: str) -> str:
197
- """The text with every non-ASCII character as a backslash escape, so it always encodes."""
198
- return text.encode("ascii", "backslashreplace").decode("ascii")
199
-
200
-
201
- def _encode_output(output: dict) -> bytes:
202
- """The output as UTF-8 JSON; raise if it is not JSON-serialisable or holds text that is not valid UTF-8."""
203
- return (json.dumps(output, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
137
+ def _error_document(error: BaseException, message: str | None = None) -> dict:
138
+ return {
139
+ "format_version": PARSE_FORMAT_VERSION,
140
+ "type": type(error).__name__,
141
+ "message": str(error) if message is None else message,
142
+ }
204
143
 
205
144
 
206
- def parse(
145
+ def render_parse_output(
207
146
  plain_file_path: str,
208
147
  template_dir: str | None,
209
148
  tests_folders: list[str] | None = None,
210
149
  require_test_plain_files: bool = False,
211
- ) -> int:
212
- """Print the parse result, or the parser error, as one UTF-8 JSON document on stdout; return the exit code."""
213
- output: dict
150
+ ) -> tuple[bytes, int]:
151
+ """Return the UTF-8 bytes of the parse JSON document and the exit code."""
214
152
  try:
215
- result = parse_spec(plain_file_path, template_dir, False, tests_folders, require_test_plain_files)
216
- output = {
153
+ res = parse_spec(plain_file_path, template_dir, False, tests_folders, require_test_plain_files)
154
+ doc: dict = {
217
155
  "format_version": PARSE_FORMAT_VERSION,
218
- "modules": [{"module": module_name, "tree": tree} for module_name, tree in result.modules],
219
- "resources": result.resources,
220
- "test_plain_files": result.test_plain_files,
156
+ "modules": [{"module": n, "tree": t} for n, t in res.modules],
157
+ "resources": res.resources,
158
+ "test_plain_files": res.test_plain_files,
221
159
  }
222
- exit_code = 0
160
+ code = 0
223
161
  except Exception as e:
224
- output = _error_output(type(e).__name__, str(e))
225
- exit_code = 1
226
-
162
+ doc, code = _error_document(e), 1
227
163
  try:
228
- data = _encode_output(output)
229
- except UnicodeEncodeError as e:
230
- # A file or directory name that is not valid UTF-8, which is allowed on Linux.
231
- if exit_code == 1:
232
- # A parser error whose message names such a file. Keep its type and escape the name.
233
- output = _error_output(output["type"], _escape(output["message"]))
234
- else:
235
- # A valid result that contains such a name. Report the output line that contains it.
236
- line_start = e.object.rfind("\n", 0, e.start) + 1
237
- line_end = e.object.find("\n", e.end)
238
- line = e.object[line_start : line_end if line_end != -1 else None].strip().rstrip(",")
239
- output = _error_output(
240
- type(e).__name__, f"The parse result holds text that is not valid UTF-8: {_escape(line)}"
241
- )
242
- data = _encode_output(output)
243
- exit_code = 1
164
+ text = json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
244
165
  except Exception as e:
245
- # A value in the result that JSON cannot represent. Report it as a JSON error.
246
- data = _encode_output(_error_output(type(e).__name__, _escape(str(e))))
247
- exit_code = 1
248
-
249
- # Write the UTF-8 bytes to stdout's byte stream, because sys.stdout encodes text with the system encoding, which
250
- # may not be UTF-8.
251
- buffer = getattr(sys.stdout, "buffer", None)
252
- if buffer is None:
253
- # A Python caller replaced stdout with a stream that takes only text.
254
- sys.stdout.write(data.decode("utf-8"))
255
- return exit_code
166
+ doc, code = _error_document(e), 1
167
+ text = json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
168
+ try:
169
+ return text.encode("utf-8"), code
170
+ except UnicodeEncodeError as e:
171
+ if code == 0:
172
+ for line in text.split("\n"):
173
+ try:
174
+ line.encode("utf-8")
175
+ except UnicodeEncodeError:
176
+ bad = line.strip().removesuffix(",").encode("utf-8", "backslashreplace").decode("ascii")
177
+ break
178
+ err = UnicodeEncodeError(e.encoding, e.object, e.start, e.end, e.reason)
179
+ msg = f"The parse result holds text that is not valid UTF-8: {bad}"
180
+ doc, code = _error_document(err, msg), 1
181
+ text = json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
182
+ return text.encode("utf-8", "backslashreplace"), code
256
183
 
184
+
185
+ def parse(
186
+ plain_file_path: str,
187
+ template_dir: str | None,
188
+ tests_folders: list[str] | None = None,
189
+ require_test_plain_files: bool = False,
190
+ ) -> int:
191
+ data, code = render_parse_output(plain_file_path, template_dir, tests_folders, require_test_plain_files)
257
192
  try:
258
- sys.stdout.flush() # Send out anything already written to sys.stdout first.
259
- buffer.write(data)
260
- buffer.flush()
193
+ buffer = getattr(sys.stdout, "buffer", None)
194
+ if buffer is not None:
195
+ sys.stdout.flush()
196
+ buffer.write(data)
197
+ buffer.flush()
198
+ else:
199
+ sys.stdout.write(data.decode("utf-8"))
200
+ sys.stdout.flush()
261
201
  except BrokenPipeError:
262
- # The reader closed the pipe early. Send stdout to /dev/null, so Python's flush at exit does not fail again,
263
- # and keep the exit code.
264
- devnull = os.open(os.devnull, os.O_WRONLY)
265
- os.dup2(devnull, sys.stdout.fileno())
266
- return exit_code
202
+ try:
203
+ devnull = os.open(os.devnull, os.O_WRONLY)
204
+ os.dup2(devnull, sys.stdout.fileno())
205
+ except (OSError, ValueError):
206
+ pass
207
+ return code
267
208
 
268
209
 
269
210
  def main(argv: list[str] | None = None) -> int:
270
211
  parser = build_parser()
271
212
  args = parser.parse_args(argv)
272
-
273
213
  try:
274
- # The config file is resolved even when --template-dir is given, so an ambiguous config is always an error.
275
- config = _read_config(parser, args)
276
- template_dir = args.template_dir or config.template_dir
277
- tests_folders = args.tests_folder or config.tests_folders
278
- if config.conformance_tests_enabled and not tests_folders:
279
- parser.error(
280
- "conformance-tests-script is set in the config file, but no tests folder is given. "
281
- "Pass --tests-folder or set tests-folder in the config file."
282
- )
283
- if args.command == "parse":
284
- return parse(args.plain_file, template_dir, tests_folders, config.conformance_tests_enabled)
285
- check(args.plain_file, template_dir, tests_folders, config.conformance_tests_enabled)
214
+ config_file = resolve_config_file(args.config_name, args.filename)
215
+ cfg = read_config(config_file) if config_file else Config()
216
+ except (AmbiguousConfigFileError, ConfigReadError) as e:
217
+ parser.error(str(e))
218
+ except KeyboardInterrupt:
219
+ return 130
220
+ template_dir = cfg.template_dir
221
+ folders = cfg.tests_folders
222
+ if args.template_dir:
223
+ template_dir = os.path.abspath(os.path.expanduser(args.template_dir))
224
+ if args.tests_folder:
225
+ folders = [os.path.abspath(os.path.expanduser(p)) for p in args.tests_folder]
226
+ require = cfg.conformance_tests_enabled
227
+ if require and not folders:
228
+ parser.error(
229
+ "conformance-tests-script is set in the config file, but no tests folder is given. "
230
+ "Pass --tests-folder or set tests-folder in the config file."
231
+ )
232
+ try:
233
+ if args.command == "check":
234
+ parse_spec(args.filename, template_dir, True, folders, require)
235
+ print(f"{args.filename}: OK")
236
+ return 0
237
+ return parse(args.filename, template_dir, folders, require)
286
238
  except KeyboardInterrupt:
287
239
  return 130
288
240
  except Exception as e:
289
241
  print(f"Error: {e}", file=sys.stderr)
290
242
  return 1
291
243
 
292
- print(f"{args.plain_file}: OK")
293
- return 0
294
244
 
295
-
296
- def _read_config(parser: argparse.ArgumentParser, args: argparse.Namespace) -> Config:
297
- try:
298
- config_file = resolve_config_file(args.config_name, args.plain_file)
299
- return read_config(config_file) if config_file is not None else Config()
300
- except AmbiguousConfigFileError as e:
301
- parser.error(str(e))
302
- except Exception as e:
303
- parser.error(f"Error reading config file: {e}")
245
+ if __name__ == "__main__":
246
+ sys.exit(main())