Skip to content

Commit 8eb143f

Browse files
authored
Do not merge top-level modules with imports_granularity Module
Fix 6191 Top level modules are now always formatted as their own `use` statement when setting `imports_granularity=Module` Signed-off-by: mwlon <m.w.loncaric@gmail.com>
1 parent c781b49 commit 8eb143f

File tree

4 files changed

+21
-3
lines changed

4 files changed

+21
-3
lines changed

Configurations.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2012,6 +2012,7 @@ use qux::{h, i};
20122012
#### `Module`:
20132013

20142014
Merge imports from the same module into a single `use` statement. Conversely, imports from different modules are split into separate statements.
2015+
Does not merge top-level modules.
20152016

20162017
```rust
20172018
use foo::b::{f, g};

src/imports.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ pub(crate) fn path_to_imported_ident(path: &ast::Path) -> symbol::Ident {
3333
path.segments.last().unwrap().ident
3434
}
3535

36+
/// Returns all but the last portion of the module path, except in the case of
37+
/// top-level modules (length 1), which remain unchanged. Used for Module-level
38+
/// imports_granularity.
39+
fn module_prefix(path: &[UseSegment]) -> &[UseSegment] {
40+
&path[..(path.len() - 1).max(1)]
41+
}
42+
3643
impl<'a> FmtVisitor<'a> {
3744
pub(crate) fn format_import(&mut self, item: &ast::Item, tree: &ast::UseTree) {
3845
let span = item.span();
@@ -683,9 +690,7 @@ impl UseTree {
683690
} else {
684691
match shared_prefix {
685692
SharedPrefix::Crate => self.path[0] == other.path[0],
686-
SharedPrefix::Module => {
687-
self.path[..self.path.len() - 1] == other.path[..other.path.len() - 1]
688-
}
693+
SharedPrefix::Module => module_prefix(&self.path) == module_prefix(&other.path),
689694
SharedPrefix::One => true,
690695
}
691696
}

tests/source/imports/imports_granularity_module.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,8 @@ use b::v::{
4545
};
4646
use b::t::{/* Before b::t::self */ self};
4747
use b::c;
48+
49+
use c;
50+
use d;
51+
52+
use {library1, library2 as lib2, library3};

tests/target/imports/imports_granularity_module.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,10 @@ use b::{
5353
/* Before b::l group */ l::{self, m, n::o, p::*},
5454
q,
5555
};
56+
57+
use c;
58+
use d;
59+
60+
use library1;
61+
use library2 as lib2;
62+
use library3;

0 commit comments

Comments
 (0)