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/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- """Parser for ***plain specification files."""
1
+ """plain-parser: parser for the plain specification language."""
2
2
 
3
3
  from plain_parser import concept_utils, exceptions, loaders, plain_file, plain_spec, project, test_plain_file
4
4
  from plain_parser.plain_file import (
plain_parser/cli.py CHANGED
@@ -1,303 +1,277 @@
1
- """Command-line entry point: ``plain-parser {check,parse} <file.plain> [--template-dir DIR] [--tests-folder DIR]...
2
- [--config-name NAME]``."""
1
+ """The plain-parser command line: `check` and `parse` an entry module with its requires chain and test plain files."""
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, Dict, List, Optional, Tuple
9
9
 
10
10
  import yaml
11
11
 
12
- from plain_parser import loaders, plain_spec, project
12
+ from plain_parser.loaders import find_resource_dir, load_linked_resources, relative_resource_path
13
+ from plain_parser.plain_spec import collect_linked_resources, get_frids, get_specifications_for_frid
14
+ from plain_parser.project import parse_project
13
15
 
14
16
  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
17
  PARSE_FORMAT_VERSION = 2
19
18
 
19
+ _NO_TESTS_FOLDER = (
20
+ "conformance-tests-script is set in the config file, but no tests folder is given. "
21
+ "Pass --tests-folder or set tests-folder in the config file."
22
+ )
23
+
20
24
 
21
25
  class AmbiguousConfigFileError(Exception):
22
26
  pass
23
27
 
24
28
 
29
+ @dataclass
30
+ class Config:
31
+ template_dir: Optional[str] = None
32
+ tests_folders: Optional[List[str]] = None
33
+ conformance_tests_enabled: bool = False
34
+
35
+
36
+ @dataclass
37
+ class ParseResult:
38
+ modules: List[Tuple[str, dict]]
39
+ resources: Dict[str, str]
40
+ test_plain_files: Dict[str, dict] = field(default_factory=dict)
41
+
42
+
25
43
  def build_parser() -> argparse.ArgumentParser:
26
- parser = argparse.ArgumentParser(prog="plain-parser", description="Tools for ***plain specification files.")
44
+ parser = argparse.ArgumentParser(prog="plain-parser", description="Check and parse plain specification modules.")
27
45
  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
+ for name, help_text in (("check", "validate a module and its requires chain"), ("parse", "print a module as JSON")):
47
+ subparser = subparsers.add_parser(name, help=help_text)
48
+ subparser.add_argument("plain_file", help="path of the module file")
49
+ subparser.add_argument("--template-dir", metavar="DIR", default=None, help="template directory")
46
50
  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.",
51
+ "--tests-folder", metavar="DIR", action="append", default=None, help="tests folder (repeatable)"
52
52
  )
53
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.",
54
+ "--config-name", metavar="NAME", default=DEFAULT_CONFIG_NAME, help="name of the config file"
58
55
  )
59
56
  return parser
60
57
 
61
58
 
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:
59
+ def resolve_config_file(config_name: str, plain_file_path: str) -> Optional[str]:
60
+ """Find the config file in the directory of the module file, then in the working directory."""
61
+ plain_dir = os.path.dirname(os.path.abspath(plain_file_path))
62
+ cwd = os.getcwd()
63
+ candidates = [os.path.join(directory, config_name) for directory in (plain_dir, cwd)]
64
+ found = [path for path in candidates if os.path.isfile(path)]
65
+ if len(found) == 2 and not os.path.samefile(found[0], found[1]):
71
66
  raise AmbiguousConfigFileError(
72
67
  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."
68
+ f" - Plain file directory: {plain_dir}\n"
69
+ f" - Current working directory: {cwd}\n"
70
+ "Remove the config file from one of these locations to resolve the ambiguity."
76
71
  )
77
- if in_plain_dir:
78
- return plain_dir_config
79
- if in_cwd:
80
- return cwd_config
81
- return None
72
+ return found[0] if found else None
82
73
 
83
74
 
84
- @dataclass
85
- class Config:
86
- 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.
75
+ def _value(data: dict, key: str) -> Any:
76
+ dashed = data.get(key)
77
+ return dashed if dashed else data.get(key.replace("-", "_"))
89
78
 
90
79
 
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)
80
+ def _resolve(path: str, base: str) -> str:
81
+ return os.path.abspath(os.path.join(base, os.path.expanduser(str(path))))
94
82
 
95
83
 
96
84
  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 {}
85
+ """Read the template directory, the tests folders and the conformance check switch of a config file."""
86
+ with open(config_file, encoding="utf-8") as file:
87
+ data = yaml.safe_load(file)
88
+ if not isinstance(data, dict):
89
+ data = {}
90
+ base = os.path.dirname(os.path.abspath(config_file))
91
+ template_dir = _value(data, "template-dir")
92
+ folders = _value(data, "tests-folder")
93
+ if folders and not isinstance(folders, list):
94
+ folders = [folders]
95
+ return Config(
96
+ template_dir=_resolve(template_dir, base) if template_dir else None,
97
+ tests_folders=[_resolve(folder, base) for folder in folders if folder] if folders else None,
98
+ conformance_tests_enabled=bool(_value(data, "conformance-tests-script")),
99
+ )
101
100
 
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
101
 
