From 718c3a6e45bc38e8a78257505b5c30e170617745 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Mon, 23 Nov 2026 22:56:47 -0800 Subject: [PATCH 1/2] Omit help text on runtime errors in xcprojformatter --- Sources/Tests/FormatterErrorOutputTests.swift | 132 ++++++++++++++++++ Sources/Tool/main.swift | 19 ++- 2 files changed, 146 insertions(+), 5 deletions(-) create mode 100644 Sources/Tests/FormatterErrorOutputTests.swift diff --git a/Sources/Tests/FormatterErrorOutputTests.swift b/Sources/Tests/FormatterErrorOutputTests.swift new file mode 100644 index 0000000..d5b66d3 --- /dev/null +++ b/Sources/Tests/FormatterErrorOutputTests.swift @@ -0,0 +1,132 @@ +//===----------------------------------------------------------------------===// +// Copyright © 2026 Apple Inc. and the xcode-project-format project authors +// +// Licensed under Apache License v2.0 with Runtime Library Exception +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if os(macOS) || os(Linux) || os(Windows) + +import Foundation +import Testing + +struct FormatterErrorOutputTests { + private struct ProcessResult { + let terminationStatus: Int32 + let stdout: String + let stderr: String + } + + private func executableURL() throws -> URL { + #if os(Windows) + let binaryName = "xcprojformatter.exe" + #else + let binaryName = "xcprojformatter" + #endif + + var candidateDirectories: [URL] = [] + if let builtProductsDir = ProcessInfo.processInfo.environment["BUILT_PRODUCTS_DIR"] { + candidateDirectories.append(URL(fileURLWithPath: builtProductsDir)) + } + for bundle in Bundle.allBundles where bundle.bundleURL.pathExtension == "xctest" { + candidateDirectories.append(bundle.bundleURL.deletingLastPathComponent()) + } + for argument in CommandLine.arguments { + var url = URL(fileURLWithPath: argument) + while url.path != "/" && !url.lastPathComponent.hasSuffix(".xctest") { + url.deleteLastPathComponent() + } + if url.lastPathComponent.hasSuffix(".xctest") { + candidateDirectories.append(url.deletingLastPathComponent()) + } + } + + for directory in candidateDirectories { + let candidate = directory.appendingPathComponent(binaryName) + if FileManager.default.isExecutableFile(atPath: candidate.path) { + return candidate + } + } + + Issue.record("Could not locate \(binaryName) executable in \(candidateDirectories.map(\.path))") + throw CancellationError() + } + + private func runFormatter(_ arguments: [String], stdin: Data? = nil) throws -> ProcessResult { + let process = Process() + process.executableURL = try executableURL() + process.arguments = arguments + + let stdoutPipe = Pipe() + let stderrPipe = Pipe() + process.standardOutput = stdoutPipe + process.standardError = stderrPipe + + let stdinPipe = Pipe() + process.standardInput = stdinPipe + + try process.run() + if let stdin { + try stdinPipe.fileHandleForWriting.write(contentsOf: stdin) + } + try stdinPipe.fileHandleForWriting.close() + process.waitUntilExit() + + let stdout = String(decoding: stdoutPipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + let stderr = String(decoding: stderrPipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + return ProcessResult(terminationStatus: process.terminationStatus, stdout: stdout, stderr: stderr) + } + + private func withTemporaryDirectory(_ body: (URL) throws -> ()) throws { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("FormatterErrorOutputTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + try body(dir) + } + + @Test func decodeFailurePrintsDiagnosticWithoutHelpText() throws { + let projectMissingTargetName = Data(#"{"default-configuration":"Debug","files":[],"localizations":{"development":"en"},"targets":[{}]}"#.utf8) + + try withTemporaryDirectory { dir in + let projectFile = dir.appendingPathComponent("project.xcproj") + try projectMissingTargetName.write(to: projectFile) + + let result = try runFormatter(["--input", projectFile.path]) + #expect(result.terminationStatus == 1) + #expect(result.stdout.isEmpty) + #expect(result.stderr.contains("Missing required value for key “name” at “/targets[0]”")) + #expect(!result.stderr.contains("Usage:")) + #expect(!result.stderr.contains("----------------------------")) + } + } + + @Test func malformedJSONPrintsDiagnosticWithoutHelpText() throws { + let result = try runFormatter([], stdin: Data("{invalid".utf8)) + #expect(result.terminationStatus == 1) + #expect(result.stdout.isEmpty) + #expect(!result.stderr.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + #expect(!result.stderr.contains("Usage:")) + } + + @Test func unreadableInputPrintsDiagnosticWithoutHelpText() throws { + try withTemporaryDirectory { dir in + let missingFile = dir.appendingPathComponent("missing.xcproj") + let result = try runFormatter(["--input", missingFile.path]) + #expect(result.terminationStatus == 1) + #expect(result.stdout.isEmpty) + #expect(result.stderr.contains("Could not open")) + #expect(!result.stderr.contains("Usage:")) + } + } + + @Test func invalidArgumentsStillPrintHelpText() throws { + let result = try runFormatter(["--unknown-flag"]) + #expect(result.terminationStatus == 1) + #expect(result.stdout.isEmpty) + #expect(result.stderr.contains("Unexpected argument")) + #expect(result.stderr.contains("Usage:")) + } +} + +#endif diff --git a/Sources/Tool/main.swift b/Sources/Tool/main.swift index a3c3238..b257254 100644 --- a/Sources/Tool/main.swift +++ b/Sources/Tool/main.swift @@ -12,8 +12,18 @@ import Foundation platform_exit(main()) func main() -> Int32 { + let arguments: Arguments + do { + arguments = try Arguments(commandLine: CommandLine.arguments) + } catch { + let error = error as NSError + let message = error.localizedDescriptionCombinedWithRecoverySuggestionIfPresent + "\n\n----------------------------\n\n" + try? FileHandle.standardError.write(contentsOf: message.utf8.asData) + try? printHelp(to: .standardError) + return 1 + } + do { - let arguments = try Arguments(commandLine: CommandLine.arguments) if arguments.help { try printHelp(to: .standardOutput) } else { @@ -24,10 +34,9 @@ func main() -> Int32 { return 0 } catch { let error = error as NSError - let message = error.localizedDescriptionCombinedWithRecoverySuggestionIfPresent + "\n\n----------------------------\n\n" - try! FileHandle.standardError.write(contentsOf: message.utf8.asData) - try! printHelp(to: .standardError) - return -1 + let message = error.localizedDescriptionCombinedWithRecoverySuggestionIfPresent + "\n" + try? FileHandle.standardError.write(contentsOf: message.utf8.asData) + return 1 } } From c2e4d5900f31ef14708b12637bf629e362e78377 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Tue, 24 Nov 2026 17:37:05 -0800 Subject: [PATCH 2/2] Share formatter error reporting --- Sources/Tool/main.swift | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Sources/Tool/main.swift b/Sources/Tool/main.swift index b257254..534d61e 100644 --- a/Sources/Tool/main.swift +++ b/Sources/Tool/main.swift @@ -16,9 +16,7 @@ func main() -> Int32 { do { arguments = try Arguments(commandLine: CommandLine.arguments) } catch { - let error = error as NSError - let message = error.localizedDescriptionCombinedWithRecoverySuggestionIfPresent + "\n\n----------------------------\n\n" - try? FileHandle.standardError.write(contentsOf: message.utf8.asData) + printError(error, terminator: "\n\n----------------------------\n\n") try? printHelp(to: .standardError) return 1 } @@ -33,9 +31,7 @@ func main() -> Int32 { } return 0 } catch { - let error = error as NSError - let message = error.localizedDescriptionCombinedWithRecoverySuggestionIfPresent + "\n" - try? FileHandle.standardError.write(contentsOf: message.utf8.asData) + printError(error) return 1 } } @@ -75,6 +71,11 @@ func readInputData(from inputPath: String?) throws -> Data { } } +private func printError(_ error: any Error, terminator: String = "\n") { + let message = (error as NSError).localizedDescriptionCombinedWithRecoverySuggestionIfPresent + terminator + try? FileHandle.standardError.write(contentsOf: message.utf8.asData) +} + func printHelp(to handle: FileHandle) throws { try handle.write(contentsOf: helpText().utf8.asData) }