-
Notifications
You must be signed in to change notification settings - Fork 633
/
Copy path_renderer.py
91 lines (74 loc) · 3.01 KB
/
_renderer.py
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
from __future__ import annotations
from textwrap import dedent
import quartodoc as qd
import toolz
from plum import dispatch
class Renderer(qd.MdRenderer):
style = "ibis"
@dispatch
def render(self, el: qd.ast.ExampleCode) -> str:
lines = el.value.splitlines()
result = []
prompt = ">>> "
continuation = "..."
skip_doctest = "doctest: +SKIP"
expect_failure = "quartodoc: +EXPECTED_FAILURE"
quartodoc_skip_doctest = "quartodoc: +SKIP"
chunker = lambda line: line.startswith((prompt, continuation))
should_skip = (
lambda line: quartodoc_skip_doctest in line or skip_doctest in line
)
for chunk in toolz.partitionby(chunker, lines):
first, *rest = chunk
# only attempt to execute or render code blocks that start with the
# >>> prompt
if first.startswith(prompt):
# check whether to skip execution and if so, render the code
# block as `python` (not `{python}`) if it's marked with
# skip_doctest, expect_failure or quartodoc_skip_doctest
if skipped := any(map(should_skip, chunk)):
start = end = ""
else:
start, end = "{}"
result.append(
dedent(
"""
```{python}
#| echo: false
import ibis
ibis.options.interactive = True
```
"""
)
)
result.append(f"```{start}python{end}")
# if we expect failures, don't fail the notebook execution and
# render the error message
if expect_failure in first or any(
expect_failure in line for line in rest
):
assert start and end, (
"expected failure should never occur alongside a skipped doctest example"
)
result.append("#| error: true")
# remove the quartodoc markers from the rendered code
result.append(
first.replace(f"# {quartodoc_skip_doctest}", "")
.replace(quartodoc_skip_doctest, "")
.replace(f"# {expect_failure}", "")
.replace(expect_failure, "")
)
result.extend(rest)
result.append("```\n")
if not skipped:
result.append(
dedent(
"""
```{python}
#| echo: false
ibis.options.interactive = False
```
"""
)
)
return "\n".join(result)