Skip to content

Commit 7f77c9a

Browse files
committed
Fix infinite looping if swift-format is run in a directory that doesn't contain a .swift-format file
swiftlang#802 this sort of infinite looping issue on Windows but introduced it on Unix platforms where `URL.deletingLastPathComponent` on `/` returns `/..`.
1 parent 58f07e3 commit 7f77c9a

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

Sources/SwiftFormat/API/Configuration.swift

+15-1
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ public struct Configuration: Codable, Equatable {
328328
if FileManager.default.isReadableFile(atPath: candidateFile.path) {
329329
return candidateFile
330330
}
331-
} while candidateDirectory.path != "/"
331+
} while !candidateDirectory.isRoot
332332

333333
return nil
334334
}
@@ -370,3 +370,17 @@ public struct NoAssignmentInExpressionsConfiguration: Codable, Equatable {
370370

371371
public init() {}
372372
}
373+
374+
fileprivate extension URL {
375+
var isRoot: Bool {
376+
#if os(Windows)
377+
// FIXME: We should call into Windows' native check to check if this path is a root once https://github.com/swiftlang/swift-foundation/issues/976 is fixed.
378+
// https://github.com/swiftlang/swift-format/issues/844
379+
return self.pathComponents.count == 1
380+
#else
381+
// On Linux, we may end up with an string for the path due to https://github.com/swiftlang/swift-foundation/issues/980
382+
// TODO: Remove the check for "" once https://github.com/swiftlang/swift-foundation/issues/980 is fixed.
383+
return self.path == "/" || self.path == ""
384+
#endif
385+
}
386+
}

Tests/SwiftFormatTests/API/ConfigurationTests.swift

+18
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,22 @@ final class ConfigurationTests: XCTestCase {
1717

1818
XCTAssertEqual(defaultInitConfig, emptyJSONConfig)
1919
}
20+
21+
func testMissingConfigurationFile() {
22+
#if os(Windows)
23+
let path = #"C:\test.swift"#
24+
#else
25+
let path = "/test.swift"
26+
#endif
27+
XCTAssertNil(Configuration.url(forConfigurationFileApplyingTo: URL(fileURLWithPath: path)))
28+
}
29+
30+
func testMissingConfigurationFileInSubdirectory() {
31+
#if os(Windows)
32+
let path = #"C:\whatever\test.swift"#
33+
#else
34+
let path = "/whatever/test.swift"
35+
#endif
36+
XCTAssertNil(Configuration.url(forConfigurationFileApplyingTo: URL(fileURLWithPath: path)))
37+
}
2038
}

0 commit comments

Comments
 (0)