-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathprocessors.py
More file actions
295 lines (231 loc) · 8.65 KB
/
processors.py
File metadata and controls
295 lines (231 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
This module defines common processor classes used in the package. It defines classes to
handle common notations like:
[example(pros?)(content-source)]
and
::example:: (props?) ...
content
::/example::
"""
import logging
import re
import textwrap
import xml.etree.ElementTree as etree
from abc import ABC, abstractmethod
from typing import Iterable
from markdown.blockprocessors import BlockProcessor
from neoteroi.mkdocs.markdown import parse_props
from neoteroi.mkdocs.markdown.data.files import FileReader
from neoteroi.mkdocs.markdown.data.source import DataReader
from neoteroi.mkdocs.markdown.data.text import (
CSVParser,
JSONParser,
TextParser,
YAMLParser,
)
from neoteroi.mkdocs.markdown.data.web import HTTPDataReader
logger = logging.getLogger("MARKDOWN")
def find_closing_fragment_index(pattern: re.Pattern, blocks: list[str]) -> int:
for index, block in enumerate(blocks):
if pattern.search(block):
return index
return -1
def pop_to_index(items, index):
"""
Pops elements from a source list, and yields them up to the given index,
included.
Example:
pop_to_index([1, 2, 3, 4], 2) -> yields 1, 2, 3,
removing them from the source list.
"""
i = 0
while i <= index:
block = items.pop(0)
yield block + "\n"
i += 1
class BaseProcessor(ABC):
root_config: dict = {}
parsers: Iterable[TextParser] = (YAMLParser(), JSONParser(), CSVParser())
@property
@abstractmethod
def name(self) -> str:
"""Returns the name of the tag that will be handled by this processor."""
@abstractmethod
def build_html(self, parent, obj, props) -> None:
"""Builds the HTML for the given input object."""
def get_parsers(self, props):
"""
Tries to get the best parser by tag property.
"""
if props.get("yaml") is True:
return [YAMLParser()]
if props.get("json") is True:
return [JSONParser()]
if props.get("csv") is True:
return [CSVParser()]
return self.parsers
def render_courtesy_error(self, parent, message: str):
div = etree.SubElement(parent, "div", {"class": "nt-error"})
p = etree.SubElement(div, "p")
p.text = message
def parse(self, text, props):
for parser in self.get_parsers(props):
try:
return parser.parse(text)
except (TypeError, ValueError) as parser_exc:
logger.debug(
"The parser %s failed to parse the text.",
type(parser).__qualname__,
exc_info=parser_exc,
)
raise ValueError("The input text could not be parsed.")
def render(self, parent, data, props):
if isinstance(data, str):
try:
obj = self.parse(data, props)
except ValueError:
logger.exception("Could not parse the value of a %s block.", self.name)
self.render_courtesy_error(
parent,
f"Could not parse the value of this {self.name} block. "
"Please correct the input.",
)
return
else:
obj = data
try:
self.build_html(parent, obj, props)
except (ValueError, TypeError):
logger.exception("Could not render a %s block.", self.name)
self.render_courtesy_error(
parent,
f"Could not render a {self.name} block. Please correct the input.",
)
def get_match(self, pattern, blocks) -> re.Match | None:
first_block = blocks.pop(0)
new_lines = []
match = None
for line in first_block.splitlines():
match = pattern.match(line)
if match:
break
else:
new_lines.append(line)
if new_lines:
blocks.insert(0, "\n".join(new_lines))
return match
def with_root_config(self, props):
self.__dict__["root_config"] = props
return self
class SourceBlockProcessor(BlockProcessor, BaseProcessor):
"""
Base class for inline processors that read information from a file or URL source
and handle it to create an HTML element, like:
[timeline(./example.yaml)]
[timeline(https://.../example.json)]
"""
_pattern: re.Pattern | None = None
@property
def pattern(self) -> re.Pattern:
if self._pattern is None:
self._pattern = re.compile(
rf"(?P<indent>\s*)\[{self.name}\s?([^\(]*)\((.*?)\)\]", re.DOTALL
)
return self._pattern
def test(self, parent, block) -> bool:
if self.pattern.search(block):
return True
else:
return False
data_readers: Iterable[DataReader] = (FileReader(), HTTPDataReader())
def get_data_reader(self, source: str) -> DataReader:
if not source:
raise ValueError("Missing source parameter.")
for reader in self.data_readers:
if reader.test(source):
return reader
logger.warning("[%s] could not resolve the source: %s", self.name, source)
raise ValueError(
f'[{self.name}] invalid source. The source "{source}" could not be '
"resolved. If the source is a file, please verify the path."
)
def read_from_source(self, source: str):
reader = self.get_data_reader(source)
return reader.read(source)
def run(self, parent, blocks):
match = self.get_match(self.pattern, blocks)
assert match is not None
groups = match.groups()
raw_props = groups[1]
source = groups[2]
if raw_props:
props = parse_props(raw_props, bool_attrs=True)
else:
props = {}
props["__source"] = source
try:
data = self.read_from_source(source)
except ValueError as value_error:
self.render_courtesy_error(parent, str(value_error))
else:
self.render(parent, data, props)
class EmbeddedBlockProcessor(BlockProcessor, BaseProcessor):
"""
Base class for standard block processors that handle a fragment like:
::example:: format prop_1="value_1" prop_2="value_2" ...
[CSV | JSON | YAML]
::/example::
This class provides base functions to handle the Markdown integration and parsing of
the input, concrete classes define how to build the HTML once the input has been
parsed.
The source of data in this case is always coming as a string.
"""
_start_pattern: re.Pattern | None = None
_end_pattern: re.Pattern | None = None
@property
def start_pattern(self) -> re.Pattern:
if self._start_pattern is None:
self._start_pattern = re.compile(
rf"""(?P<indent>\s*)::{self.name}::([^\n]*)?""", re.DOTALL
)
return self._start_pattern
@property
def end_pattern(self) -> re.Pattern:
if self._end_pattern is None:
self._end_pattern = re.compile(rf"\s*::/{self.name}::\s*\n?")
return self._end_pattern
def test(self, parent, block) -> bool:
if self.start_pattern.search(block):
return True
else:
return False
def find_closing_fragment_index(self, blocks) -> int:
return find_closing_fragment_index(self.end_pattern, blocks)
def get_content(self, relevant_blocks):
raw_text = textwrap.dedent("".join(relevant_blocks))
return self.end_pattern.sub("", self.start_pattern.sub("", raw_text))
def run(self, parent, blocks):
closing_block_index = self.find_closing_fragment_index(blocks)
if closing_block_index == -1:
# unclosed tag, ignore
logger.warning(
f"Unclosed ::{self.name}:: block - expected a ::/{self.name}:: block."
)
return False
match = self.start_pattern.match(blocks[0])
assert match is not None, "A match here is expected"
props = parse_props(
match.group(0).lstrip().replace(f"::{self.name}::", ""), bool_attrs=True
)
if closing_block_index == 0:
# there is no carriage return, which is not ideal for
# what we want to achieve
single_block = blocks[0].lstrip()
raw_text = textwrap.dedent(
self.end_pattern.sub("", self.start_pattern.sub("", single_block))
).lstrip()
blocks.pop(0)
else:
blocks.pop(0)
raw_text = self.get_content(pop_to_index(blocks, closing_block_index - 1))
self.render(parent, raw_text, props)