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.
plain_parser/__init__.py CHANGED
@@ -1,7 +1,7 @@
1
- """plain-parser."""
1
+ """plain-parser: parser for the plain specification language."""
2
2
 
3
- from . import concept_utils, exceptions, loaders, plain_file, plain_spec, project, test_plain_file
4
- from .plain_file import (
3
+ from plain_parser import concept_utils, exceptions, loaders, plain_file, plain_spec, project, test_plain_file
4
+ from plain_parser.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,246 +1,277 @@
1
- """Command line of plain-parser."""
1
+ """The plain-parser command line: `check` and `parse` an entry module with its requires chain and test plain files."""
2
2
 
3
3
  import argparse
4
4
  import json
5
5
  import os
6
6
  import sys
7
7
  from dataclasses import dataclass, field
8
- from typing import Any
8
+ from typing import Any, Dict, List, Optional, Tuple
9
9
 
10
10
  import yaml
11
11
 
12
- from . 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
17
  PARSE_FORMAT_VERSION = 2
16
18
 
17
-
18
- class AmbiguousConfigFileError(Exception):
19
- pass
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
+ )
20
23
 
21
24
 
22
- class ConfigReadError(Exception):
25
+ class AmbiguousConfigFileError(Exception):
23
26
  pass
24
27
 
25
28
 
26
29
  @dataclass
27
30
  class Config:
28
- template_dir: str | None = None
29
- tests_folders: list[str] | None = None
31
+ template_dir: Optional[str] = None
32
+ tests_folders: Optional[List[str]] = None
30
33
  conformance_tests_enabled: bool = False
31
34
 
32
35
 
33
36
  @dataclass
34
37
  class ParseResult:
35
- modules: list[tuple[str, dict]]
36
- resources: dict[str, str]
37
- test_plain_files: dict[str, dict] = field(default_factory=dict)
38
+ modules: List[Tuple[str, dict]]
39
+ resources: Dict[str, str]
40
+ test_plain_files: Dict[str, dict] = field(default_factory=dict)
38
41
 
39
42
 
40
43
  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)
44
+ parser = argparse.ArgumentParser(prog="plain-parser", description="Check and parse plain specification modules.")
45
+ subparsers = parser.add_subparsers(dest="command", required=True)
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")
50
+ subparser.add_argument(
51
+ "--tests-folder", metavar="DIR", action="append", default=None, help="tests folder (repeatable)"
52
+ )
53
+ subparser.add_argument(
54
+ "--config-name", metavar="NAME", default=DEFAULT_CONFIG_NAME, help="name of the config file"
55
+ )
49
56
  return parser
50
57
 
51
58
 
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
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]):
66
+ raise AmbiguousConfigFileError(
67
+ f"Config file '{config_name}' was found in two locations:\n"
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."
71
+ )
72
+ return found[0] if found else None
62
73
 
63
74
 
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
75
+ def _value(data: dict, key: str) -> Any:
76
+ dashed = data.get(key)
77
+ return dashed if dashed else data.get(key.replace("-", "_"))
69
78
 
70
79
 
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
+ def _resolve(path: str, base: str) -> str:
81
+ return os.path.abspath(os.path.join(base, os.path.expanduser(str(path))))
80
82
 
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
83
 
85
- folders = _key(data, "tests-folder")
86
- if isinstance(folders, str):
84
+ def read_config(config_file: str) -> Config:
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):
87
94
  folders = [folders]
88
- template_dir = _key(data, "template-dir")
89
95
  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")),
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")),
93
99
  )
94
100
 
95
101
 
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))]
104
+ if template_dir:
105
+ directories.append(os.path.abspath(template_dir))
106
+ return directories
107
+
108
+
96
109
  def parse_spec(
97
110
  plain_file_path: str,
98
- template_dir: str | None,
111
+ template_dir: Optional[str],
99
112
  load_resources: bool,
100
- tests_folders: list[str] | None = None,
113
+ tests_folders: Optional[List[str]] = None,
101
114
  require_test_plain_files: bool = False,
102
115
  ) -> ParseResult:
103
- entry_dir = os.path.dirname(os.path.abspath(plain_file_path))
104
- dirs = [entry_dir]
105
- if template_dir:
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)
108
- resources: dict[str, str] = {}
109
- for name, tree in result.chain:
110
- registry: list[dict] = []
111
- plain_spec.collect_linked_resources(tree, registry, None, True)
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
121
+ )
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)
112
126
  if load_resources:
