|
3 | 3 | import contextlib |
4 | 4 | import re |
5 | 5 | import textwrap |
| 6 | +from abc import ABC, abstractmethod |
6 | 7 | from bisect import bisect |
7 | 8 | from collections.abc import Generator, Sequence |
8 | 9 | from pathlib import Path |
|
32 | 33 | TRAILING_NL_RE, |
33 | 34 | ) |
34 | 35 |
|
| 36 | +__all__ = ("BlackFormatter",) |
35 | 37 |
|
36 | | -class BlackFormatter: |
37 | | - def __init__( |
38 | | - self, |
39 | | - # FIXME: |
40 | | - # The original default value fails with |
41 | | - # > TypeError: set object expected; got dataclasses.Field |
42 | | - target_versions: set[TargetVersion] | None = None, |
43 | | - line_length: int = DEFAULT_LINE_LENGTH, |
44 | | - string_normalization: bool = True, |
45 | | - is_pyi: bool = False, |
46 | | - preview: bool = False, |
47 | | - ) -> None: |
48 | | - if target_versions is None: |
49 | | - target_versions = set() |
50 | 38 |
|
| 39 | +class BaseProcessor(ABC): |
| 40 | + def __init__(self) -> None: |
51 | 41 | self.errors: list[CodeBlockError] = [] |
52 | 42 | self.off_ranges: list[tuple[int, int]] = [] |
53 | 43 |
|
54 | | - self.mode: Mode = Mode( |
55 | | - target_versions=target_versions, |
56 | | - line_length=line_length, |
57 | | - string_normalization=string_normalization, |
58 | | - is_pyi=is_pyi, |
59 | | - preview=preview, |
60 | | - ) |
61 | | - |
| 44 | + @abstractmethod |
62 | 45 | def process_code_block(self, code_block: str) -> str: |
63 | | - return black.format_str(code_block, mode=self.mode) |
| 46 | + pass # pragma: no cover |
64 | 47 |
|
65 | 48 | def _within_off_range(self, code_range: tuple[int, int]) -> bool: |
66 | 49 | index = bisect(self.off_ranges, code_range) |
@@ -312,3 +295,32 @@ def format_file( |
312 | 295 | f.write(new_contents) |
313 | 296 |
|
314 | 297 | return 1 |
| 298 | + |
| 299 | + |
| 300 | +class BlackFormatter(BaseProcessor): |
| 301 | + def __init__( |
| 302 | + self, |
| 303 | + # FIXME: |
| 304 | + # The original default value fails with |
| 305 | + # > TypeError: set object expected; got dataclasses.Field |
| 306 | + target_versions: set[TargetVersion] | None = None, |
| 307 | + line_length: int = DEFAULT_LINE_LENGTH, |
| 308 | + string_normalization: bool = True, |
| 309 | + is_pyi: bool = False, |
| 310 | + preview: bool = False, |
| 311 | + ) -> None: |
| 312 | + if target_versions is None: |
| 313 | + target_versions = set() |
| 314 | + |
| 315 | + self.mode: Mode = Mode( |
| 316 | + target_versions=target_versions, |
| 317 | + line_length=line_length, |
| 318 | + string_normalization=string_normalization, |
| 319 | + is_pyi=is_pyi, |
| 320 | + preview=preview, |
| 321 | + ) |
| 322 | + |
| 323 | + super().__init__() |
| 324 | + |
| 325 | + def process_code_block(self, code_block: str) -> str: |
| 326 | + return black.format_str(code_block, mode=self.mode) |
0 commit comments