jsh9 / cercis

https://pypi.org/project/cercis/
MIT License
14 stars 1 forks source link

Handle comment as last leaf item when collapsing brackets #36

Open char101 opened 9 months ago

char101 commented 9 months ago

Hi,

Having a comment as a last item break bracket collapsing, e.g.

input:

call({
    'a': 1,
})

call({
    'a': 1,
    # 'c': 2,
})

output:

call({
    'a': 1,
})

call(
    {
        'a': 1,
        # 'b': 2,
    }
)

A comment as the last leaf item is practically the same as having an ending comma.

This patch seems to fix it

diff --git a/src/cercis/utils_linegen.py b/src/cercis/utils_linegen.py
index e93c279..d3e0b23 100644
--- a/src/cercis/utils_linegen.py
+++ b/src/cercis/utils_linegen.py
@@ -68,7 +68,7 @@ def perform_collapse_nested_brackets(
                 mode=mode,
             )
             if inner_body.should_split_rhs or (
-                inner_body_leaves and inner_body_leaves[-1].type == token.COMMA
+                inner_body_leaves and inner_body_leaves[-1].type in (token.COMMA, 153)
             ):
                 # Only when the inner body itself will be split or ends with a comma,
                 # should we prefer not break immediately nested brackets.

The token type is 153. I couldn't find the name for the token in token.py.

jsh9 commented 8 months ago

Hi @char101 , thanks for offering a solution! And sorry for the delayed reply -- I've been very busy with other things these past few weeks.

I'll make a code change by the end of this week then.

char101 commented 8 months ago

This seems to be implemented in black now.