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,11 +1,14 @@
1
+ """Helpers over the plain source tree: func-id navigation, specification collection, linked resources, hashing."""
2
+
1
3
  import hashlib
2
4
  import json
3
5
  import re
4
6
  import uuid
7
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
5
8
 
6
9
  from liquid2.filter import with_context
7
10
 
8
- from plain_parser.exceptions import InvalidFridArgument, InvalidLiquidVariableName
11
+ from plain_parser.exceptions import InvalidFridArgument, InvalidLiquidVariableName # noqa: F401
9
12
 
10
13
  DEFINITIONS = "definitions"
11
14
  NON_FUNCTIONAL_REQUIREMENTS = "implementation reqs"
@@ -15,16 +18,9 @@ CONFORMANCE_TESTS = "conformance_tests"
15
18
  ACCEPTANCE_TESTS = "acceptance_tests"
16
19
  CONFORMANCE_TEST_HEADING = "conformance tests"
17
20
  ACCEPTANCE_TEST_HEADING = "acceptance tests"
18
-
19
- # The sections whose content is a list of `- ` items.
20
21
  LIST_SECTION_HEADINGS = [DEFINITIONS, NON_FUNCTIONAL_REQUIREMENTS, TEST_REQUIREMENTS]
21
-
22
22
  ALLOWED_SPECIFICATION_HEADINGS = [*LIST_SECTION_HEADINGS, FUNCTIONAL_REQUIREMENTS]
23
-
24
23
  ALLOWED_IMPORT_SPECIFICATION_HEADINGS = LIST_SECTION_HEADINGS
25
-
26
- # A func-id or scenario-id: segments of lowercase letters and digits, with one hyphen between segments. So a
27
- # hyphen never starts or ends an id, two hyphens never touch, and an id is never only hyphens.
28
24
  SEMANTIC_ID_PATTERN = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
29
25
 
30
26
 
@@ -32,252 +28,197 @@ def is_semantic_id(text: str) -> bool:
32
28
  return SEMANTIC_ID_PATTERN.fullmatch(text) is not None
33
29
 
34
30
 
35
- def has_acceptance_tests(plain_source_tree) -> bool:
36
- """Return True if any functional requirement in the plain source defines acceptance tests."""
37
- functional_requirements = plain_source_tree.get(FUNCTIONAL_REQUIREMENTS) or []
38
- for functional_requirement in functional_requirements:
39
- if functional_requirement.get(ACCEPTANCE_TESTS):
40
- return True
41
- return False
42
-
43
-
44
- def collect_specification_linked_resources(specification, specification_heading, linked_resources_list):
45
- linked_resources = []
46
- if "linked_resources" in specification:
47
- linked_resources.extend(specification["linked_resources"])
48
-
49
- for resource in linked_resources:
50
- resource_found = False
51
- for resource_map in linked_resources_list:
52
- if resource["text"] == resource_map["text"]:
53
- if resource["target"] != resource_map["target"]:
54
- raise Exception(
55
- f"The file {resource['target']} is linked to multiple linked resources with the same text: {resource['text']}"
56
- )
57
- elif resource["target"] == resource_map["target"]:
58
- if resource["text"] != resource_map["text"]:
59
- raise Exception(
60
- f"The linked resource {resource['text']} is linked to multiple files: {resource_map['target']}"
61
- )
62
- else:
63
- continue
64
-
65
- if resource_found:
66
- raise Exception(
67
- "Duplicate linked resource found: " + resource["text"] + " (" + resource["target"] + ")"
68
- )
69
-
70
- resource_found = True
71
- resource_map["sections"].append(specification_heading)
72
-
73
- if not resource_found:
74
- linked_resources_list.append(
75
- {"text": resource["text"], "target": resource["target"], "sections": [specification_heading]}
76
- )
77
-
78
-
79
- def collect_linked_resources(
80
- plain_source_tree, linked_resources_list, specifications_list, include_test_scenarios, frid=None
81
- ):
82
- """Add the linked resources of the tree to ``linked_resources_list`` and sort the list by link text.
83
-
84
- ``specifications_list`` limits the sections read; None reads every section. The functional specs are read up to
85
- and including ``frid``, or all of them when ``frid`` is None. With ``include_test_scenarios`` the links of the
86
- conformance and acceptance scenarios are added too, for ``frid`` alone when one is given. Returns True when
87
- ``frid`` was reached.
88
- """
89
- if not isinstance(plain_source_tree, dict):
90
- raise ValueError("plain_source_tree must be a dictionary.")
91
-
92
- if frid is not None and frid not in get_frids(plain_source_tree):
93
- raise ValueError(f"frid {frid} does not exist.")
94
-
95
- sections_to_collect = [
96
- heading
97
- for heading in ALLOWED_SPECIFICATION_HEADINGS
98
- if heading in plain_source_tree and (not specifications_list or heading in specifications_list)
99
- ]
100
- frid_reached = False
101
- for specification_heading in sections_to_collect:
102
- for specification in plain_source_tree[specification_heading]:
103
- collect_specification_linked_resources(specification, specification_heading, linked_resources_list)
104
-
105
- if specification_heading != FUNCTIONAL_REQUIREMENTS:
106
- continue
107
-
108
- if include_test_scenarios and (frid is None or frid == specification["id"]):
109
- scenarios = [*specification.get(CONFORMANCE_TESTS, []), *specification.get(ACCEPTANCE_TESTS, [])]
110
- for scenario in scenarios:
111
- collect_specification_linked_resources(scenario, FUNCTIONAL_REQUIREMENTS, linked_resources_list)
31
+ def _functionalities(plain_source_tree) -> List[Dict[str, Any]]:
32
+ return list(plain_source_tree.get(FUNCTIONAL_REQUIREMENTS, []))
112
33
 
