|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import Foundation |
| 14 | + |
| 15 | +/// Keeps track of subprocesses spawned by this script and forwards SIGINT |
| 16 | +/// signals to them. |
| 17 | +class SigIntListener { |
| 18 | + /// The subprocesses spawned by this script that are currently running. |
| 19 | + static var runningSubprocesses: Set<Process> = [] |
| 20 | + |
| 21 | + /// Whether a `SIGINT` signal has been received by this script. |
| 22 | + static var hasReceivedSigInt: Bool = false |
| 23 | + |
| 24 | + /// Registers a `SIGINT` signal handler that forwards `SIGINT` to all |
| 25 | + /// subprocesses that are registered in `runningSubprocesses` |
| 26 | + static func registerSigIntSubprocessTerminationHandler() { |
| 27 | + #if canImport(Darwin) || canImport(Glibc) |
| 28 | + signal(SIGINT) { _ in |
| 29 | + SigIntListener.hasReceivedSigInt = true |
| 30 | + for process in SigIntListener.runningSubprocesses { |
| 31 | + process.interrupt() |
| 32 | + } |
| 33 | + } |
| 34 | + #endif |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +/// Provides convenience APIs for launching and gathering output from a subprocess |
| 39 | +public class ProcessRunner { |
| 40 | + private static let serialQueue = DispatchQueue(label: "\(ProcessRunner.self)") |
| 41 | + |
| 42 | + private let process: Process |
| 43 | + |
| 44 | + public init( |
| 45 | + executableURL: URL, |
| 46 | + arguments: [String], |
| 47 | + additionalEnvironment: [String: String] = [:] |
| 48 | + ) { |
| 49 | + process = Process() |
| 50 | + process.executableURL = executableURL |
| 51 | + process.arguments = arguments |
| 52 | + process.environment = additionalEnvironment.merging(ProcessInfo.processInfo.environment) { (additional, _) in additional } |
| 53 | + } |
| 54 | + |
| 55 | + @discardableResult |
| 56 | + public func run( |
| 57 | + captureStdout: Bool = true, |
| 58 | + captureStderr: Bool = true, |
| 59 | + verbose: Bool |
| 60 | + ) throws -> ProcessResult { |
| 61 | + if verbose { |
| 62 | + print(process.command) |
| 63 | + } |
| 64 | + |
| 65 | + let group = DispatchGroup() |
| 66 | + |
| 67 | + var stdoutData = Data() |
| 68 | + if captureStdout { |
| 69 | + let outPipe = Pipe() |
| 70 | + process.standardOutput = outPipe |
| 71 | + addHandler(pipe: outPipe, group: group) { stdoutData.append($0) } |
| 72 | + } |
| 73 | + |
| 74 | + var stderrData = Data() |
| 75 | + if captureStderr { |
| 76 | + let errPipe = Pipe() |
| 77 | + process.standardError = errPipe |
| 78 | + addHandler(pipe: errPipe, group: group) { stderrData.append($0) } |
| 79 | + } |
| 80 | + |
| 81 | + try process.run() |
| 82 | + SigIntListener.runningSubprocesses.insert(process) |
| 83 | + process.waitUntilExit() |
| 84 | + SigIntListener.runningSubprocesses.remove(process) |
| 85 | + if captureStdout || captureStderr { |
| 86 | + // Make sure we've received all stdout/stderr |
| 87 | + group.wait() |
| 88 | + } |
| 89 | + |
| 90 | + guard let stdoutString = String(data: stdoutData, encoding: .utf8) else { |
| 91 | + throw FailedToDecodeUTF8Error(data: stdoutData) |
| 92 | + } |
| 93 | + guard let stderrString = String(data: stderrData, encoding: .utf8) else { |
| 94 | + throw FailedToDecodeUTF8Error(data: stderrData) |
| 95 | + } |
| 96 | + |
| 97 | + guard process.terminationStatus == 0 else { |
| 98 | + throw NonZeroExitCodeError( |
| 99 | + process: process, |
| 100 | + stdout: stdoutString, |
| 101 | + stderr: stderrString, |
| 102 | + exitCode: Int(process.terminationStatus) |
| 103 | + ) |
| 104 | + } |
| 105 | + |
| 106 | + return ProcessResult( |
| 107 | + stdout: stdoutString, |
| 108 | + stderr: stderrString |
| 109 | + ) |
| 110 | + } |
| 111 | + |
| 112 | + private func addHandler( |
| 113 | + pipe: Pipe, |
| 114 | + group: DispatchGroup, |
| 115 | + addData: @escaping (Data) -> Void |
| 116 | + ) { |
| 117 | + group.enter() |
| 118 | + pipe.fileHandleForReading.readabilityHandler = { fileHandle in |
| 119 | + // Apparently using availableData can cause various issues |
| 120 | + let newData = fileHandle.readData(ofLength: Int.max) |
| 121 | + if newData.count == 0 { |
| 122 | + pipe.fileHandleForReading.readabilityHandler = nil; |
| 123 | + group.leave() |
| 124 | + } else { |
| 125 | + addData(newData) |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +/// The exit code and output (if redirected) from a subprocess that has |
| 132 | +/// terminated |
| 133 | +public struct ProcessResult { |
| 134 | + public let stdout: String |
| 135 | + public let stderr: String |
| 136 | +} |
| 137 | + |
| 138 | +/// Error thrown if a process terminates with a non-zero exit code. |
| 139 | +struct NonZeroExitCodeError: Error, CustomStringConvertible { |
| 140 | + let process: Process |
| 141 | + let stdout: String |
| 142 | + let stderr: String |
| 143 | + let exitCode: Int |
| 144 | + |
| 145 | + var description: String { |
| 146 | + var result = """ |
| 147 | + Command failed with non-zero exit code \(exitCode): |
| 148 | + Command: \(process.command) |
| 149 | + """ |
| 150 | + if !stdout.isEmpty { |
| 151 | + result += """ |
| 152 | + Standard output: |
| 153 | + \(stdout) |
| 154 | + """ |
| 155 | + } |
| 156 | + if !stderr.isEmpty { |
| 157 | + result += """ |
| 158 | + Standard error: |
| 159 | + \(stderr) |
| 160 | + """ |
| 161 | + } |
| 162 | + return result |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +/// Error thrown if `stdout` or `stderr` could not be decoded as UTF-8. |
| 167 | +struct FailedToDecodeUTF8Error: Error { |
| 168 | + let data: Data |
| 169 | +} |
| 170 | + |
| 171 | +extension Process { |
| 172 | + var command: String { |
| 173 | + var message = "" |
| 174 | + |
| 175 | + for (key, value) in environment?.sorted(by: { $0.key < $1.key }) ?? [] { |
| 176 | + message += "\(key)='\(value)' " |
| 177 | + } |
| 178 | + |
| 179 | + if let executableURL = executableURL { |
| 180 | + message += executableURL.path |
| 181 | + } |
| 182 | + |
| 183 | + if let arguments = arguments { |
| 184 | + message += " \(arguments.joined(separator: " "))" |
| 185 | + } |
| 186 | + |
| 187 | + return message |
| 188 | + } |
| 189 | +} |
0 commit comments