From 0b5ab901ea587e736d463dee4981cd57d06d431e Mon Sep 17 00:00:00 2001 From: Cal Stephens Date: Wed, 24 Sep 2025 08:24:55 -0700 Subject: [PATCH] Fix issue where `.swift-version` file was ignored if not also using config file (#2230) --- Sources/SwiftFormat.swift | 13 +++++-- Tests/CommandLineTests.swift | 75 ++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/Sources/SwiftFormat.swift b/Sources/SwiftFormat.swift index 18412f0c..d65d5792 100644 --- a/Sources/SwiftFormat.swift +++ b/Sources/SwiftFormat.swift @@ -353,10 +353,15 @@ private func processDirectory(_ inputURL: URL, with options: inout Options, logg logger?("Ignoring swift-version file at \(versionFile.path)") } else if Version(rawValue: versionString) != nil { logger?("Reading swift-version file at \(versionFile.path) (version \(versionString))") - args = args.map { - var args = $0 - args["swift-version"] = versionString - return args + + if args.isEmpty { + args = [["swift-version": versionString]] + } else { + args = args.map { + var args = $0 + args["swift-version"] = versionString + return args + } } } else { // Don't treat as error, per: https://github.com/nicklockwood/SwiftFormat/issues/639 diff --git a/Tests/CommandLineTests.swift b/Tests/CommandLineTests.swift index 0fcc7b90..c696a7b0 100644 --- a/Tests/CommandLineTests.swift +++ b/Tests/CommandLineTests.swift @@ -1423,4 +1423,79 @@ class CommandLineTests: XCTestCase { try FileManager.default.removeItem(at: tempFile) } } + + func testSwiftVersionFileWithNoConfigFile() throws { + var errors = [String]() + + CLI.print = { message, type in + print(message) + if type == .error { + errors.append(message) + } + } + + try withTmpFiles([ + ".swift-version": """ + 6.1 + """, + "Test.swift": """ + func foo( + foo: Foo, + bar: Bar + ) {} + """, + ]) { url in + guard url.pathExtension == "swift" else { return } + _ = processArguments(["", url.path, "--rules", "trailingCommas"], in: "") + + XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), """ + func foo( + foo: Foo, + bar: Bar, + ) {} + """) + } + + XCTAssertEqual(errors, []) + } + + func testSwiftVersionFileWithConfigFile() throws { + var errors = [String]() + + CLI.print = { message, type in + print(message) + if type == .error { + errors.append(message) + } + } + + try withTmpFiles([ + ".swift-version": """ + 6.1 + """, + ".swiftformat": """ + --rules trailingCommas + --rules indent + --indent 2 + """, + "Test.swift": """ + func foo( + foo: Foo, + bar: Bar + ) {} + """, + ]) { url in + guard url.pathExtension == "swift" else { return } + _ = processArguments(["", url.path], in: "") + + XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), """ + func foo( + foo: Foo, + bar: Bar, + ) {} + """) + } + + XCTAssertEqual(errors, []) + } }