113
- if specification["id"] == frid:
114
- frid_reached = True
115
- break
116
34
 
117
- linked_resources_list.sort(key=lambda x: x["text"])
118
-
119
- return frid_reached
35
+ def has_acceptance_tests(plain_source_tree) -> bool:
36
+ return any(f.get(ACCEPTANCE_TESTS) for f in _functionalities(plain_source_tree))
120
37
 
121
38
 
122
- def get_frids(plain_source_tree):
123
- """The func-ids of the tree's functionalities, in file order."""
124
- for functionality in plain_source_tree.get(FUNCTIONAL_REQUIREMENTS) or []:
39
+ def get_frids(plain_source_tree) -> Iterator[str]:
40
+ for functionality in _functionalities(plain_source_tree):
125
41
  yield functionality["id"]
126
42
 
127
43
 
128
- def get_first_frid(plain_source_tree):
44
+ def get_first_frid(plain_source_tree) -> Optional[str]:
129
45
  return next(get_frids(plain_source_tree), None)
130
46
 
131
47
 
132
- def get_next_frid(plain_source_tree, frid):
133
- functional_requirements = get_frids(plain_source_tree)
134
- for temp_frid in functional_requirements:
135
- if temp_frid == frid:
136
- return next(functional_requirements, None)
137
-
138
- raise Exception(f"Functionality {frid} does not exist.")
139
-
140
-
141
- def get_previous_frid(plain_source_tree, frid):
142
- previous_frid = None
143
- for temp_frid in get_frids(plain_source_tree):
144
- if temp_frid == frid:
145
- return previous_frid
48
+ def get_next_frid(plain_source_tree, frid) -> Optional[str]:
49
+ frids = list(get_frids(plain_source_tree))
50
+ if frid not in frids:
51
+ raise Exception(f"Functionality {frid} does not exist.")
52
+ position = frids.index(frid) + 1
53
+ return frids[position] if position < len(frids) else None
146
54
 
147
- previous_frid = temp_frid
148
55
 
149
- raise Exception(f"Functionality {frid} does not exist.")
56
+ def get_previous_frid(plain_source_tree, frid) -> Optional[str]:
57
+ frids = list(get_frids(plain_source_tree))
58
+ if frid not in frids:
59
+ raise Exception(f"Functionality {frid} does not exist.")
60
+ position = frids.index(frid) - 1
61
+ return frids[position] if position >= 0 else None
150
62
 
151
63
 
152
- def get_frids_before(plain_source_tree, target_frid: str) -> list[str]:
153
- """The func-ids that come before ``target_frid`` in the specification, in order."""
154
- previous_frids = []
64
+ def get_frids_before(plain_source_tree, target_frid: str) -> List[str]:
65
+ before: List[str] = []
155
66
  for frid in get_frids(plain_source_tree):
