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.
@@ -1,247 +1,250 @@
1
- """Test plain files: the conformance and acceptance scenarios of one functionality.
1
+ """Parsing of test plain files: the scenarios of one functionality, read line by line."""
2
2
 
3
- A test plain file binds to a functionality with the frontmatter keys ``module`` and ``func_id``. It holds a
4
- ``***conformance tests***`` section followed by an ``***acceptance tests***`` section; each scenario in them is a
5
- `# <scenario-id>` heading followed by free text, which is kept verbatim.
6
- """
7
-
8
- import io
3
+ import re
9
4
  from dataclasses import dataclass, field
5
+ from typing import Any, Dict, List, Optional, Set
10
6
 
11
7
  import frontmatter
12
- import mistletoe
8
+ from mistletoe import Document
13
9
 
14
- from plain_parser import concept_utils, loaders, plain_file, plain_spec
10
+ from plain_parser.concept_utils import DEFAULT_CONCEPTS, extract_concepts_from_spec_text
15
11
  from plain_parser.exceptions import PlainSyntaxError
12
+ from plain_parser.loaders import _render
13
+ from plain_parser.plain_file import (
14
+ find_linked_resources,
15
+ normalize_line_endings,
16
+ process_section_code_variables,
17
+ restore_stripped_lines,
18
+ )
19
+ from plain_parser.plain_spec import ACCEPTANCE_TEST_HEADING, CONFORMANCE_TEST_HEADING, is_semantic_id
16
20
 
17
21
  MODULE_KEY = "module"
18
22
  FUNC_ID_KEY = "func_id"
19
- FRONTMATTER_KEYS = (MODULE_KEY, FUNC_ID_KEY)
20
- SECTION_HEADINGS = (plain_spec.CONFORMANCE_TEST_HEADING, plain_spec.ACCEPTANCE_TEST_HEADING)
23
+
24
+ _SECTIONS = [CONFORMANCE_TEST_HEADING, ACCEPTANCE_TEST_HEADING]
25
+ _FENCE = re.compile(r"^ *(```|~~~)")
21
26
 
22
27
 
23
28
  @dataclass
24
29
  class Scenario:
25
30
  id: str
26
31
  line_number: int
27
- # The body as written, without `>` comment lines and without leading and trailing blank lines.
28
32
  text: str = ""
29
- linked_resources: list[dict] = field(default_factory=list)
30
- code_variables: list[dict] = field(default_factory=list)
33
+ linked_resources: List[dict] = field(default_factory=list)
34
+ code_variables: List[dict] = field(default_factory=list)
31
35
 
32
36
  def to_dict(self) -> dict:
33
- entry = {"id": self.id, "text": self.text, "linked_resources": self.linked_resources}
37
+ result: Dict[str, Any] = {"id": self.id, "text": self.text, "linked_resources": self.linked_resources}
34
38
  if self.code_variables:
35
- entry["code_variables"] = self.code_variables
36
- return entry
39
+ result["code_variables"] = self.code_variables
40
+ return result
37
41
 
38
42
 
39
43
  @dataclass
40
44
  class TestPlainFile:
41
- name: str # The path of the file as shown in messages.
45
+ __test__ = False # not a pytest test class
46
+
47
+ name: str
42
48
  module: str
43
49
  func_id: str
44
- conformance_tests: list[Scenario]
45
- acceptance_tests: list[Scenario]
50
+ conformance_tests: List[Scenario]
51
+ acceptance_tests: List[Scenario]
46
52
 
47
53
  @property
48
- def scenarios(self) -> list[Scenario]:
54
+ def scenarios(self) -> List[Scenario]:
49
55
  return [*self.conformance_tests, *self.acceptance_tests]
50
56
 
51
57
 
52
58
  def is_test_plain_file(metadata: dict) -> bool:
53
- """Whether a frontmatter binds its file to a functionality, which makes the file a test plain file."""
54
- return all(key in metadata for key in FRONTMATTER_KEYS)
55
-
56
-
57
- def _error(message: str) -> PlainSyntaxError:
58
- return PlainSyntaxError(f"Plain syntax error: {message}")
59
+ """A file is a test plain file when its frontmatter has both the `module` and the `func_id` keys."""
60
+ return isinstance(metadata, dict) and MODULE_KEY in metadata and FUNC_ID_KEY in metadata
59
61
 
60
62
 
61
- def _at(line_number: int, name: str) -> str:
62
- return f"Syntax error at line {line_number} in test plain file '{name}'"
63
-
64
-
65
- def read_metadata(plain_source_text: str, name: str) -> frontmatter.Post:
66
- """The frontmatter and content of a test plain file; raise unless the keys are exactly module and func_id."""
63
+ def _read_frontmatter(plain_source_text: str, name: str) -> frontmatter.Post:
67
64
  try:
68
65
  post = frontmatter.loads(plain_source_text)
69
- except Exception as e:
70
- raise _error(f"Test plain file '{name}' has invalid frontmatter: {e}")
71
-
72
- for key in FRONTMATTER_KEYS:
73
- if key not in post.metadata:
74
- raise _error(f"Test plain file '{name}' has no `{key}:` key in its frontmatter.")
75
- value = post.metadata[key]
66
+ except Exception as error:
67
+ raise PlainSyntaxError(
68
+ f"Plain syntax error: Test plain file '{name}' has invalid frontmatter: {error}"
69
+ ) from error
70
+ metadata = post.metadata
71
+ for key in (MODULE_KEY, FUNC_ID_KEY):
72
+ if key not in metadata:
73
+ raise PlainSyntaxError(
74
+ f"Plain syntax error: Test plain file '{name}' has no `{key}:` key in its frontmatter."
75
+ )
76
+ for key in (MODULE_KEY, FUNC_ID_KEY):
77
+ value = metadata[key]
76
78
  if not isinstance(value, str) or not value.strip():
