import Darwin import Foundation public struct ProcessResult: Sendable, Equatable { public var exitCode: Int32 public var stdout: String public var stderr: String public init(exitCode: Int32, stdout: String, stderr: String) { self.exitCode = exitCode self.stdout = stdout self.stderr = stderr } public var succeeded: Bool { exitCode == 0 } } public enum ProcessRunnerError: Error, Equatable { case executableNotFound(String) case launchFailed(String) } /// Runs a command to completion. Services depend on this protocol so tests can script the output. public protocol ProcessRunning: Sendable { /// Runs `executable` (a name looked up on the search path, or a path) and collects its output. /// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours. func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult /// Like `run`, but hands each output line to `onLine` as it arrives (`isError` for stderr). func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?, onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult } extension ProcessRunning { /// Runs to completion, then emits the stdout lines and after them the stderr lines. public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?, onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult { let result = try await run(executable, arguments: arguments, in: directory, environment: environment) for line in OutputLines.split(result.stdout) { onLine(line, false) } for line in OutputLines.split(result.stderr) { onLine(line, true) } return result } public func run(_ executable: String, _ arguments: [String], in directory: URL? = nil) async throws -> ProcessResult { try await run(executable, arguments: arguments, in: directory, environment: nil) } } public struct ProcessRunner: ProcessRunning { public let locator: ExecutableLocator public init(locator: ExecutableLocator = .standard) { self.locator = locator } public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult { try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: nil) } public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?, onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult { try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: onLine) } private func launch(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?, onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult { guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) } let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, onLine: onLine) return try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in job.start(continuation) } } onCancel: { job.cancel() } } } /// Splits output into lines on "\n" and "\r", so a progress update ends a line too; empty lines are dropped. enum OutputLines { static func split(_ text: String) -> [String] { text.split(omittingEmptySubsequences: true) { $0 == "\n" || $0 == "\r" || $0 == "\r\n" }.map(String.init) } } /// Collects one pipe's bytes and, when streaming, cuts them into lines as they arrive. private final class LineBuffer { private(set) var all = Data() private var pending = Data() /// Appends a chunk and returns the lines it completed. func append(_ chunk: Data) -> [String] { all.append(chunk) pending.append(chunk) var lines: [String] = [] while let end = pending.firstIndex(where: { $0 == 0x0A || $0 == 0x0D }) { let line = pending[pending.startIndex.. String? { defer { pending.removeAll() } return pending.isEmpty ? nil : String(decoding: pending, as: UTF8.self) } } /// One child process. Both pipes are drained on their own threads, because a child that /// fills one pipe while we wait on the other would deadlock. /// /// A cancel resumes at once and signals the child and every descendant: a grandchild such as /// `ssh` can hold a pipe open long after the child is gone, so waiting for EOF could hang. private final class Job: @unchecked Sendable { private let process = Process() private let lock = NSLock() private var cancelled = false private var continuation: CheckedContinuation? private let onLine: (@Sendable (String, Bool) -> Void)? /// Keeps `onLine` to one call at a time, though both pipes feed it. private let emitLock = NSLock() init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?, onLine: (@Sendable (String, Bool) -> Void)?) { self.onLine = onLine process.executableURL = url process.arguments = arguments if let directory { process.currentDirectoryURL = directory } if let environment { process.environment = environment } process.standardInput = FileHandle.nullDevice } func start(_ continuation: CheckedContinuation) { let out = Pipe() let err = Pipe() process.standardOutput = out process.standardError = err let group = DispatchGroup() var outData = Data() var errData = Data() group.enter() process.terminationHandler = { _ in group.leave() } lock.lock() if cancelled { lock.unlock() continuation.resume(throwing: CancellationError()) return } do { try process.run() } catch { lock.unlock() continuation.resume(throwing: ProcessRunnerError.launchFailed(error.localizedDescription)) return } self.continuation = continuation lock.unlock() group.enter() DispatchQueue.global().async { [self] in outData = drain(out.fileHandleForReading, isError: false) group.leave() } group.enter() DispatchQueue.global().async { [self] in errData = drain(err.fileHandleForReading, isError: true) group.leave() } group.notify(queue: .global()) { [self, process] in resume(with: .success(ProcessResult( exitCode: process.terminationStatus, stdout: String(decoding: outData, as: UTF8.self), stderr: String(decoding: errData, as: UTF8.self) ))) } } /// Resumes the caller once; whichever of finish and cancel comes second is dropped. private func resume(with result: Result) { lock.lock() let pending = continuation continuation = nil lock.unlock() pending?.resume(with: result) } /// Reads a pipe to its end, emitting each line on the way when streaming. private func drain(_ handle: FileHandle, isError: Bool) -> Data { guard let onLine else { return handle.readDataToEndOfFile() } let buffer = LineBuffer() // `read(upToCount:)` waits for the full count; `availableData` returns each chunk as it lands. while true { let chunk = handle.availableData if chunk.isEmpty { break } emit(buffer.append(chunk), isError: isError, onLine) } if let last = buffer.finish() { emit([last], isError: isError, onLine) } return buffer.all } private func emit(_ lines: [String], isError: Bool, _ onLine: @Sendable (String, Bool) -> Void) { guard !lines.isEmpty else { return } emitLock.lock() defer { emitLock.unlock() } for line in lines { onLine(line, isError) } } func cancel() { lock.lock() cancelled = true if process.isRunning { let pid = process.processIdentifier // Descendants first: once the child is gone its children are reparented and out of reach. for descendant in ProcessTree.descendants(of: pid).reversed() { kill(descendant, SIGTERM) } kill(pid, SIGTERM) } lock.unlock() resume(with: .failure(CancellationError())) } } /// The process tree below a pid, read through libproc. enum ProcessTree { /// Children before grandchildren. static func descendants(of pid: pid_t) -> [pid_t] { var out: [pid_t] = [] var queue = [pid] while !queue.isEmpty { let children = Self.children(of: queue.removeFirst()) out += children queue += children } return out } private static func children(of pid: pid_t) -> [pid_t] { var buffer = [pid_t](repeating: 0, count: 64) let bytes = proc_listchildpids(pid, &buffer, Int32(buffer.count * MemoryLayout.size)) guard bytes > 0 else { return [] } return buffer.filter { $0 > 0 } } }