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])
| 123 | |
| 124 | |
| 125 | def 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 | |
| 155 | def format_file( |