113
- loaders.load_linked_resources(dirs, registry, name)
114
- for link in registry:
127
+ load_linked_resources(template_dirs, links, module_name)
128
+ for link in links:
115
129
  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)
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)
136
+ test_plain_files = {
137
+ file.name: {"module": file.parsed.module, "func_id": file.parsed.func_id} for file in project.test_plain_files
138
+ }
139
+ return ParseResult(project.chain, resources, test_plain_files)
126
140
 
127
141
 
128
142
  def check(
129
143
  plain_file_path: str,
130
- template_dir: str | None,
131
- tests_folders: list[str] | None = None,
144
+ template_dir: Optional[str],
145
+ tests_folders: Optional[List[str]] = None,
132
146
  require_test_plain_files: bool = False,
133
147
  ) -> None:
148
+ """Validate an entry module, loading its linked files; raise the first error found."""
134
149
  parse_spec(plain_file_path, template_dir, True, tests_folders, require_test_plain_files)
135
150
 
136
151
 
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
- }
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}
143
155
 
144
156
 
145
- def render_parse_output(
146
- plain_file_path: str,
147
- template_dir: str | None,
148
- tests_folders: list[str] | None = None,
149
- require_test_plain_files: bool = False,
150
- ) -> tuple[bytes, int]:
151
- """Return the UTF-8 bytes of the parse JSON document and the exit code."""
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
152
163
  try:
153
- res = parse_spec(plain_file_path, template_dir, False, tests_folders, require_test_plain_files)
154
- doc: dict = {
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 = {
155
179
  "format_version": PARSE_FORMAT_VERSION,
156
- "modules": [{"module": n, "tree": t} for n, t in res.modules],
157
- "resources": res.resources,
158
- "test_plain_files": res.test_plain_files,
180
+ "type": type(error).__name__,
181
+ "message": f"The parse result holds text that is not valid UTF-8: {shown}",
159
182
  }
160
- code = 0
161
- except Exception as e:
162
- doc, code = _error_document(e), 1
163
- try:
164
- text = json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
165
- except Exception as e:
166
- doc, code = _error_document(e), 1
167
- text = json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
183
+ return json.dumps(failure, indent=2, ensure_ascii=False).encode("utf-8") + b"\n", 1
184
+
185
+
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:
168
198
  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
199
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
200
+ except (OSError, ValueError, AttributeError):
201
+ pass
183
202
 
184
203
 
185
204
  def parse(
186
205
  plain_file_path: str,
187
- template_dir: str | None,
188
- tests_folders: list[str] | None = None,
206
+ template_dir: Optional[str],
207
+ tests_folders: Optional[List[str]] = None,
189
208
  require_test_plain_files: bool = False,
190
209
  ) -> int:
191
- data, code = render_parse_output(plain_file_path, template_dir, tests_folders, require_test_plain_files)
210
+ """Print an entry module as one JSON document and return the exit code."""
192
211
  try:
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()
212
+ result = parse_spec(plain_file_path, template_dir, False, tests_folders, require_test_plain_files)
213
+ document: dict = {
214
+ "format_version": PARSE_FORMAT_VERSION,
215
+ "modules": [{"module": name, "tree": tree} for name, tree in result.modules],
216
+ "resources": result.resources,
217
+ "test_plain_files": result.test_plain_files,
218
+ }
219
+ exit_code = 0
220
+ except KeyboardInterrupt:
221
+ return 130
222
+ except Exception as error:
223
+ document, exit_code = _error_document(error), 1
224
+ data, failed = _render(document)
225
+ try:
226
+ _write_stdout(data)
201
227
  except BrokenPipeError:
228
+ _silence_stdout()
229
+ return exit_code or failed
230
+
231
+
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:
202
242
  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
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
208
255
 
209
256
 
210
- def main(argv: list[str] | None = None) -> int:
257
+ def main(argv: Optional[List[str]] = None) -> int:
211
258
  parser = build_parser()
212
- args = parser.parse_args(argv)
213
259
  try:
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))
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
218
264
  except KeyboardInterrupt:
219
265
  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
- )
266
+
267
+ if args.command == "parse":
268
+ return parse(args.plain_file, template_dir, tests_folders, require)
232
269
  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)
270
+ check(args.plain_file, template_dir, tests_folders, require)
238
271
  except KeyboardInterrupt:
239
272
  return 130
240
- except Exception as e:
241
- print(f"Error: {e}", file=sys.stderr)
273
+ except Exception as error:
274
+ sys.stderr.write(f"Error: {error}\n")
242
275
  return 1
243
-
244
-
245
- if __name__ == "__main__":
246
- sys.exit(main())
276
+ sys.stdout.write(f"{args.plain_file}: OK\n")
277
+ return 0