Skip to content

Commit

Permalink
Fix issue where conditional compilation blocks would be sorted incorr…
Browse files Browse the repository at this point in the history
…ectly (#1714)
  • Loading branch information
calda authored and nicklockwood committed Jun 11, 2024
1 parent 89bfc69 commit 7db0538
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 5 deletions.
10 changes: 8 additions & 2 deletions Sources/FormattingHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2020,8 +2020,14 @@ extension Formatter {
return .beforeMarks
}

case .conditionalCompilation:
return .conditionalCompilation
case let .conditionalCompilation(_, body, _):
// Prefer treating conditional compliation blocks as having
// the property type of the first declaration in their body.
if let firstDeclarationInBlock = body.first {
return type(of: firstDeclarationInBlock, for: mode)
} else {
return .conditionalCompilation
}
}
}

Expand Down
65 changes: 62 additions & 3 deletions Tests/RulesTests+Organization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,12 @@ class OrganizationTests: RulesTests {
init() {}
var quuz = "quux"
#if DEBUG
struct Test {
let foo: Bar
}
#endif
}
"""

Expand All @@ -1296,8 +1302,6 @@ class OrganizationTests: RulesTests {
// MARK: Public
public var bar = "bar"
#if DEBUG
public struct DebugFoo {
Expand All @@ -1315,17 +1319,26 @@ class OrganizationTests: RulesTests {
private let other = "other"
#endif
public var bar = "bar"
// MARK: Internal
#if DEBUG
struct Test {
let foo: Bar
}
#endif
var baz = "baz"
var quuz = "quux"
}
"""

testFormatting(for: input, output, rule: FormatRules.organizeDeclarations,
options: FormatOptions(ifdefIndent: .noIndent),
exclude: ["blankLinesAtStartOfScope"])
exclude: ["blankLinesAtStartOfScope", "blankLinesAtEndOfScope"])
}

func testOrganizesTypeBelowSymbolImport() {
Expand Down Expand Up @@ -1785,6 +1798,52 @@ class OrganizationTests: RulesTests {
)
}

func testOrganizeConditionalInitDeclaration() {
let input = """
class Foo {
// MARK: Lifecycle
init() {}
#if DEBUG
init() {
print("Debug")
}
#endif
// MARK: Internal
func test() {}
}
"""

testFormatting(for: input, rule: FormatRules.organizeDeclarations, options: FormatOptions(ifdefIndent: .noIndent), exclude: ["blankLinesAtStartOfScope", "blankLinesAtEndOfScope"])
}

func testOrganizeConditionalPublicFunction() {
let input = """
class Foo {
// MARK: Lifecycle
init() {}
// MARK: Public
#if DEBUG
public func publicTest() {}
#endif
// MARK: Internal
func internalTest() {}
}
"""

testFormatting(for: input, rule: FormatRules.organizeDeclarations, options: FormatOptions(ifdefIndent: .noIndent), exclude: ["blankLinesAtStartOfScope", "blankLinesAtEndOfScope"])
}

// MARK: extensionAccessControl .onDeclarations

func testUpdatesVisibilityOfExtensionMembers() {
Expand Down

0 comments on commit 7db0538

Please sign in to comment.