From 3f4f61ba85583346b1d61b1a6e7219dd0def5f84 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 17 Mar 2026 07:14:01 -0700 Subject: [PATCH] Update `sortImports` to support `--import-grouping length,alpha` (#2463) Co-authored-by: calda <1811727+calda@users.noreply.github.com> --- Sources/Rules/SortImports.swift | 8 +++++++- Tests/Rules/SortImportsTests.swift | 32 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/Sources/Rules/SortImports.swift b/Sources/Rules/SortImports.swift index 44b70ef7..6f15025f 100644 --- a/Sources/Rules/SortImports.swift +++ b/Sources/Rules/SortImports.swift @@ -84,7 +84,13 @@ extension Formatter { } if grouping.contains(.length) { - return lhs.module.count < rhs.module.count + if lhs.module.count != rhs.module.count { + return lhs.module.count < rhs.module.count + } + if grouping.contains(.alpha) { + return lhs < rhs + } + return false } // Default to alphabetical return lhs < rhs diff --git a/Tests/Rules/SortImportsTests.swift b/Tests/Rules/SortImportsTests.swift index e7cdc68b..e1a4c967 100644 --- a/Tests/Rules/SortImportsTests.swift +++ b/Tests/Rules/SortImportsTests.swift @@ -596,4 +596,36 @@ final class SortImportsTests: XCTestCase { let options = FormatOptions(importGrouping: [.length, .testableLast]) testFormatting(for: input, output, rule: .sortImports, options: options) } + + func testLengthThenAlphaSortImports() { + let input = """ + import Module + import Foo + import Bar + import Ab + """ + let output = """ + import Ab + import Bar + import Foo + import Module + """ + let options = FormatOptions(importGrouping: [.length, .alpha]) + testFormatting(for: input, output, rule: .sortImports, options: options) + } + + func testLengthThenAlphaSortImportsWithSameLength() { + let input = """ + import Zed + import Foo + import Bar + """ + let output = """ + import Bar + import Foo + import Zed + """ + let options = FormatOptions(importGrouping: [.length, .alpha]) + testFormatting(for: input, output, rule: .sortImports, options: options) + } }