MCPcopy
hub / github.com/openai/openai-python / format_str

Function format_str

scripts/utils/ruffen-docs.py:33–104  ·  view source on GitHub ↗
(
    src: str,
)

Source from the content-addressed store, hash-verified

31
32
33def format_str(
34 src: str,
35) -> tuple[str, Sequence[CodeBlockError]]:
36 errors: list[CodeBlockError] = []
37
38 @contextlib.contextmanager
39 def _collect_error(match: Match[str]) -> Generator[None, None, None]:
40 try:
41 yield
42 except Exception as e:
43 errors.append(CodeBlockError(match.start(), e))
44
45 def _md_match(match: Match[str]) -> str:
46 code = textwrap.dedent(match["code"])
47 with _collect_error(match):
48 code = format_code_block(code)
49 code = textwrap.indent(code, match["indent"])
50 return f"{match['before']}{code}{match['after']}"
51
52 def _pycon_match(match: Match[str]) -> str:
53 code = ""
54 fragment = cast(Optional[str], None)
55
56 def finish_fragment() -> None:
57 nonlocal code
58 nonlocal fragment
59
60 if fragment is not None:
61 with _collect_error(match):
62 fragment = format_code_block(fragment)
63 fragment_lines = fragment.splitlines()
64 code += f"{PYCON_PREFIX}{fragment_lines[0]}\n"
65 for line in fragment_lines[1:]:
66 # Skip blank lines to handle Black adding a blank above
67 # functions within blocks. A blank line would end the REPL
68 # continuation prompt.
69 #
70 # >>> if True:
71 # ... def f():
72 # ... pass
73 # ...
74 if line:
75 code += f"{PYCON_CONTINUATION_PREFIX} {line}\n"
76 if fragment_lines[-1].startswith(" "):
77 code += f"{PYCON_CONTINUATION_PREFIX}\n"
78 fragment = None
79
80 indentation = None
81 for line in match["code"].splitlines():
82 orig_line, line = line, line.lstrip()
83 if indentation is None and line:
84 indentation = len(orig_line) - len(line)
85 continuation_match = PYCON_CONTINUATION_RE.match(line)
86 if continuation_match and fragment is not None:
87 fragment += line[continuation_match.end() :] + "\n"
88 else:
89 finish_fragment()
90 if line.startswith(PYCON_PREFIX):

Callers 1

format_fileFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected