Skip to content

Commit 337c19b

Browse files
committed
Sort the first group in StdExternalCrate import grouping by their subset relation
`core` is a subset of `alloc`, and `alloc` is a subset of `std`. This changes the ordering logic so that imports from `core` are placed first, imports from `alloc` second, and imports from `std` last.
1 parent fd0ea74 commit 337c19b

File tree

4 files changed

+28
-4
lines changed

4 files changed

+28
-4
lines changed

Configurations.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2379,8 +2379,8 @@ Discard existing import groups, and create three groups for:
23792379
3. `self`, `super` and `crate` imports.
23802380

23812381
```rust
2382-
use alloc::alloc::Layout;
23832382
use core::f32;
2383+
use alloc::alloc::Layout;
23842384
use std::sync::Arc;
23852385

23862386
use broker::database::PooledConnection;

src/reorder.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,31 @@ fn rewrite_reorderable_or_regroupable_items(
137137
};
138138

139139
if context.config.reorder_imports() {
140-
regrouped_items.iter_mut().for_each(|items| items.sort())
140+
if context.config.group_imports() == GroupImportsTactic::StdExternalCrate {
141+
// Sort the first group by core -> alloc -> std.
142+
regrouped_items[0].sort_by(|a, b| {
143+
if let (UseSegmentKind::Ident(a_id, _), UseSegmentKind::Ident(b_id, _)) =
144+
(&a.path[0].kind, &b.path[0].kind)
145+
{
146+
match (a_id.as_ref(), b_id.as_ref()) {
147+
("core", "alloc") | ("core", "std") | ("alloc", "std") => {
148+
return Ordering::Less;
149+
}
150+
("alloc", "core") | ("std", "core") | ("std", "alloc") => {
151+
return Ordering::Greater;
152+
}
153+
_ => {}
154+
}
155+
}
156+
a.cmp(b)
157+
});
158+
regrouped_items
159+
.iter_mut()
160+
.skip(1)
161+
.for_each(|items| items.sort());
162+
} else {
163+
regrouped_items.iter_mut().for_each(|items| items.sort());
164+
}
141165
}
142166

143167
// 4 = "use ", 1 = ";"

tests/target/configs/group_imports/StdExternalCrate-merge_imports.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// rustfmt-group_imports: StdExternalCrate
22
// rustfmt-imports_granularity: Crate
3-
use alloc::{alloc::Layout, vec::Vec};
43
use core::f32;
4+
use alloc::{alloc::Layout, vec::Vec};
55
use std::sync::Arc;
66

77
use broker::database::PooledConnection;

tests/target/configs/group_imports/StdExternalCrate.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// rustfmt-group_imports: StdExternalCrate
2-
use alloc::alloc::Layout;
32
use core::f32;
3+
use alloc::alloc::Layout;
44
use std::sync::Arc;
55

66
use broker::database::PooledConnection;

0 commit comments

Comments
 (0)