1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use ruff_formatter::write;
use ruff_python_ast::Alias;
use crate::comments::trailing_comments;
use crate::other::identifier::DotDelimitedIdentifier;
use crate::prelude::*;
#[derive(Default)]
pub struct FormatAlias;
impl FormatNodeRule<Alias> for FormatAlias {
fn fmt_fields(&self, item: &Alias, f: &mut PyFormatter) -> FormatResult<()> {
let Alias {
range: _,
node_index: _,
name,
asname,
} = item;
write!(f, [DotDelimitedIdentifier::new(name)])?;
let comments = f.context().comments().clone();
// ```python
// from foo import (
// bar # comment
// as baz,
// )
// ```
if comments.has_trailing(name) {
write!(
f,
[
trailing_comments(comments.trailing(name)),
hard_line_break()
]
)?;
} else if asname.is_some() {
write!(f, [space()])?;
}
if let Some(asname) = asname {
write!(f, [token("as")])?;
// ```python
// from foo import (
// bar as # comment
// baz,
// )
// ```
if comments.has_leading(asname) {
write!(
f,
[
trailing_comments(comments.leading(asname)),
hard_line_break()
]
)?;
} else {
write!(f, [space()])?;
}
write!(f, [asname.format()])?;
}
// Dangling comment between alias and comma on a following line
// ```python
// from foo import (
// bar # comment
// ,
// )
// ```
let dangling = comments.dangling(item);
if !dangling.is_empty() {
write!(f, [trailing_comments(comments.dangling(item))])?;
// Black will move the comma and merge comments if there is no own-line comment between
// the alias and the comma.
//
// Eg:
// ```python
// from foo import (
// bar # one
// , # two
// )
// ```
//
// Will become:
// ```python
// from foo import (
// bar, # one # two)
// ```
//
// Only force a hard line break if an own-line dangling comment is present.
if dangling
.iter()
.any(|comment| comment.line_position().is_own_line())
{
write!(f, [hard_line_break()])?;
}
}
Ok(())
}
}