/
__init__.py
302 lines (275 loc) · 9.75 KB
/
__init__.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
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
296
297
298
299
300
301
302
from __future__ import annotations
import argparse
import contextlib
import re
import textwrap
from typing import Generator
from typing import Match
from typing import Sequence
import black
from black.const import DEFAULT_LINE_LENGTH
from black.mode import TargetVersion
PYGMENTS_PY_LANGS = frozenset(("python", "py", "sage", "python3", "py3", "numpy"))
PYGMENTS_PY_LANGS_RE_FRAGMENT = f"({'|'.join(PYGMENTS_PY_LANGS)})"
MD_RE = re.compile(
r"(?P<before>^(?P<indent> *)```\s*" + PYGMENTS_PY_LANGS_RE_FRAGMENT + r"( .*?)?\n)"
r"(?P<code>.*?)"
r"(?P<after>^(?P=indent)```\s*$)",
re.DOTALL | re.MULTILINE,
)
MD_PYCON_RE = re.compile(
r"(?P<before>^(?P<indent> *)```\s*pycon( .*?)?\n)"
r"(?P<code>.*?)"
r"(?P<after>^(?P=indent)```.*$)",
re.DOTALL | re.MULTILINE,
)
BLOCK_TYPES = "(code|code-block|sourcecode|ipython)"
DOCTEST_TYPES = "(testsetup|testcleanup|testcode)"
RST_RE = re.compile(
rf"(?P<before>"
rf"^(?P<indent> *)\.\. ("
rf"jupyter-execute::|"
rf"{BLOCK_TYPES}:: (?P<lang>\w+)|"
rf"{DOCTEST_TYPES}::.*"
rf")\n"
rf"((?P=indent) +:.*\n)*"
rf"( *\n)*"
rf")"
rf"(?P<code>(^((?P=indent) +.*)?\n)+)",
re.MULTILINE,
)
RST_LITERAL_BLOCKS_RE = re.compile(
r"(?P<before>"
r"^(?! *\.\. )(?P<indent> *).*::\n"
r"((?P=indent) +:.*\n)*"
r"\n*"
r")"
r"(?P<code>(^((?P=indent) +.*)?\n)+)",
re.MULTILINE,
)
RST_PYCON_RE = re.compile(
r"(?P<before>"
r"(?P<indent> *)\.\. ((code|code-block):: pycon|doctest::.*)\n"
r"((?P=indent) +:.*\n)*"
r"\n*"
r")"
r"(?P<code>(^((?P=indent) +.*)?(\n|$))+)",
re.MULTILINE,
)
PYCON_PREFIX = ">>> "
PYCON_CONTINUATION_PREFIX = "..."
PYCON_CONTINUATION_RE = re.compile(
rf"^{re.escape(PYCON_CONTINUATION_PREFIX)}( |$)",
)
LATEX_RE = re.compile(
r"(?P<before>^(?P<indent> *)\\begin{minted}{python}\n)"
r"(?P<code>.*?)"
r"(?P<after>^(?P=indent)\\end{minted}\s*$)",
re.DOTALL | re.MULTILINE,
)
LATEX_PYCON_RE = re.compile(
r"(?P<before>^(?P<indent> *)\\begin{minted}{pycon}\n)"
r"(?P<code>.*?)"
r"(?P<after>^(?P=indent)\\end{minted}\s*$)",
re.DOTALL | re.MULTILINE,
)
PYTHONTEX_LANG = r"(?P<lang>pyblock|pycode|pyconsole|pyverbatim)"
PYTHONTEX_RE = re.compile(
rf"(?P<before>^(?P<indent> *)\\begin{{{PYTHONTEX_LANG}}}\n)"
rf"(?P<code>.*?)"
rf"(?P<after>^(?P=indent)\\end{{(?P=lang)}}\s*$)",
re.DOTALL | re.MULTILINE,
)
INDENT_RE = re.compile("^ +(?=[^ ])", re.MULTILINE)
TRAILING_NL_RE = re.compile(r"\n+\Z", re.MULTILINE)
class CodeBlockError:
def __init__(self, offset: int, exc: Exception) -> None:
self.offset = offset
self.exc = exc
def format_str(
src: str,
black_mode: black.FileMode,
*,
rst_literal_blocks: bool = False,
) -> tuple[str, Sequence[CodeBlockError]]:
errors: list[CodeBlockError] = []
@contextlib.contextmanager
def _collect_error(match: Match[str]) -> Generator[None, None, None]:
try:
yield
except Exception as e:
errors.append(CodeBlockError(match.start(), e))
def _md_match(match: Match[str]) -> str:
code = textwrap.dedent(match["code"])
with _collect_error(match):
code = black.format_str(code, mode=black_mode)
code = textwrap.indent(code, match["indent"])
return f'{match["before"]}{code}{match["after"]}'
def _rst_match(match: Match[str]) -> str:
lang = match["lang"]
if lang is not None and lang not in PYGMENTS_PY_LANGS:
return match[0]
min_indent = min(INDENT_RE.findall(match["code"]))
trailing_ws_match = TRAILING_NL_RE.search(match["code"])
assert trailing_ws_match
trailing_ws = trailing_ws_match.group()
code = textwrap.dedent(match["code"])
with _collect_error(match):
code = black.format_str(code, mode=black_mode)
code = textwrap.indent(code, min_indent)
return f'{match["before"]}{code.rstrip()}{trailing_ws}'
def _rst_literal_blocks_match(match: Match[str]) -> str:
if not match["code"].strip():
return match[0]
min_indent = min(INDENT_RE.findall(match["code"]))
trailing_ws_match = TRAILING_NL_RE.search(match["code"])
assert trailing_ws_match
trailing_ws = trailing_ws_match.group()
code = textwrap.dedent(match["code"])
with _collect_error(match):
code = black.format_str(code, mode=black_mode)
code = textwrap.indent(code, min_indent)
return f'{match["before"]}{code.rstrip()}{trailing_ws}'
def _pycon_match(match: Match[str]) -> str:
code = ""
fragment: str | None = None
def finish_fragment() -> None:
nonlocal code
nonlocal fragment
if fragment is not None:
with _collect_error(match):
fragment = black.format_str(fragment, mode=black_mode)
fragment_lines = fragment.splitlines()
code += f"{PYCON_PREFIX}{fragment_lines[0]}\n"
for line in fragment_lines[1:]:
# Skip blank lines to handle Black adding a blank above
# functions within blocks. A blank line would end the REPL
# continuation prompt.
#
# >>> if True:
# ... def f():
# ... pass
# ...
if line:
code += f"{PYCON_CONTINUATION_PREFIX} {line}\n"
if fragment_lines[-1].startswith(" "):
code += f"{PYCON_CONTINUATION_PREFIX}\n"
fragment = None
indentation = None
for line in match["code"].splitlines():
orig_line, line = line, line.lstrip()
if indentation is None and line:
indentation = len(orig_line) - len(line)
continuation_match = PYCON_CONTINUATION_RE.match(line)
if continuation_match and fragment is not None:
fragment += line[continuation_match.end() :] + "\n"
else:
finish_fragment()
if line.startswith(PYCON_PREFIX):
fragment = line[len(PYCON_PREFIX) :] + "\n"
else:
code += orig_line[indentation:] + "\n"
finish_fragment()
return code
def _md_pycon_match(match: Match[str]) -> str:
code = _pycon_match(match)
code = textwrap.indent(code, match["indent"])
return f'{match["before"]}{code}{match["after"]}'
def _rst_pycon_match(match: Match[str]) -> str:
code = _pycon_match(match)
min_indent = min(INDENT_RE.findall(match["code"]))
code = textwrap.indent(code, min_indent)
return f'{match["before"]}{code}'
def _latex_match(match: Match[str]) -> str:
code = textwrap.dedent(match["code"])
with _collect_error(match):
code = black.format_str(code, mode=black_mode)
code = textwrap.indent(code, match["indent"])
return f'{match["before"]}{code}{match["after"]}'
def _latex_pycon_match(match: Match[str]) -> str:
code = _pycon_match(match)
code = textwrap.indent(code, match["indent"])
return f'{match["before"]}{code}{match["after"]}'
src = MD_RE.sub(_md_match, src)
src = MD_PYCON_RE.sub(_md_pycon_match, src)
src = RST_RE.sub(_rst_match, src)
src = RST_PYCON_RE.sub(_rst_pycon_match, src)
if rst_literal_blocks:
src = RST_LITERAL_BLOCKS_RE.sub(
_rst_literal_blocks_match,
src,
)
src = LATEX_RE.sub(_latex_match, src)
src = LATEX_PYCON_RE.sub(_latex_pycon_match, src)
src = PYTHONTEX_RE.sub(_latex_match, src)
return src, errors
def format_file(
filename: str,
black_mode: black.FileMode,
skip_errors: bool,
rst_literal_blocks: bool,
) -> int:
with open(filename, encoding="UTF-8") as f:
contents = f.read()
new_contents, errors = format_str(
contents,
black_mode,
rst_literal_blocks=rst_literal_blocks,
)
for error in errors:
lineno = contents[: error.offset].count("\n") + 1
print(f"{filename}:{lineno}: code block parse error {error.exc}")
if errors and not skip_errors:
return 2
if contents != new_contents:
print(f"{filename}: Rewriting...")
with open(filename, "w", encoding="UTF-8") as f:
f.write(new_contents)
return 1
else:
return 0
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"-l",
"--line-length",
type=int,
default=DEFAULT_LINE_LENGTH,
)
parser.add_argument("--preview", action="store_true")
parser.add_argument(
"-S",
"--skip-string-normalization",
action="store_true",
)
parser.add_argument(
"-t",
"--target-version",
action="append",
type=lambda v: TargetVersion[v.upper()],
default=[],
help=f"choices: {[v.name.lower() for v in TargetVersion]}",
dest="target_versions",
)
parser.add_argument("-E", "--skip-errors", action="store_true")
parser.add_argument(
"--rst-literal-blocks",
action="store_true",
)
parser.add_argument("filenames", nargs="*")
args = parser.parse_args(argv)
black_mode = black.FileMode(
line_length=args.line_length,
preview=args.preview,
string_normalization=not args.skip_string_normalization,
target_versions=set(args.target_versions),
)
retv = 0
for filename in args.filenames:
retv |= format_file(
filename,
black_mode,
skip_errors=args.skip_errors,
rst_literal_blocks=args.rst_literal_blocks,
)
return retv