156
67
  if frid == target_frid:
157
68
  break
158
- previous_frids.append(frid)
69
+ before.append(frid)
70
+ return before
159
71
 
160
- return previous_frids
72
+
73
+ def get_frids_range(plain_source, start, end=None) -> List[str]:
74
+ frids = list(get_frids(plain_source))
75
+ if start not in frids:
76
+ raise InvalidFridArgument(f"Invalid start functionality ID: {start}. Valid IDs are: {frids}.")
77
+ if end is not None and end not in frids:
78
+ raise InvalidFridArgument(f"Invalid end functionality ID: {end}. Valid IDs are: {frids}.")
79
+ start_position = frids.index(start)
80
+ if end is None:
81
+ return frids[start_position:]
82
+ end_position = frids.index(end)
83
+ if start_position > end_position:
84
+ raise InvalidFridArgument(f"Start functionality ID: {start} must be before end functionality ID: {end}.")
85
+ return frids[start_position : end_position + 1]
86
+
87
+
88
+ def get_specification_item_markdown(specification_item, code_variables, replace_code_variables, key="markdown") -> str:
89
+ """Return the text of an item, recording its code variables and, when asked, replacing their placeholders."""
90
+ text = specification_item[key]
91
+ for variable in specification_item.get("code_variables", []):
92
+ name, value = variable["name"], variable["value"]
93
+ if name in code_variables and code_variables[name] != value:
94
+ raise Exception(f"Code variable {name} has multiple values: {code_variables[name]} and {value}")
95
+ code_variables[name] = value
96
+ if replace_code_variables:
97
+ text = text.replace("{{ " + name + " }}", value)
98
+ return text
99
+
100
+
101
+ def get_specifications_for_frid(plain_source_tree, frid, replace_code_variables=True) -> Tuple[dict, Optional[dict]]:
102
+ """Return the specification texts that build one functionality, and the code variables they use."""
103
+ functionalities = _functionalities(plain_source_tree)
104
+ if frid not in [f["id"] for f in functionalities]:
105
+ raise Exception(f"Functionality {frid} does not exist.")
106
+ code_variables: Dict[str, str] = {}
107
+ specifications: Dict[str, list] = {}
108
+ for heading in LIST_SECTION_HEADINGS:
109
+ specifications[heading] = [
110
+ get_specification_item_markdown(item, code_variables, replace_code_variables)
111
+ for item in plain_source_tree.get(heading, [])
112
+ ]
113
+ specifications[FUNCTIONAL_REQUIREMENTS] = []
114
+ specifications[CONFORMANCE_TESTS] = []
115
+ specifications[ACCEPTANCE_TESTS] = []
116
+ for functionality in functionalities:
117
+ specifications[FUNCTIONAL_REQUIREMENTS].append(
118
+ get_specification_item_markdown(functionality, code_variables, replace_code_variables)
119
+ )
120
+ if functionality["id"] == frid:
121
+ for key in (CONFORMANCE_TESTS, ACCEPTANCE_TESTS):
122
+ for scenario in functionality.get(key, []):
123
+ text = get_specification_item_markdown(scenario, code_variables, replace_code_variables, "text")
124
+ specifications[key].append({"id": scenario["id"], "text": text})
125
+ break
126
+ return specifications, (code_variables or None)
161
127
 
162
128
 
163
- def get_specification_item_markdown(specification_item, code_variables, replace_code_variables, key="markdown"):
164
- """The text under ``key`` of the item, with its code variables recorded in ``code_variables`` and, when
165
- ``replace_code_variables`` is set, their values put in place of the `{{ name }}` placeholders."""
166
- markdown = specification_item[key]
167
- if "code_variables" in specification_item:
168
- for code_variable in specification_item["code_variables"]:
169
- if code_variable["name"] in code_variables:
170
- if code_variables[code_variable["name"]] != code_variable["value"]:
129
+ def collect_specification_linked_resources(specification, specification_heading, linked_resources_list) -> None:
130
+ """Add the links of every item of a section to the registry, sorting it afterwards is the caller's job."""
131
+ for item in specification:
132
+ for link in item.get("linked_resources", []):
133
+ text, target = link["text"], link["target"]
134
+ same = [e for e in linked_resources_list if e["text"] == text and e["target"] == target]
135
+ if len(same) > 1:
136
+ raise Exception(f"Duplicate linked resource found: {text} ({target})")
137
+ if same:
138
+ same[0]["sections"].append(specification_heading)
139
+ continue
140
+ for entry in linked_resources_list:
141
+ if entry["text"] == text:
171
142
  raise Exception(
172
- f"Code variable {code_variable['name']} has multiple values: {code_variables[code_variable['name']]} and {code_variable['value']}"
143
+ f"The file {target} is linked to multiple linked resources with the same text: {text}"
173
144
  )