106
- result = Config()
107
- template_dir = _config_value(config, TEMPLATE_DIR_CONFIG_KEYS)
102
+ def _template_dirs(plain_file_path: str, template_dir: Optional[str]) -> List[str]:
103
+ directories = [os.path.dirname(os.path.abspath(plain_file_path))]
108
104
  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
117
-
118
-
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)
105
+ directories.append(os.path.abspath(template_dir))
106
+ return directories
129
107
 
130
108
 
131
109
  def parse_spec(
132
110
  plain_file_path: str,
133
- template_dir: str | None,
111
+ template_dir: Optional[str],
134
112
  load_resources: bool,
135
- tests_folders: list[str] | None = None,
113
+ tests_folders: Optional[List[str]] = None,
136
114
  require_test_plain_files: bool = False,
137
115
  ) -> 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
- entry_dir = os.path.dirname(os.path.abspath(plain_file_path))
148
- template_dirs = [entry_dir]
149
- 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
116
+ """Parse an entry module file with its requires chain, resource map and test plain file map."""
117
+ template_dirs = _template_dirs(plain_file_path, template_dir)
118
+ entry_dir = template_dirs[0]
119
+ project = parse_project(
120
+ os.path.abspath(plain_file_path), template_dirs, list(tests_folders or []), require_test_plain_files
155
121
  )
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.
160
- 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)
122
+ resources: Dict[str, str] = {}
123
+ for module_name, tree in project.chain:
124
+ links: List[dict] = []
125
+ collect_linked_resources(tree, links, None, True)
164
126
  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
-
127
+ load_linked_resources(template_dirs, links, module_name)
128
+ for link in links:
129
+ target = link["target"]
130
+ resource_dir = find_resource_dir(template_dirs, target)
131
+ if resource_dir is not None and target not in resources:
132
+ resources[target] = relative_resource_path(entry_dir, resource_dir, target)
133
+ entry_tree = project.chain[-1][1]
134
+ for frid in get_frids(entry_tree):
135
+ get_specifications_for_frid(entry_tree, frid)
175
136
  test_plain_files = {
176
- bound.name: {"module": bound.parsed.module, "func_id": bound.parsed.func_id}
177
- for bound in parsed.test_plain_files
137
+ file.name: {"module": file.parsed.module, "func_id": file.parsed.func_id} for file in project.test_plain_files
178
138
  }
179
- return ParseResult(chain, resources, test_plain_files)
139
+ return ParseResult(project.chain, resources, test_plain_files)
180
140
 
181
141
 
182
142
  def check(
183
143
  plain_file_path: str,
184
- template_dir: str | None,
185
- tests_folders: list[str] | None = None,
144
+ template_dir: Optional[str],
145
+ tests_folders: Optional[List[str]] = None,
186
146
  require_test_plain_files: bool = False,
187
147
  ) -> None:
188
- """Raise if the module, its requires chain, its test plain files, or its linked resources are invalid."""
148
+ """Validate an entry module, loading its linked files; raise the first error found."""
189
149
  parse_spec(plain_file_path, template_dir, True, tests_folders, require_test_plain_files)
190
150
 
191
151
 
192
- def _error_output(type_name: str, message: str) -> dict:
193
- return {"format_version": PARSE_FORMAT_VERSION, "type": type_name, "message": message}
152
+ def _error_document(error: BaseException) -> dict:
153
+ message = str(error).encode("utf-8", "backslashreplace").decode("utf-8")
154
+ return {"format_version": PARSE_FORMAT_VERSION, "type": type(error).__name__, "message": message}
194
155
 
195
156
 
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")
157
+ def _render(document: dict) -> Tuple[bytes, int]:
158
+ """Render a parse document as UTF-8 JSON; a document that cannot be written becomes an error document."""
159
+ try:
160
+ text = json.dumps(document, indent=2, ensure_ascii=False) + "\n"
161
+ except (TypeError, ValueError) as error:
162
+ return _render(_error_document(error))[0], 1
163
+ try:
164
+ return text.encode("utf-8"), 0
165
+ except UnicodeEncodeError as error:
166
+ if document.get("type") is not None and document.get("format_version") == PARSE_FORMAT_VERSION:
167
+ fixed = dict(document)
168
+ fixed["message"] = str(document.get("message", "")).encode("utf-8", "backslashreplace").decode("utf-8")
169
+ return json.dumps(fixed, indent=2, ensure_ascii=False).encode("utf-8", "backslashreplace") + b"\n", 1
170
+ for line in text.split("\n"):
171
+ try:
172
+ line.encode("utf-8")
173
+ except UnicodeEncodeError:
174
+ shown = line.strip().rstrip(",").encode("ascii", "backslashreplace").decode("ascii")
175
+ break
176
+ else:
177
+ shown = str(error)
178
+ failure = {
179
+ "format_version": PARSE_FORMAT_VERSION,
180
+ "type": type(error).__name__,
181
+ "message": f"The parse result holds text that is not valid UTF-8: {shown}",
182
+ }
183
+ return json.dumps(failure, indent=2, ensure_ascii=False).encode("utf-8") + b"\n", 1
199
184
 
