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 +3 -3
- plain_parser/cli.py +194 -163
- plain_parser/concept_utils.py +141 -124
- plain_parser/graph.py +145 -109
- plain_parser/liquid_nodes.py +25 -43
- plain_parser/loaders.py +103 -90
- plain_parser/plain_file.py +614 -530
- plain_parser/plain_spec.py +135 -134
- plain_parser/project.py +94 -80
- plain_parser/test_plain_file.py +195 -175
- {plain_parser-1.0.0.dev1.dist-info → plain_parser-1.0.0.dev2.dist-info}/METADATA +15 -2
- plain_parser-1.0.0.dev2.dist-info/RECORD +16 -0
- plain_parser-1.0.0.dev2.dist-info/licenses/LICENSE +21 -0
- plain_parser-1.0.0.dev1.dist-info/RECORD +0 -15
- {plain_parser-1.0.0.dev1.dist-info → plain_parser-1.0.0.dev2.dist-info}/WHEEL +0 -0
- {plain_parser-1.0.0.dev1.dist-info → plain_parser-1.0.0.dev2.dist-info}/entry_points.txt +0 -0
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
|
|
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
|
-
"""
|
|
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
|
|
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
|
-
|
|
19
|
-
|
|
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
|
|
25
|
+
class AmbiguousConfigFileError(Exception):
|
|
23
26
|
pass
|
|
24
27
|
|
|
25
28
|
|
|
26
29
|
@dataclass
|
|
27
30
|
class Config:
|
|
28
|
-
template_dir: str
|
|
29
|
-
tests_folders:
|
|
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:
|
|
36
|
-
resources:
|
|
37
|
-
test_plain_files:
|
|
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
|
-
|
|
43
|
-
for name in ("check", "parse"):
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
if len(
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
|
65
|
-
|
|
66
|
-
|
|
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
|
|
72
|
-
|
|
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
|
-
|
|
86
|
-
|
|
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=
|
|
91
|
-
tests_folders=[
|
|
92
|
-
conformance_tests_enabled=bool(
|
|
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
|
|
111
|
+
template_dir: Optional[str],
|
|
99
112
|
load_resources: bool,
|
|
100
|
-
tests_folders:
|
|
113
|
+
tests_folders: Optional[List[str]] = None,
|
|
101
114
|
require_test_plain_files: bool = False,
|
|
102
115
|
) -> ParseResult:
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
114
|
-
for link in
|
|
127
|
+
load_linked_resources(template_dirs, links, module_name)
|
|
128
|
+
for link in links:
|
|
115
129
|
target = link["target"]
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
return ParseResult(
|
|
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
|
|
131
|
-
tests_folders:
|
|
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
|
|
138
|
-
|
|
139
|
-
|
|
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
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
)
|
|
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
|
-
|
|
154
|
-
|
|
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
|
-
"
|
|
157
|
-
"
|
|
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
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
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
|
-
|
|
170
|
-
except
|
|
171
|
-
|
|
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
|
|
188
|
-
tests_folders:
|
|
206
|
+
template_dir: Optional[str],
|
|
207
|
+
tests_folders: Optional[List[str]] = None,
|
|
189
208
|
require_test_plain_files: bool = False,
|
|
190
209
|
) -> int:
|
|
191
|
-
|
|
210
|
+
"""Print an entry module as one JSON document and return the exit code."""
|
|
192
211
|
try:
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
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
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
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:
|
|
257
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
211
258
|
parser = build_parser()
|
|
212
|
-
args = parser.parse_args(argv)
|
|
213
259
|
try:
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
except
|
|
217
|
-
|
|
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
|
-
|
|
221
|
-
|
|
222
|
-
|
|
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
|
-
|
|
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
|
|
241
|
-
|
|
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
|