openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.4.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

bin/blacken-docs.py

251lines · modeblame

08b8179aDavid Schnurr2 years ago1# fork of https://github.com/asottile/blacken-docs implementing https://github.com/asottile/blacken-docs/issues/170
2from __future__ import annotations
3
4import re
5import argparse
6import textwrap
7import contextlib
8from typing import Match, Optional, Sequence, Generator, NamedTuple, cast
9
10import black
11from black.mode import TargetVersion
12from black.const import DEFAULT_LINE_LENGTH
13
14MD_RE = re.compile(
15r"(?P<before>^(?P<indent> *)```\s*python\n)" r"(?P<code>.*?)" r"(?P<after>^(?P=indent)```\s*$)",
16re.DOTALL | re.MULTILINE,
17)
18MD_PYCON_RE = re.compile(
19r"(?P<before>^(?P<indent> *)```\s*pycon\n)" r"(?P<code>.*?)" r"(?P<after>^(?P=indent)```.*$)",
20re.DOTALL | re.MULTILINE,
21)
22RST_PY_LANGS = frozenset(("python", "py", "sage", "python3", "py3", "numpy"))
23BLOCK_TYPES = "(code|code-block|sourcecode|ipython)"
24DOCTEST_TYPES = "(testsetup|testcleanup|testcode)"
25RST_RE = re.compile(
26rf"(?P<before>"
27rf"^(?P<indent> *)\.\. ("
28rf"jupyter-execute::|"
29rf"{BLOCK_TYPES}:: (?P<lang>\w+)|"
30rf"{DOCTEST_TYPES}::.*"
31rf")\n"
32rf"((?P=indent) +:.*\n)*"
33rf"\n*"
34rf")"
35rf"(?P<code>(^((?P=indent) +.*)?\n)+)",
36re.MULTILINE,
37)
38RST_PYCON_RE = re.compile(
39r"(?P<before>"
40r"(?P<indent> *)\.\. ((code|code-block):: pycon|doctest::.*)\n"
41r"((?P=indent) +:.*\n)*"
42r"\n*"
43r")"
44r"(?P<code>(^((?P=indent) +.*)?(\n|$))+)",
45re.MULTILINE,
46)
47PYCON_PREFIX = ">>> "
48PYCON_CONTINUATION_PREFIX = "..."
49PYCON_CONTINUATION_RE = re.compile(
50rf"^{re.escape(PYCON_CONTINUATION_PREFIX)}( |$)",
51)
52LATEX_RE = re.compile(
53r"(?P<before>^(?P<indent> *)\\begin{minted}{python}\n)"
54r"(?P<code>.*?)"
55r"(?P<after>^(?P=indent)\\end{minted}\s*$)",
56re.DOTALL | re.MULTILINE,
57)
58LATEX_PYCON_RE = re.compile(
59r"(?P<before>^(?P<indent> *)\\begin{minted}{pycon}\n)" r"(?P<code>.*?)" r"(?P<after>^(?P=indent)\\end{minted}\s*$)",
60re.DOTALL | re.MULTILINE,
61)
62PYTHONTEX_LANG = r"(?P<lang>pyblock|pycode|pyconsole|pyverbatim)"
63PYTHONTEX_RE = re.compile(
64rf"(?P<before>^(?P<indent> *)\\begin{{{PYTHONTEX_LANG}}}\n)"
65rf"(?P<code>.*?)"
66rf"(?P<after>^(?P=indent)\\end{{(?P=lang)}}\s*$)",
67re.DOTALL | re.MULTILINE,
68)
69INDENT_RE = re.compile("^ +(?=[^ ])", re.MULTILINE)
70TRAILING_NL_RE = re.compile(r"\n+\Z", re.MULTILINE)
71
72
73class CodeBlockError(NamedTuple):
74offset: int
75exc: Exception
76
77
78def format_str(
79src: str,
80black_mode: black.FileMode,
81) -> tuple[str, Sequence[CodeBlockError]]:
82errors: list[CodeBlockError] = []
83
84@contextlib.contextmanager
85def _collect_error(match: Match[str]) -> Generator[None, None, None]:
86try:
87yield
88except Exception as e:
89errors.append(CodeBlockError(match.start(), e))
90
91def _md_match(match: Match[str]) -> str:
92code = textwrap.dedent(match["code"])
93with _collect_error(match):
94code = black.format_str(code, mode=black_mode)
95code = textwrap.indent(code, match["indent"])
96return f'{match["before"]}{code}{match["after"]}'
97
98def _rst_match(match: Match[str]) -> str:
99lang = match["lang"]
100if lang is not None and lang not in RST_PY_LANGS:
101return match[0]
102min_indent = min(INDENT_RE.findall(match["code"]))
103trailing_ws_match = TRAILING_NL_RE.search(match["code"])
104assert trailing_ws_match
105trailing_ws = trailing_ws_match.group()
106code = textwrap.dedent(match["code"])
107with _collect_error(match):
108code = black.format_str(code, mode=black_mode)
109code = textwrap.indent(code, min_indent)
110return f'{match["before"]}{code.rstrip()}{trailing_ws}'
111
112def _pycon_match(match: Match[str]) -> str:
113code = ""
114fragment = cast(Optional[str], None)
115
116def finish_fragment() -> None:
117nonlocal code
118nonlocal fragment
119
120if fragment is not None:
121with _collect_error(match):
122fragment = black.format_str(fragment, mode=black_mode)
123fragment_lines = fragment.splitlines()
124code += f"{PYCON_PREFIX}{fragment_lines[0]}\n"
125for line in fragment_lines[1:]:
126# Skip blank lines to handle Black adding a blank above
127# functions within blocks. A blank line would end the REPL
128# continuation prompt.
129#
130# >>> if True:
131# ... def f():
132# ... pass
133# ...
134if line:
135code += f"{PYCON_CONTINUATION_PREFIX} {line}\n"
136if fragment_lines[-1].startswith(" "):
137code += f"{PYCON_CONTINUATION_PREFIX}\n"
138fragment = None
139
140indentation = None
141for line in match["code"].splitlines():
142orig_line, line = line, line.lstrip()
143if indentation is None and line:
144indentation = len(orig_line) - len(line)
145continuation_match = PYCON_CONTINUATION_RE.match(line)
146if continuation_match and fragment is not None:
147fragment += line[continuation_match.end() :] + "\n"
148else:
149finish_fragment()
150if line.startswith(PYCON_PREFIX):
151fragment = line[len(PYCON_PREFIX) :] + "\n"
152else:
153code += orig_line[indentation:] + "\n"
154finish_fragment()
155return code
156
157def _md_pycon_match(match: Match[str]) -> str:
158code = _pycon_match(match)
159code = textwrap.indent(code, match["indent"])
160return f'{match["before"]}{code}{match["after"]}'
161
162def _rst_pycon_match(match: Match[str]) -> str:
163code = _pycon_match(match)
164min_indent = min(INDENT_RE.findall(match["code"]))
165code = textwrap.indent(code, min_indent)
166return f'{match["before"]}{code}'
167
168def _latex_match(match: Match[str]) -> str:
169code = textwrap.dedent(match["code"])
170with _collect_error(match):
171code = black.format_str(code, mode=black_mode)
172code = textwrap.indent(code, match["indent"])
173return f'{match["before"]}{code}{match["after"]}'
174
175def _latex_pycon_match(match: Match[str]) -> str:
176code = _pycon_match(match)
177code = textwrap.indent(code, match["indent"])
178return f'{match["before"]}{code}{match["after"]}'
179
180src = MD_RE.sub(_md_match, src)
181src = MD_PYCON_RE.sub(_md_pycon_match, src)
182src = RST_RE.sub(_rst_match, src)
183src = RST_PYCON_RE.sub(_rst_pycon_match, src)
184src = LATEX_RE.sub(_latex_match, src)
185src = LATEX_PYCON_RE.sub(_latex_pycon_match, src)
186src = PYTHONTEX_RE.sub(_latex_match, src)
187return src, errors
188
189
190def format_file(
191filename: str,
192black_mode: black.FileMode,
193skip_errors: bool,
194) -> int:
195with open(filename, encoding="UTF-8") as f:
196contents = f.read()
197new_contents, errors = format_str(contents, black_mode)
198for error in errors:
199lineno = contents[: error.offset].count("\n") + 1
200print(f"{filename}:{lineno}: code block parse error {error.exc}")
201if errors and not skip_errors:
202return 1
203if contents != new_contents:
204print(f"{filename}: Rewriting...")
205with open(filename, "w", encoding="UTF-8") as f:
206f.write(new_contents)
207return 0
208else:
209return 0
210
211
212def main(argv: Sequence[str] | None = None) -> int:
213parser = argparse.ArgumentParser()
214parser.add_argument(
215"-l",
216"--line-length",
217type=int,
218default=DEFAULT_LINE_LENGTH,
219)
220parser.add_argument(
221"-t",
222"--target-version",
223action="append",
224type=lambda v: TargetVersion[v.upper()],
225default=[],
226help=f"choices: {[v.name.lower() for v in TargetVersion]}",
227dest="target_versions",
228)
229parser.add_argument(
230"-S",
231"--skip-string-normalization",
232action="store_true",
233)
234parser.add_argument("-E", "--skip-errors", action="store_true")
235parser.add_argument("filenames", nargs="*")
236args = parser.parse_args(argv)
237
238black_mode = black.FileMode(
239target_versions=set(args.target_versions),
240line_length=args.line_length,
241string_normalization=not args.skip_string_normalization,
242)
243
244retv = 0
245for filename in args.filenames:
246retv |= format_file(filename, black_mode, skip_errors=args.skip_errors)
247return retv
248
249
250if __name__ == "__main__":
251raise SystemExit(main())