200
185
 
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")
186
+ def _write_stdout(data: bytes) -> None:
187
+ stream = sys.stdout
188
+ stream.flush()
189
+ buffer = getattr(stream, "buffer", None)
190
+ if buffer is None:
191
+ stream.write(data.decode("utf-8"))
192
+ return
193
+ buffer.write(data)
194
+ buffer.flush()
195
+
196
+
197
+ def _silence_stdout() -> None:
198
+ try:
199
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
200
+ except (OSError, ValueError, AttributeError):
201
+ pass
204
202
 
205
203
 
206
204
  def parse(
207
205
  plain_file_path: str,
208
- template_dir: str | None,
209
- tests_folders: list[str] | None = None,
206
+ template_dir: Optional[str],
207
+ tests_folders: Optional[List[str]] = None,
210
208
  require_test_plain_files: bool = False,
211
209
  ) -> 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
210
+ """Print an entry module as one JSON document and return the exit code."""
214
211
  try:
215
212
  result = parse_spec(plain_file_path, template_dir, False, tests_folders, require_test_plain_files)
216
- output = {
213
+ document: dict = {
217
214
  "format_version": PARSE_FORMAT_VERSION,
218
- "modules": [{"module": module_name, "tree": tree} for module_name, tree in result.modules],
215
+ "modules": [{"module": name, "tree": tree} for name, tree in result.modules],
219
216
  "resources": result.resources,
220
217
  "test_plain_files": result.test_plain_files,
221
218
  }
222
219
  exit_code = 0
223
- except Exception as e:
224
- output = _error_output(type(e).__name__, str(e))
225
- exit_code = 1
226
-
227
- 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
244
- 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
256
-
220
+ except KeyboardInterrupt:
221
+ return 130
222
+ except Exception as error:
223
+ document, exit_code = _error_document(error), 1
224
+ data, failed = _render(document)
257
225
  try:
258
- sys.stdout.flush() # Send out anything already written to sys.stdout first.
259
- buffer.write(data)
260
- buffer.flush()
226
+ _write_stdout(data)
261
227
  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
228
+ _silence_stdout()
229
+ return exit_code or failed
267
230
 
268
231
 
269
- def main(argv: list[str] | None = None) -> int:
232
+ def _settings(
233
+ parser: argparse.ArgumentParser, args: argparse.Namespace
234
+ ) -> Tuple[Optional[str], Optional[List[str]], bool]:
235
+ """Combine the config file with the options into the template directory, tests folders and check switch."""
236
+ try:
237
+ config_file = resolve_config_file(args.config_name, args.plain_file)
238
+ except AmbiguousConfigFileError as error:
239
+ parser.error(str(error))
240
+ config = Config()
241
+ if config_file:
242
+ try:
243
+ config = read_config(config_file)
244
+ except Exception as error:
245
+ parser.error(f"Error reading config file: {error}")
246
+ template_dir = config.template_dir
247
+ if args.template_dir is not None:
248
+ template_dir = os.path.abspath(args.template_dir) if args.template_dir else None
249
+ tests_folders = config.tests_folders
250
+ if args.tests_folder:
251
+ tests_folders = [os.path.abspath(folder) for folder in args.tests_folder]
252
+ if config.conformance_tests_enabled and not tests_folders:
253
+ parser.error(_NO_TESTS_FOLDER)
254
+ return template_dir, tests_folders, config.conformance_tests_enabled
255
+
256
+
257
+ def main(argv: Optional[List[str]] = None) -> int:
270
258
  parser = build_parser()
271
- args = parser.parse_args(argv)
259
+ try:
260
+ args = parser.parse_args(argv)
261
+ template_dir, tests_folders, require = _settings(parser, args)
262
+ except SystemExit as exit_request:
263
+ return exit_request.code if isinstance(exit_request.code, int) else 2
264
+ except KeyboardInterrupt:
265
+ return 130
272
266
 
267
+ if args.command == "parse":
268
+ return parse(args.plain_file, template_dir, tests_folders, require)
273
269
  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)
270
+ check(args.plain_file, template_dir, tests_folders, require)
286
271
  except KeyboardInterrupt:
287
272
  return 130
288
- except Exception as e:
289
- print(f"Error: {e}", file=sys.stderr)
273
+ except Exception as error:
274
+ sys.stderr.write(f"Error: {error}\n")
290
275
  return 1
291
-
292
- print(f"{args.plain_file}: OK")
276
+ sys.stdout.write(f"{args.plain_file}: OK\n")
293
277
  return 0
294
-
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}")