174
- else:
175
- code_variables[code_variable["name"]] = code_variable["value"]
145
+ if entry["target"] == target:
146
+ raise Exception(f"The linked resource {text} is linked to multiple files: {target}")
147
+ linked_resources_list.append({"text": text, "target": target, "sections": [specification_heading]})
176
148
 
177
- if replace_code_variables:
178
- markdown = markdown.replace(f"{{{{ {code_variable['name']} }}}}", code_variable["value"])
179
149
 
180
- return markdown
150
+ def collect_linked_resources(
151
+ plain_source_tree, linked_resources_list, specifications_list, include_test_scenarios, frid=None
152
+ ) -> bool:
153
+ """Collect the links of a tree into a registry, up to a func-id; true when that func-id was reached."""
154
+ if not isinstance(plain_source_tree, dict):
155
+ raise ValueError("plain_source_tree must be a dictionary.")
156
+ if frid is not None and frid not in list(get_frids(plain_source_tree)):
157
+ raise ValueError(f"frid {frid} does not exist.")
158
+ headings = list(specifications_list) if specifications_list is not None else ALLOWED_SPECIFICATION_HEADINGS
159
+ reached = False
160
+ for heading in ALLOWED_SPECIFICATION_HEADINGS:
161
+ if heading not in headings or heading not in plain_source_tree:
162
+ continue
163
+ if heading != FUNCTIONAL_REQUIREMENTS:
164
+ collect_specification_linked_resources(plain_source_tree[heading], heading, linked_resources_list)
165
+ continue
166
+ for functionality in plain_source_tree[heading]:
167
+ collect_specification_linked_resources([functionality], heading, linked_resources_list)
168
+ is_target = frid is not None and functionality["id"] == frid
169
+ if include_test_scenarios and (frid is None or is_target):
170
+ for key in (CONFORMANCE_TESTS, ACCEPTANCE_TESTS):
171
+ collect_specification_linked_resources(functionality.get(key, []), heading, linked_resources_list)
172
+ if is_target:
173
+ reached = True
174
+ break
175
+ linked_resources_list.sort(key=lambda entry: entry["text"])
176
+ return reached
181
177
 
182
178
 
183
- def get_specifications_for_frid(plain_source_tree, frid, replace_code_variables=True):
184
- """The specifications that build ``frid``: every list section, the functional specs up to and including
185
- ``frid``, and the conformance and acceptance scenarios of ``frid`` as `{"id", "text"}` entries.
179
+ def hash_text(text: str) -> str:
180
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
186
181
 
187
- Returns the specifications and the code variables they use (None when there are none). Raise when ``frid``
188
- is not in the tree.
189
- """
190
- functionalities = plain_source_tree.get(FUNCTIONAL_REQUIREMENTS) or []
191
- position = next((index for index, item in enumerate(functionalities) if item["id"] == frid), None)
192
- if position is None:
193
- raise Exception(f"Functionality {frid} does not exist.")
194
182
 
195
- code_variables = {}
183
+ def get_hash_value(specifications) -> str:
184
+ return hash_text(json.dumps(specifications, indent=4, ensure_ascii=True))
196
185
 
197
- def texts(items, key="markdown"):
198
- return [get_specification_item_markdown(item, code_variables, replace_code_variables, key) for item in items]
199
186
 
200
- def scenarios(items):
201
- return [{"id": item["id"], "text": text} for item, text in zip(items, texts(items, "text"))]
187
+ _BUILT_IN_VARIABLES = ("now", "today")
202
188
 