77
- raise _error(f"Test plain file '{name}': the frontmatter key `{key}:` must be a non-empty string.")
78
-
79
- for key in post.metadata:
80
- if key not in FRONTMATTER_KEYS:
81
- raise _error(
82
- f"Test plain file '{name}' has the frontmatter key `{key}:`; only `module:` and `func_id:` are allowed."
79
+ raise PlainSyntaxError(
80
+ f"Plain syntax error: Test plain file '{name}': the frontmatter key `{key}:` must be a non-empty string."
81
+ )
82
+ for key in metadata:
83
+ if key not in (MODULE_KEY, FUNC_ID_KEY):
84
+ raise PlainSyntaxError(
85
+ f"Plain syntax error: Test plain file '{name}' has the frontmatter key `{key}:`; "
86
+ "only `module:` and `func_id:` are allowed."
83
87
  )
84
-
85
88
  return post
86
89
 
87
90
 
88
- def _trim_blank_lines(lines: list[str]) -> list[str]:
89
- start, end = 0, len(lines)
90
- while start < end and not lines[start].strip():
91
- start += 1
92
- while end > start and not lines[end - 1].strip():
93
- end -= 1
94
- return lines[start:end]
91
+ class _ScenarioReader:
92
+ """Reads the lines of a rendered test plain file into the scenarios of its two sections."""
95
93
 
94
+ def __init__(self, name: str) -> None:
95
+ self.name = name
96
+ self.sections: Dict[str, List[Scenario]] = {}
97
+ self.section: Optional[str] = None
98
+ self.scenario: Optional[Scenario] = None
99
+ self.lines: List[str] = []
100
+ self.ids: Dict[str, int] = {}
101
+ self.fence: Optional[str] = None
96
102
 
97
- def read_scenarios(rendered_text: str, name: str) -> dict[str, list[Scenario]]: # noqa: C901
98
- """The scenarios of the rendered content, keyed by section heading; raise on the first structural error."""
99
- sections: dict[str, list[Scenario]] = {}
100
- current_section: str | None = None
101
- current: Scenario | None = None
102
- body: list[str] = []
103
- fence: str | None = None # The marker of the open fenced code block (``` or ~~~), None outside one.
104
- heading_lines: dict[str, int] = {} # scenario-id to the line of its heading
103
+ def error(self, line_number: int, message: str) -> PlainSyntaxError:
104
+ return PlainSyntaxError(
105
+ f"Plain syntax error: Syntax error at line {line_number} in test plain file '{self.name}': {message}"
106
+ )
105
107
 
106
- def close_scenario() -> None:
107
- if current is None:
108
+ def finish_scenario(self) -> None:
109
+ scenario = self.scenario
110
+ if scenario is None:
108
111
  return
109
- if fence is not None:
110
- raise _error(
111
- f"{_at(current.line_number, name)}: Scenario `{current.id}` has a code fence that is not closed."
112
- )
113
- lines = _trim_blank_lines(body)
112
+ if self.fence is not None:
113
+ raise self.error(scenario.line_number, f"Scenario `{scenario.id}` has a code fence that is not closed.")
114
+ lines = list(self.lines)
115
+ while lines and not lines[0].strip():
116
+ lines.pop(0)
117
+ while lines and not lines[-1].strip():
118
+ lines.pop()
114
119
  if not lines:
115
- raise _error(f"{_at(current.line_number, name)}: Scenario `{current.id}` has no text.")
116
- current.text = "\n".join(lines)
117
-
118
- for line_number, line in enumerate(rendered_text.split("\n"), start=1):
119
- where = _at(line_number, name)
120
- # Inside a fenced code block every line is body text: a `# ` line is not a heading there, a `***` line is
121
- # not a section marker, and a `>` line is not a comment.
122
- stripped = line.lstrip()
123
- if stripped.startswith(("```", "~~~")):
124
- marker = stripped[:3]
125
- if fence is None:
126
- fence = marker
127
- elif fence == marker:
128
- fence = None
129
- if current is not None:
130
- body.append(line)
131
- continue
132
- elif fence is not None and current is not None:
133
- body.append(line)
134
- continue
135
-
120
+ raise self.error(scenario.line_number, f"Scenario `{scenario.id}` has no text.")
121
+ scenario.text = "\n".join(lines)
122
+ self.scenario = None
123
+ self.lines = []
124
+
125
+ def start_section(self, line_number: int, line: str) -> None:
126
+ self.finish_scenario()
127
+ heading = line.strip().strip("*")
128
+ if line.strip() != f"***{heading}***" or heading not in _SECTIONS:
129
+ raise self.error(
130
+ line_number,
131
+ f"Invalid section (`{line.strip()}`). A test plain file has the sections `***conformance tests***` "
132
+ "and `***acceptance tests***`, in this order.",
133
+ )
134
+ if heading in self.sections:
135
+ raise self.error(line_number, f"Duplicate section `***{heading}***`.")
136
+ if heading == ACCEPTANCE_TEST_HEADING and CONFORMANCE_TEST_HEADING not in self.sections:
137
+ raise self.error(
138
+ line_number,
139
+ f"The `***{heading}***` section must come after `***{CONFORMANCE_TEST_HEADING}***`.",
140
+ )
141
+ self.sections[heading] = []
142
+ self.section = heading
143
+
144
+ def start_scenario(self, line_number: int, line: str) -> None:
145
+ self.finish_scenario()
146
+ scenario_id = line[1:].strip()
147
+ if self.section is None:
148
+ raise self.error(
149
+ line_number,
150
+ f"Scenario `{scenario_id}` comes before the first section; a test plain file starts with "
151
+ "`***conformance tests***`.",
152
+ )
153
+ if not is_semantic_id(scenario_id):
154
+ raise self.error(
155
+ line_number,
156
+ f"Invalid scenario-id (`{scenario_id}`). A scenario-id is lowercase letters and digits, with single "
157
+ "hyphens between them.",
158
+ )
159
+ if scenario_id in self.ids:
160
+ raise self.error(
161
+ line_number,
162
+ f"Duplicate scenario-id `{scenario_id}`; it is first used at line {self.ids[scenario_id]}.",
163
+ )
164
+ self.ids[scenario_id] = line_number
165
+ self.scenario = Scenario(scenario_id, line_number)
166
+ self.sections[self.section].append(self.scenario)
167
+
168
+ def read_line(self, line_number: int, line: str) -> None:
169
+ if self.scenario is not None and self.fence is not None:
170
+ self.lines.append(line)
171
+ if line.lstrip(" ").startswith(self.fence):
172
+ self.fence = None
173
+ return
174
+ if line.lstrip().startswith(">"):
175
+ return
136
176
  if line.startswith("***"):
137
- heading = line.strip()[3:-3] if line.strip().endswith("***") and len(line.strip()) > 6 else None
138
- if heading not in SECTION_HEADINGS:
139
- raise _error(
140
- f"{where}: Invalid section (`{line.strip()}`). A test plain file has the sections "
141
- f"`***{SECTION_HEADINGS[0]}***` and `***{SECTION_HEADINGS[1]}***`, in this order."
142
- )
143
- if heading in sections:
144
- raise _error(f"{where}: Duplicate section `***{heading}***`.")
145
- if heading != SECTION_HEADINGS[len(sections)]:
146
- raise _error(f"{where}: The `***{heading}***` section must come after `***{SECTION_HEADINGS[0]}***`.")
147
- close_scenario()
148
- current = None
149
- current_section = heading
150
- sections[heading] = []
151
- elif line.startswith("# ") or line == "#":
152
- scenario_id = line[1:].strip()
153
- if current_section is None:
154
- raise _error(
155
- f"{where}: Scenario `{scenario_id}` comes before the first section; a test plain file starts "
156
- f"with `***{SECTION_HEADINGS[0]}***`."
157
- )
158
- if not plain_spec.is_semantic_id(scenario_id):
159
- raise _error(
160
- f"{where}: Invalid scenario-id (`{scenario_id}`). A scenario-id is lowercase letters and digits, "
161
- f"with single hyphens between them."
162
- )
163
- if scenario_id in heading_lines:
164
- raise _error(
165
- f"{where}: Duplicate scenario-id `{scenario_id}`; it is first used at line "
166
- f"{heading_lines[scenario_id]}."
167
- )
168
- close_scenario()
169
- current = Scenario(scenario_id, line_number)
170
- body = []
171
- heading_lines[scenario_id] = line_number
172
- sections[current_section].append(current)
173
- elif line.lstrip().startswith(">"):
174
- continue
175
- elif current is not None:
176
- body.append(line)
177
+ self.start_section(line_number, line)
178
+ elif line.startswith("# ") or line.rstrip() == "#":
179
+ self.start_scenario(line_number, line.rstrip())
180
+ elif self.scenario is not None:
181
+ self.lines.append(line)
182
+ match = _FENCE.match(line)
183
+ if match:
184
+ self.fence = match.group(1)
177
185
  elif line.strip():
178
- if current_section is None:
179
- raise _error(
180
- f"{where}: Content before the first section (`{line.strip()}`); a test plain file starts with "
181
- f"`***{SECTION_HEADINGS[0]}***`."
182
- )
183
- raise _error(
184
- f"{where}: Content before the first `# <scenario-id>` heading in the `{current_section}` section "
185
- f"(`{line.strip()}`)."
186
+ self.reject_content(line_number, line)
187
+
188
+ def reject_content(self, line_number: int, line: str) -> None:
189
+ if self.section is None:
190
+ raise self.error(
191
+ line_number,
192
+ f"Content before the first section (`{line.strip()}`); a test plain file starts with "
193
+ "`***conformance tests***`.",
186
194
  )
187
-
188
- close_scenario()
189
-
190
- for heading in SECTION_HEADINGS:
191
- if heading not in sections:
192
- raise _error(f"Test plain file '{name}' has no `***{heading}***` section.")
193
-
194
- return sections
195
-
196
-
197
- def find_scenario_linked_resources(scenario: Scenario, template_dirs: list[str], name: str) -> list[dict]:
198
- document = mistletoe.Document(io.StringIO(scenario.text))
199
- where = f" in test plain file '{name}', scenario `{scenario.id}`"
200
- return plain_file.find_linked_resources(document.children, template_dirs, where)
195
+ raise self.error(
196
+ line_number,
197
+ f"Content before the first `# <scenario-id>` heading in the `{self.section}` section (`{line.strip()}`).",
198
+ )
199
+
200
+ def read(self, rendered: str) -> Dict[str, List[Scenario]]:
201
+ for line_number, line in enumerate(rendered.split("\n"), start=1):
202
+ self.read_line(line_number, line)
203
+ self.finish_scenario()
204
+ for heading in _SECTIONS:
205
+ if heading not in self.sections:
206
+ raise PlainSyntaxError(
207
+ f"Plain syntax error: Test plain file '{self.name}' has no `***{heading}***` section."
208
+ )
209
+ return self.sections
201
210
 
202
211
 
203
212
  def parse_test_plain_file_source(
204
- plain_source_text: str, name: str, template_dirs: list[str], code_variables: dict
213
+ plain_source_text: str, name: str, template_dirs: List[str], code_variables: dict
205
214
  ) -> TestPlainFile:
206
- """Parse the text of a test plain file. Liquid runs as on a spec plain file, with the same template directories;
207
- every link in a scenario is resolved against them. Concepts are not checked here, see
208
- validate_scenario_concepts."""
209
- plain_source_text = plain_file.normalize_line_endings(plain_source_text)
210
-
211
- post = read_metadata(plain_source_text, name)
212
-
213
- _, loaded_templates = loaders.get_loaded_templates(template_dirs, plain_source_text, name)
214
-
215
- content = plain_file.restore_stripped_lines(plain_source_text, post.content)
216
-
217
- rendered_text = plain_file.render_plain_source(content, loaded_templates, code_variables)
218
-
219
- sections = read_scenarios(rendered_text, name)
220
-
221
- for scenario in [*sections[SECTION_HEADINGS[0]], *sections[SECTION_HEADINGS[1]]]:
222
- scenario.linked_resources = find_scenario_linked_resources(scenario, template_dirs, name)
223
- entry = {"text": scenario.text}
224
- plain_file.process_section_code_variables(entry, code_variables, "text")
225
- scenario.text = entry["text"]
226
- scenario.code_variables = entry.get("code_variables", [])
227
-
215
+ """Parse the text of a test plain file, shown in messages by `name`, into its scenarios."""
216
+ text = normalize_line_endings(plain_source_text)
217
+ post = _read_frontmatter(text, name)
218
+ rendered, _ = _render(template_dirs, restore_stripped_lines(text, post.content), name, code_variables)
219
+ sections = _ScenarioReader(name).read(rendered)
220
+
221
+ scenarios = [scenario for heading in _SECTIONS for scenario in sections[heading]]
222
+ for scenario in scenarios:
223
+ where = f" in test plain file '{name}', scenario `{scenario.id}`"
224
+ scenario.linked_resources = find_linked_resources(Document(scenario.text).children, template_dirs, where)
225
+ items: List[Dict[str, Any]] = [{"text": scenario.text} for scenario in scenarios]
226
+ process_section_code_variables(items, code_variables, "text")
227
+ for scenario, item in zip(scenarios, items):
228
+ scenario.text = item["text"]
229
+ scenario.code_variables = list(item.get("code_variables", []))
228
230
  return TestPlainFile(
229
231
  name,
230
232
  str(post.metadata[MODULE_KEY]),
231
233
  str(post.metadata[FUNC_ID_KEY]),
232
- sections[SECTION_HEADINGS[0]],
233
- sections[SECTION_HEADINGS[1]],
234
+ sections[CONFORMANCE_TEST_HEADING],
235
+ sections[ACCEPTANCE_TEST_HEADING],
234
236
  )
235
237
 
236
238
 
237
- def validate_scenario_concepts(test_plain_file: TestPlainFile, concepts: set[str]) -> list[str]:
238
- """One message per concept used in a scenario that is neither in ``concepts`` nor predefined."""
239
- errors = []
239
+ def validate_scenario_concepts(test_plain_file: TestPlainFile, concepts: Set[str]) -> List[str]:
240
+ """Return an error for every concept a scenario mentions that is neither visible nor predefined."""
241
+ errors: List[str] = []
240
242
  for scenario in test_plain_file.scenarios:
241
- for concept in dict.fromkeys(concept_utils.extract_concepts_from_spec_text(scenario.text)):
242
- if concept not in concepts and concept not in concept_utils.DEFAULT_CONCEPTS:
243
+ for concept in dict.fromkeys(extract_concepts_from_spec_text(scenario.text)):
244
+ if concept not in concepts and concept not in DEFAULT_CONCEPTS:
243
245
  errors.append(
244
- f"{_at(scenario.line_number, test_plain_file.name)}: Concept {concept} used in scenario "
245
- f"`{scenario.id}` is not defined in module '{test_plain_file.module}'."
246
+ f"Syntax error at line {scenario.line_number} in test plain file '{test_plain_file.name}': "
247
+ f"Concept {concept} used in scenario `{scenario.id}` is not defined in module "
248
+ f"'{test_plain_file.module}'."
246
249
  )
247
250
  return errors
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.5
2
+ Name: plain-parser
3
+ Version: 1.0.0.dev2
4
+ Summary: Parser for the plain specification language.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: mistletoe<2,>=1.6.0
9
+ Requires-Dist: python-frontmatter<2,>=1.3.0
10
+ Requires-Dist: python-liquid2<0.5,>=0.4.0
11
+ Requires-Dist: pyyaml<7,>=6
12
+ Provides-Extra: dev
13
+ Requires-Dist: black==26.10.1; extra == 'dev'
14
+ Requires-Dist: flake8==7.5.0; extra == 'dev'
15
+ Requires-Dist: isort==9.0.2; extra == 'dev'
16
+ Requires-Dist: mypy==2.4.1; extra == 'dev'
17
+ Requires-Dist: pytest==9.2.0; extra == 'dev'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # plain-parser
21
+
22
+ Parser for the plain specification language. It checks and parses a module together with its `requires` chain and its
23
+ test plain files.
24
+
25
+ ```
26
+ plain-parser check path/to/module.plain
27
+ plain-parser parse path/to/module.plain
28
+ ```
@@ -0,0 +1,16 @@
1
+ plain_parser/__init__.py,sha256=PwqEUlDl4ro2Tt0A5UyYBLes6PXG181_TFB0lr7-OmY,807
2
+ plain_parser/cli.py,sha256=jLz_h_UZxPSxpWbqf1Kr7pG7W1TDo4NsV6tpNBDkPF8,10944
3
+ plain_parser/concept_utils.py,sha256=WWaXEAwM3a4_mjgGFyS-M6D-GQYq892X2qbnnUA2U7s,8438
4
+ plain_parser/exceptions.py,sha256=56TDXrYRlLL51qHnpO5B_ayh3Il4rmU2W3OHn7LO3eQ,527
5
+ plain_parser/graph.py,sha256=_V7rQAtpNxF9wA8FdexORESlbW9jSlnmpoWD3Zs5dXY,6469
6
+ plain_parser/liquid_nodes.py,sha256=OM840uavSkdFuPo4sNeF9E-F6YEN4H5KFe_HBjS_OdU,1761
7
+ plain_parser/loaders.py,sha256=c_yjnwQ-CuF2nJnCke4_IKfUEc-UmOx0SHhKLRclXGQ,7706
8
+ plain_parser/plain_file.py,sha256=Sv9rGKm5iEpCbynPX9am8gp0CgV6aYTFYJKooL6zphs,32780
9
+ plain_parser/plain_spec.py,sha256=2CIpK1ztgJpQjsjOrWRXqP-tCDa-lsuF_9tuB6TXqqg,9820
10
+ plain_parser/project.py,sha256=nxubNautWOXfn1_8ZivJVz4eQh_6FMYJhNZIp058eIc,7751
11
+ plain_parser/test_plain_file.py,sha256=yMsZbYYvXeUAO7gHT5kEITZ-Buq1kAq4AhJO9OYAJJ0,10252
12
+ plain_parser-1.0.0.dev2.dist-info/METADATA,sha256=MrfvI0oHfLMG3460CjovOBSzWAM8YIsC8827tR32DFc,848
13
+ plain_parser-1.0.0.dev2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ plain_parser-1.0.0.dev2.dist-info/entry_points.txt,sha256=pA31GGUyYrmZSpH1CuSzhjrv8pX5ac5HI5hFop1B4eI,55
15
+ plain_parser-1.0.0.dev2.dist-info/licenses/LICENSE,sha256=d8ioYoS41y-ashGrT76K6XWgGLwljc-_6ABKgjNXEcA,1072
16
+ plain_parser-1.0.0.dev2.dist-info/RECORD,,
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Codeplain Inc.
3
+ Copyright (c) plain-parser authors
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -1,145 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: plain-parser
3
- Version: 0.2.1.dev23
4
- Summary: Parser for ***plain specification files
5
- License-Expression: MIT
6
- License-File: LICENSE
7
- Classifier: Intended Audience :: Developers
8
- Classifier: Operating System :: OS Independent
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: Topic :: Software Development :: Compilers
11
- Requires-Python: >=3.11
12
- Requires-Dist: mistletoe<2,>=1.6.0
13
- Requires-Dist: python-frontmatter<2,>=1.3.0
14
- Requires-Dist: python-liquid2<0.5,>=0.4.0
15
- Requires-Dist: pyyaml<7,>=6
16
- Provides-Extra: dev
17
- Requires-Dist: black==26.10.1; extra == 'dev'
18
- Requires-Dist: flake8==7.5.0; extra == 'dev'
19
- Requires-Dist: isort==9.0.2; extra == 'dev'
20
- Requires-Dist: mypy==2.4.1; extra == 'dev'
21
- Requires-Dist: pytest==9.2.0; extra == 'dev'
22
- Description-Content-Type: text/markdown
23
-
24
- # plain-parser
25
-
26
- Python parser for [`***plain`](https://www.plainlang.org/docs/) specification files.
27
-
28
- Reads a `.plain` module with its `import` / `requires` chain and its test plain files, resolves Liquid templates,
29
- validates concepts and linked resources, and returns the marshalled specification tree of every module in the
30
- chain, with the test scenarios of each functionality merged in.
31
-
32
- ## Install
33
-
34
- ```bash
35
- pip install plain-parser
36
- ```
37
-
38
- ## Command line
39
-
40
- ```
41
- plain-parser check <file.plain> [--template-dir DIR] [--tests-folder DIR]... [--config-name NAME]
42
- plain-parser parse <file.plain> [--template-dir DIR] [--tests-folder DIR]... [--config-name NAME]
43
- ```
44
-
45
- Both commands parse the module and its `requires` chain, bind the test plain files under the tests folders to the
46
- functionalities, check that every linked resource is an existing file (not a directory), and walk the module's
47
- functionalities. They stop at the first error.
48
-
49
- ### `check`
50
-
51
- Validates the module. In addition to the steps above it reads every linked file and rejects binary files and
52
- files holding a large base64 blob. When the config file names a `conformance-tests-script`, every functionality
53
- of every module in the chain needs a test plain file bound to it; the sections of the file may be empty.
54
-
55
- ```
56
- $ plain-parser check my_spec.plain
57
- my_spec.plain: OK
58
- ```
59
-
60
- Exit `0` when the module is valid. On an error, `Error: …` is written to stderr and the exit code is `1`. The
61
- message names the file and the line where known. The previous syntax (`- ` bullets instead of `# <func-id>`
62
- headings in `***functional specs***`, an `***acceptance tests***` section in a spec plain file) is reported as not
63
- supported. A functionality without a test plain file names the `add-test-scenarios` skill.
64
-
65
- ### `parse`
66
-
67
- Prints the parse result as one UTF-8 JSON document on stdout. Linked files are located but not read.
68
-
69
- ```
70
- $ plain-parser parse my_spec.plain
71
- {
72
- "format_version": 2,
73
- "modules": [{"module": "...", "tree": {...}}, ...],
74
- "resources": {...},
75
- "test_plain_files": {...}
76
- }
77
- ```
78
-
79
- - `format_version`: `2`.
80
- - `modules`: every module in the `requires` chain, in build order: deepest ancestor first, the module itself last.
81
- Each entry has the module name and its specification tree, in the shape described under *Python* below.
82
- - `resources`: every linked-resource target in the chain and its test plain files, as written in the spec, mapped
83
- to the path it resolves to, relative to the entry module's directory, with `/` as separator: `notes.md` when
84
- found next to the module, `../tpl/notes.md` when found in a template directory. The directory part is lexical
85
- (symlinks not resolved) and the target is appended as written (`..` kept), so joining the value onto the entry
86
- module's directory names the file the parser matched. When no relative path exists (another drive on Windows)
87
- the value is the absolute path, still with `/`. Two spellings of one file (`notes.md`, `./notes.md`) are two
88
- keys.
89
- - `test_plain_files`: every test plain file read, by its path relative to the entry module's directory with `/`
90
- as separator, mapped to `{"module": ..., "func_id": ...}`, the functionality it binds to.
91
-
92
- Exit `0` on success. On a parser error the JSON is `{"format_version": 2, "type": "<error class>",
93
- "message": "…"}` and the exit code is `1`.
94
-
95
- ### Options and exit codes
96
-
97
- Modules and `{% include %}` templates are looked up in the `.plain` file's directory, then in `--template-dir`.
98
- When `--template-dir` is not given, it is read from the `template-dir` key of `config.yaml` (or the file named by
99
- `--config-name`), found next to the `.plain` file or in the working directory. Finding it in both is a usage
100
- error. The config file is read even when `--template-dir` is given, so a malformed one fails the run either way.
101
-
102
- Test plain files are the `.plain` files under the tests folders: those given with `--tests-folder` (repeat the
103
- option for more than one), else the `tests-folder` key of the config file (a string or a list). Without both, no test
104
- plain files are read, and a config file that names a `conformance-tests-script` makes that a usage error. A test
105
- directory that does not exist is skipped. Linked resources in a scenario are looked up
106
- as in a module. The `conformance-tests-script` key of the config file turns on the check that every
107
- functionality has a test plain file. Other config keys are ignored.
108
-
109
- | Exit code | Meaning |
110
- |---|---|
111
- | `0` | Success |
112
- | `1` | The module, its chain, a test plain file, or a linked resource is invalid |
113
- | `2` | Usage error, including an ambiguous or malformed config file |
114
- | `130` | Interrupted |
115
-
116
- ## Python
117
-
118
- ```python
119
- from plain_parser import plain_file_parser, project
120
-
121
- module_name, plain_source_tree, required_modules = plain_file_parser("my_spec.plain", ["."])
122
-
123
- result = project.parse_project("my_spec.plain", ["."], ["tests"], require_test_plain_files=True)
124
- chain = result.chain # (module name, plain source tree) pairs, deepest ancestor first, the module itself last
125
- ```
126
-
127
- `plain_source_tree` is a dict keyed by section. `definitions`, `implementation reqs` and `test reqs` are lists
128
- of `{"markdown": ..., "linked_resources": [...]}` entries. `functional specs` is a list of
129
- `{"id", "markdown", "linked_resources", "conformance_tests", "acceptance_tests"}` entries, one per `# <func-id>`
130
- heading in file order; each test entry is `{"id", "text", "linked_resources"}` with the scenario text as written.
131
- `plain_parser.plain_spec` has helpers for walking functionalities by func-id (`get_frids`,
132
- `get_specifications_for_frid`, `collect_linked_resources`).
133
-
134
- ## Development
135
-
136
- ```bash
137
- uv venv --python 3.11 && source .venv/bin/activate
138
- uv pip install -e ".[dev]"
139
- pytest
140
- black . --check && isort . --check-only && flake8 . && mypy src
141
- ```
142
-
143
- ## License
144
-
145
- MIT, see [LICENSE](LICENSE).