|
27 | 27 | # |
28 | 28 |
|
29 | 29 | # stdlib |
30 | | -import itertools |
31 | | -from collections.abc import Mapping |
32 | | -from typing import Optional |
| 30 | +from ast import Tuple |
33 | 31 |
|
34 | 32 | # 3rd party |
35 | | -from domdf_python_tools.paths import PathPlus |
36 | | -from domdf_python_tools.typing import PathLike |
37 | | -from domdf_python_tools.words import TAB |
38 | | -from formate.config import wants_filename, wants_global_config |
| 33 | +from tokenize_rt import src_to_tokens, tokens_to_src |
| 34 | + |
| 35 | +# this package |
| 36 | +from formate_trailing_commas._vendor.add_trailing_comma._ast_helpers import ast_parse |
| 37 | +from formate_trailing_commas._vendor.add_trailing_comma._data import FUNCS, visit |
| 38 | +from formate_trailing_commas._vendor.add_trailing_comma._main import _changing_list, _fix_src |
| 39 | +from formate_trailing_commas._vendor.add_trailing_comma._token_helpers import START_BRACES, find_simple, fix_brace |
39 | 40 |
|
40 | 41 | __author__: str = "Dominic Davis-Foster" |
41 | 42 | __copyright__: str = "2026 Dominic Davis-Foster" |
|
46 | 47 | __all__ = ["trailing_commas_hook"] |
47 | 48 |
|
48 | 49 |
|
49 | | -@wants_filename |
50 | | -@wants_global_config |
51 | | -def trailing_commas_hook( |
52 | | - source: str, |
53 | | - formate_filename: PathLike, |
54 | | - formate_global_config: Optional[Mapping] = None, |
55 | | - **kwargs, |
56 | | - ) -> str: |
| 50 | +def trailing_commas_hook(source: str, **kwargs) -> str: |
57 | 51 | r""" |
58 | 52 | Call `add-trailing-comma <https://github.com/asottile/add-trailing-comma>`_, using the given keyword arguments as its configuration. |
59 | 53 |
|
60 | 54 | :param source: The source to reformat. |
61 | | - :param formate_global_config: The global configuration dictionary. Optional. |
62 | 55 | :param \*\*kwargs: |
63 | 56 |
|
64 | 57 | :returns: The reformatted source. |
65 | 58 | """ |
66 | 59 |
|
67 | | - # TODO |
| 60 | + ast_obj = ast_parse(source) |
| 61 | + min_version: Tuple[int, int] = kwargs.get("min-version", (3, 6)) |
| 62 | + |
| 63 | + callbacks = visit(FUNCS, ast_obj, min_version) |
| 64 | + |
| 65 | + tokens = src_to_tokens(source) |
| 66 | + for i, token in _changing_list(tokens): |
| 67 | + # DEDENT is a zero length token |
| 68 | + if not token.src: |
| 69 | + continue |
| 70 | + |
| 71 | + for callback in callbacks.get(token.offset, ()): |
| 72 | + callback(i, tokens) |
| 73 | + |
| 74 | + if token.src in START_BRACES: |
| 75 | + fix_brace(tokens, find_simple(i, tokens), add_comma=False, remove_comma=False) |
| 76 | + |
| 77 | + return tokens_to_src(tokens) |
0 commit comments