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

Function format_code_blocks

scripts/utils/ruffen-docs.py:125–152  ·  view source on GitHub ↗

Formats all the given blocks with one run of ruff, as starting ruff takes far longer than formatting a block. Returns nothing if ruff can't format one of them. `format_code_block` then says which one.

(blocks: Sequence[str])

Source from the content-addressed store, hash-verified

123
124
125def format_code_blocks(blocks: Sequence[str]) -> dict[str, str]:
126 """Formats all the given blocks with one run of ruff, as starting ruff takes far longer than formatting a block.
127
128 Returns nothing if ruff can't format one of them. `format_code_block` then says which one.
129 """
130 # without a path, ruff formats the whole directory
131 if not blocks:
132 return {}
133
134 # in this directory, so that ruff finds the same config as for `script.py`
135 with tempfile.TemporaryDirectory(prefix=".ruffen-docs-", dir=os.curdir) as directory:
136 paths = [os.path.join(directory, f"{index}.py") for index in range(len(blocks))]
137 for index, block in enumerate(blocks):
138 with open(paths[index], "w", encoding="UTF-8") as f:
139 f.write(block)
140
141 result = subprocess.run(
142 [sys.executable, "-m", "ruff", "format", "--quiet", f"--line-length={DEFAULT_LINE_LENGTH}", *paths],
143 stderr=subprocess.DEVNULL,
144 )
145 if result.returncode != 0:
146 return {}
147
148 formatted: dict[str, str] = {}
149 for index, block in enumerate(blocks):
150 with open(paths[index], encoding="UTF-8") as f:
151 formatted[block] = f.read()
152 return formatted
153
154
155def format_file(

Callers 1

mainFunction · 0.85

Calls 3

writeMethod · 0.45
runMethod · 0.45
readMethod · 0.45

Tested by

no test coverage detected