Formats all the given blocks with one run of ruff, as starting ruff takes far longer than formatting a block. Exits if ruff can't format one of them. Ruff's error names the block by its index, as ` .py`.
(blocks: Sequence[str])
| 18 | |
| 19 | |
| 20 | def format_code_blocks(blocks: Sequence[str]) -> dict[str, str]: |
| 21 | """Formats all the given blocks with one run of ruff, as starting ruff takes far longer than formatting a block. |
| 22 | |
| 23 | Exits if ruff can't format one of them. Ruff's error names the block by its index, as `<index>.py`. |
| 24 | """ |
| 25 | # without a path, ruff formats the whole directory |
| 26 | if not blocks: |
| 27 | return {} |
| 28 | |
| 29 | # in this directory, so that ruff finds the project's config |
| 30 | with tempfile.TemporaryDirectory(prefix=".ruffen-docs-", dir=os.curdir) as directory: |
| 31 | paths = [os.path.join(directory, f"{index}.py") for index in range(len(blocks))] |
| 32 | for index, block in enumerate(blocks): |
| 33 | with open(paths[index], "w", encoding="UTF-8") as f: |
| 34 | f.write(block) |
| 35 | |
| 36 | result = subprocess.run( |
| 37 | [sys.executable, "-m", "ruff", "format", f"--line-length={DEFAULT_LINE_LENGTH}", *paths], |
| 38 | stdout=subprocess.DEVNULL, |
| 39 | ) |
| 40 | if result.returncode != 0: |
| 41 | raise SystemExit(result.returncode) |
| 42 | |
| 43 | formatted: dict[str, str] = {} |
| 44 | for index, block in enumerate(blocks): |
| 45 | with open(paths[index], encoding="UTF-8") as f: |
| 46 | formatted[block] = f.read() |
| 47 | return formatted |
| 48 | |
| 49 | |
| 50 | def main(argv: Sequence[str] | None = None) -> int: |