-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmacros.py
105 lines (84 loc) · 2.35 KB
/
macros.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""MkDocs macros for the documentation site."""
import functools
import os
import re
from pathlib import Path
from mkdocs_macros.plugin import MacrosPlugin
from sh import python, ErrorReturnCode
TEMPLATE = """
<div class="side-by-side" style="max-width: 100%" markdown>
<div class="admonition info" markdown>
<p class="admonition-title" markdown>{path}</p>
```python
{code}
```
{annotations}
</div>
<div class="admonition {output_block_class}" markdown>
<p class="admonition-title">python</p>
```python
{output}
```
</div>
</div>
"""
def format_annotations(annotations: list[str]) -> str:
"""Format annotations for a piece of code."""
enumerated_annotations = enumerate(annotations, start=1)
return '\n\n'.join(
f'{number}. {annotation}'
for number, annotation in enumerated_annotations
)
def replace_full_file_path(line: str, code_path: Path) -> str:
"""Replace full file path with its absolute path, for conciseness."""
return line.replace(str(code_path.parent.absolute()), '📂')
def run_python_script(
path: str,
docs_dir: Path,
annotations: list[str] | None = None,
args: list[str] | None = None,
):
if annotations is None:
annotations = []
if args is None:
args = []
code_path = docs_dir / path
code = code_path.read_text()
try:
stdout, stderr = python(
*args,
code_path,
_env={
**os.environ,
'TERM': 'dumb',
},
), None
except ErrorReturnCode as err:
stdout = err.stdout.decode()
stderr = err.stderr.decode()
cmd = 'python'
if args:
formatted_args = ' '.join(args)
cmd = f'{cmd} {formatted_args}'
output = '\n'.join(filter(bool, [stdout, stderr]))
output = '\n'.join(
replace_full_file_path(line=line, code_path=code_path)
for line in output.splitlines()
)
return TEMPLATE.format(
path=path,
code=code,
output=output,
annotations=format_annotations(annotations),
cmd=cmd,
output_block_class='failure' if stderr else 'success',
)
def define_env(env: MacrosPlugin):
"""Hook function."""
env.macro(
functools.partial(
run_python_script,
docs_dir=Path(env.conf['docs_dir']),
),
name='run_python_script',
)