203
- functionality = functionalities[position]
204
- specifications = {
205
- DEFINITIONS: texts(plain_source_tree.get(DEFINITIONS) or []),
206
- NON_FUNCTIONAL_REQUIREMENTS: texts(plain_source_tree.get(NON_FUNCTIONAL_REQUIREMENTS) or []),
207
- TEST_REQUIREMENTS: texts(plain_source_tree.get(TEST_REQUIREMENTS) or []),
208
- FUNCTIONAL_REQUIREMENTS: texts(functionalities[: position + 1]),
209
- CONFORMANCE_TESTS: scenarios(functionality.get(CONFORMANCE_TESTS, [])),
210
- ACCEPTANCE_TESTS: scenarios(functionality.get(ACCEPTANCE_TESTS, [])),
211
- }
212
189
 
213
- return specifications, (code_variables or None)
190
+ def _first_variable_name(context) -> Optional[str]:
191
+ """Name of the first variable in the Liquid scope: the first named argument of the enclosing include tag."""
192
+ for name in context.scope:
193
+ if name not in _BUILT_IN_VARIABLES:
194
+ return name
195
+ return None
214
196
 
215
197
 
216
198
  @with_context
217
199
  def code_variable_liquid_filter(value, *, context):
218
- if len(context.scope) == 0:
200
+ """Mark a value as a code variable: store it under a random token and output the token."""
201
+ name = _first_variable_name(context)
202
+ if name is None:
219
203
  raise Exception("Invalid use of code_variable filter!")
220
-
221
- if "code_variables" in context.globals:
222
- code_variables = context.globals["code_variables"]
223
-
224
- variable = next(iter(context.scope.items()))
225
-
226
- unique_str = uuid.uuid4().hex
227
-
228
- code_variables[unique_str] = {variable[0]: value}
229
-
230
- return unique_str
231
- else:
232
-
204
+ code_variables = context.scope.get("code_variables")
205
+ if not isinstance(code_variables, dict):
233
206
  return value
207
+ token = uuid.uuid4().hex
208
+ code_variables[token] = {name: value}
209
+ return token
234
210
 
235
211
 
236
212
  @with_context
237
213
  def prohibited_chars_liquid_filter(value, prohibited_chars, *, context):
238
- if not isinstance(value, str):
239
- value = str(value)
240
-
241
- if len(context.scope) == 0:
214
+ """Output a value as text, unless it holds one of the prohibited characters."""
215
+ name = _first_variable_name(context)
216
+ if name is None:
242
217
  raise Exception("Invalid use of prohibited_chars filter!")
243
-
244
- variable = next(iter(context.scope.items()))
245
- variable_name = variable[0]
246
-
247
- for char in prohibited_chars:
248
- if char in value:
218
+ text = str(value)
219
+ for char in text:
220
+ if char in str(prohibited_chars):
249
221
  raise InvalidLiquidVariableName(
250
- f"'{char}' is not a valid character for variable '{variable_name}' (value: '{value}')."
222
+ f"'{char}' is not a valid character for variable '{name}' (value: '{text}')."
251
223
  )
252
-
253
- return value
254
-
255
-
256
- def hash_text(text):
257
- return hashlib.sha256(text.encode()).hexdigest()
258
-
259
-
260
- def get_hash_value(specifications):
261
- return hash_text(json.dumps(specifications, indent=4))
262
-
263
-
264
- def get_frids_range(plain_source, start, end=None):
265
- """The func-ids from ``start`` through ``end`` inclusive, or through the last one when ``end`` is None."""
266
- frids = list(get_frids(plain_source))
267
-
268
- if start not in frids:
269
- raise InvalidFridArgument(f"Invalid start functionality ID: {start}. Valid IDs are: {frids}.")
270
-
271
- if end is not None:
272
- if end not in frids:
273
- raise InvalidFridArgument(f"Invalid end functionality ID: {end}. Valid IDs are: {frids}.")
274
-
275
- end_idx = frids.index(end) + 1
276
- else:
277
- end_idx = len(frids)
278
-
279
- start_idx = frids.index(start)
280
- if start_idx >= end_idx:
281
- raise InvalidFridArgument(f"Start functionality ID: {start} must be before end functionality ID: {end}.")
282
-
283
- return frids[start_idx:end_idx]
224
+ return text