Skip to content

Commit 7ee11c7

Browse files
authored
Merge pull request #845 from ahoppen/infinite-searching
Fix infinite looping if swift-format is run in a directory that doesn't contain a `.swift-format` file
2 parents f170037 + 231be3c commit 7ee11c7

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

Sources/SwiftFormat/API/Configuration.swift

+13-6
Original file line numberDiff line numberDiff line change
@@ -425,17 +425,12 @@ public struct Configuration: Codable, Equatable {
425425
candidateDirectory.appendPathComponent("placeholder")
426426
}
427427
repeat {
428-
let previousDirectory = candidateDirectory
429428
candidateDirectory.deleteLastPathComponent()
430-
// if deleting a path component resulted in no change, terminate the loop
431-
if candidateDirectory == previousDirectory {
432-
break
433-
}
434429
let candidateFile = candidateDirectory.appendingPathComponent(".swift-format")
435430
if FileManager.default.isReadableFile(atPath: candidateFile.path) {
436431
return candidateFile
437432
}
438-
} while true
433+
} while !candidateDirectory.isRoot
439434

440435
return nil
441436
}
@@ -477,3 +472,15 @@ public struct NoAssignmentInExpressionsConfiguration: Codable, Equatable {
477472

478473
public init() {}
479474
}
475+
476+
fileprivate extension URL {
477+
var isRoot: Bool {
478+
#if os(Windows)
479+
// 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.
480+
// https://github.com/swiftlang/swift-format/issues/844
481+
return self.pathComponents.count == 1
482+
#else
483+
return self.path == "/"
484+
#endif
485+
}
486+
}

Tests/SwiftFormatTests/API/ConfigurationTests.swift

+9
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,13 @@ 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+
}
2029
}

0 commit comments

Comments
 (0)