[ruff] fix crash with dangling comments in importfrom alias

Resolves the crash when attempting to format code like:

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

And chooses to format it as:
```
from x import (
    a as b,  # whatever
)
```

Fixes issue #19138
This commit is contained in:
Amethyst Reese 2025-09-24 13:48:05 -07:00
parent 09f570af92
commit 63b3f7adae

View file

@ -1,6 +1,7 @@
use ruff_formatter::write;
use ruff_python_ast::Alias;
use crate::comments::dangling_comments;
use crate::other::identifier::DotDelimitedIdentifier;
use crate::prelude::*;
@ -17,7 +18,18 @@ impl FormatNodeRule<Alias> for FormatAlias {
} = item;
DotDelimitedIdentifier::new(name).fmt(f)?;
if let Some(asname) = asname {
write!(f, [space(), token("as"), space(), asname.format()])?;
let comments = f.context().comments().clone();
let dangling = comments.dangling(item);
write!(
f,
[
space(),
token("as"),
space(),
asname.format(),
line_suffix(&dangling_comments(dangling), 0),
]
)?;
}
Ok(())
}