From bb85c12fe92749dd3274700454d3868be64d6048 Mon Sep 17 00:00:00 2001 From: Marc Khouri Date: Tue, 11 Jun 2024 20:00:51 +0200 Subject: [PATCH] Don't merge crates when `imports_granularity="Module"` When merging imports using `imports_granularity="Module"`, individual crate imports should get their own `use` statement on a new line. ``` // Before this commit: use {library1, library2 as lib2, library3}; // After this commit: use library1; use library2 as lib2; use library3; ``` Fixes: #6191 --- src/imports.rs | 7 ++++++- tests/source/imports/imports_granularity_module.rs | 4 ++++ tests/source/issue-6191.rs | 4 ++++ tests/target/imports/imports_granularity_module.rs | 5 +++++ tests/target/issue-6191.rs | 5 +++++ 5 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 tests/source/issue-6191.rs create mode 100644 tests/target/issue-6191.rs diff --git a/src/imports.rs b/src/imports.rs index 05195553c08..c4107510dc3 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -662,7 +662,12 @@ impl UseTree { match shared_prefix { SharedPrefix::Crate => self.path[0] == other.path[0], SharedPrefix::Module => { - self.path[..self.path.len() - 1] == other.path[..other.path.len() - 1] + if self.path.len() == 1 && other.path.len() == 1 { + // When importing an entire crate, use the crate name for comparison. + self.path[0] == other.path[0] + } else { + self.path[..self.path.len() - 1] == other.path[..other.path.len() - 1] + } } SharedPrefix::One => true, } diff --git a/tests/source/imports/imports_granularity_module.rs b/tests/source/imports/imports_granularity_module.rs index c7f68cea6d4..2ef71005fb1 100644 --- a/tests/source/imports/imports_granularity_module.rs +++ b/tests/source/imports/imports_granularity_module.rs @@ -45,3 +45,7 @@ use b::v::{ }; use b::t::{/* Before b::t::self */ self}; use b::c; + +// Issue #6191: grouping of top-level modules +use library1; +use {library2 as lib2, library3}; diff --git a/tests/source/issue-6191.rs b/tests/source/issue-6191.rs new file mode 100644 index 00000000000..dca0a30fb62 --- /dev/null +++ b/tests/source/issue-6191.rs @@ -0,0 +1,4 @@ +// rustfmt-imports_granularity: Module + +use library1; +use {library2 as lib2, library3}; diff --git a/tests/target/imports/imports_granularity_module.rs b/tests/target/imports/imports_granularity_module.rs index 14f341016ff..2c85bce493a 100644 --- a/tests/target/imports/imports_granularity_module.rs +++ b/tests/target/imports/imports_granularity_module.rs @@ -53,3 +53,8 @@ use b::{ /* Before b::l group */ l::{self, m, n::o, p::*}, q, }; + +// Issue #6191: grouping of top-level modules +use library1; +use library2 as lib2; +use library3; diff --git a/tests/target/issue-6191.rs b/tests/target/issue-6191.rs new file mode 100644 index 00000000000..6bb56ed84b7 --- /dev/null +++ b/tests/target/issue-6191.rs @@ -0,0 +1,5 @@ +// rustfmt-imports_granularity: Module + +use library1; +use library2 as lib2; +use library3;