[ruff] improve handling of intermixed comments inside from-imports (#20561)

Resolves a crash when attempting to format code like:

```
from x import (a as # whatever
b)
```

Reworks the way comments are associated with nodes when parsing modules,
so that all possible comment positions can be retained and reproduced during
formatting.

Overall follows Black's formatting style for multi-line import statements.

Fixes issue #19138
This commit is contained in:
Amethyst Reese 2025-10-07 08:14:09 -07:00 committed by GitHub
parent 23ebfe7777
commit 8fb29eafb8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 269 additions and 6 deletions

View file

@ -0,0 +1,47 @@
# ensure trailing comments are preserved
import x # comment
from x import a # comment
from x import a, b # comment
from x import a as b # comment
from x import a as b, b as c # comment
from x import (
a, # comment
)
from x import (
a, # comment
b,
)
# ensure comma is added
from x import (
a # comment
)
# follow black style by merging cases without own-line comments
from x import (
a # alpha
, # beta
b,
)
# ensure intermixed comments are all preserved
from x import ( # one
# two
a # three
# four
, # five
# six
) # seven
from x import ( # alpha
# bravo
a # charlie
# delta
as # echo
# foxtrot
b # golf
# hotel
, # india
# juliet
) # kilo

View file

@ -0,0 +1,46 @@
# ensure trailing comments are preserved
import x # comment
from x import a # comment
from x import a, b # comment
from x import a as b # comment
from x import a as b, b as c # comment
from x import (
a, # comment
)
from x import (
a, # comment
b,
)
# ensure comma is added
from x import (
a, # comment
)
# follow black style by merging cases without own-line comments
from x import (
a, # alpha # beta
b,
)
# ensure intermixed comments are all preserved
from x import ( # one
# two
a # three
# four
, # five
# six
) # seven
from x import ( # alpha
# bravo
a # charlie
# delta
as # echo
# foxtrot
b # golf
# hotel
, # india
# juliet
) # kilo