MCPcopy Create free account
hub / github.com/anthropics/anthropic-sdk-python / format_str

Function format_str

scripts/utils/ruffen-docs.py:35–107  ·  view source on GitHub ↗
(
    src: str,
    format_code_block: Callable[[str], str],
)

Source from the content-addressed store, hash-verified

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

Callers 2

format_fileFunction · 0.85
mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected