-
Notifications
You must be signed in to change notification settings - Fork 125
Conditionally adopt swift-subprocess #638
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,18 +11,21 @@ | |
| //===----------------------------------------------------------------------===// | ||
|
|
||
| public import Foundation | ||
| import SWBLibc | ||
| public import SWBLibc | ||
| import Synchronization | ||
|
|
||
| #if os(Windows) | ||
| public typealias pid_t = Int32 | ||
| #if canImport(Subprocess) && (!canImport(Darwin) || os(macOS)) | ||
| import Subprocess | ||
| #endif | ||
|
|
||
| #if !canImport(Darwin) | ||
| extension ProcessInfo { | ||
| public var isMacCatalystApp: Bool { | ||
| false | ||
| } | ||
| } | ||
| #if canImport(System) | ||
| public import System | ||
| #else | ||
| public import SystemPackage | ||
| #endif | ||
|
|
||
| #if os(Windows) | ||
| public typealias pid_t = Int32 | ||
| #endif | ||
|
|
||
| #if (!canImport(Foundation.NSTask) || targetEnvironment(macCatalyst)) && canImport(Darwin) | ||
|
|
@@ -64,7 +67,7 @@ public typealias Process = Foundation.Process | |
| #endif | ||
|
|
||
| extension Process { | ||
| public static var hasUnsafeWorkingDirectorySupport: Bool { | ||
| fileprivate static var hasUnsafeWorkingDirectorySupport: Bool { | ||
| get throws { | ||
| switch try ProcessInfo.processInfo.hostOperatingSystem() { | ||
| case .linux: | ||
|
|
@@ -81,6 +84,30 @@ extension Process { | |
|
|
||
| extension Process { | ||
| public static func getOutput(url: URL, arguments: [String], currentDirectoryURL: URL? = nil, environment: Environment? = nil, interruptible: Bool = true) async throws -> Processes.ExecutionResult { | ||
| #if canImport(Subprocess) | ||
| #if !canImport(Darwin) || os(macOS) | ||
| var platformOptions = PlatformOptions() | ||
| if interruptible { | ||
| platformOptions.teardownSequence = [.gracefulShutDown(allowedDurationToNextStep: .seconds(5))] | ||
| } | ||
| let configuration = try Subprocess.Configuration( | ||
| .path(FilePath(url.filePath.str)), | ||
| arguments: .init(arguments), | ||
| environment: environment.map { .custom(.init($0)) } ?? .inherit, | ||
| workingDirectory: (currentDirectoryURL?.filePath.str).map { FilePath($0) } ?? nil, | ||
| platformOptions: platformOptions | ||
| ) | ||
| let result = try await Subprocess.run(configuration, body: { execution, inputWriter, outputReader, errorReader in | ||
| async let stdoutBytes = outputReader.collect().flatMap { $0.withUnsafeBytes(Array.init) } | ||
| async let stderrBytes = errorReader.collect().flatMap { $0.withUnsafeBytes(Array.init) } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is existing behavior; we can address it separately. |
||
| try await inputWriter.finish() | ||
| return try await (stdoutBytes, stderrBytes) | ||
| }) | ||
| return Processes.ExecutionResult(exitStatus: .init(result.terminationStatus), stdout: Data(result.value.0), stderr: Data(result.value.1)) | ||
| #else | ||
| throw StubError.error("Process spawning is unavailable") | ||
| #endif | ||
| #else | ||
| if #available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *) { | ||
| let stdoutPipe = Pipe() | ||
| let stderrPipe = Pipe() | ||
|
|
@@ -118,9 +145,40 @@ extension Process { | |
| } | ||
| return Processes.ExecutionResult(exitStatus: exitStatus, stdout: Data(output.stdoutData), stderr: Data(output.stderrData)) | ||
| } | ||
| #endif | ||
| } | ||
|
|
||
| public static func getMergedOutput(url: URL, arguments: [String], currentDirectoryURL: URL? = nil, environment: Environment? = nil, interruptible: Bool = true) async throws -> (exitStatus: Processes.ExitStatus, output: Data) { | ||
| #if canImport(Subprocess) | ||
| #if !canImport(Darwin) || os(macOS) | ||
| let (readEnd, writeEnd) = try FileDescriptor.pipe() | ||
| return try await readEnd.closeAfter { | ||
| // Direct both stdout and stderr to the same fd. Only set `closeAfterSpawningProcess` on one of the outputs so it isn't double-closed (similarly avoid using closeAfter for the same reason). | ||
| var platformOptions = PlatformOptions() | ||
| if interruptible { | ||
| platformOptions.teardownSequence = [.gracefulShutDown(allowedDurationToNextStep: .seconds(5))] | ||
| } | ||
| let configuration = try Subprocess.Configuration( | ||
| .path(FilePath(url.filePath.str)), | ||
| arguments: .init(arguments), | ||
| environment: environment.map { .custom(.init($0)) } ?? .inherit, | ||
| workingDirectory: (currentDirectoryURL?.filePath.str).map { FilePath($0) } ?? nil, | ||
| platformOptions: platformOptions | ||
| ) | ||
| // FIXME: Use new API from https://github.com/swiftlang/swift-subprocess/pull/180 | ||
| let result = try await Subprocess.run(configuration, output: .fileDescriptor(writeEnd, closeAfterSpawningProcess: true), error: .fileDescriptor(writeEnd, closeAfterSpawningProcess: false), body: { execution in | ||
| if #available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *) { | ||
| try await Array(Data(DispatchFD(fileDescriptor: readEnd).dataStream().collect())) | ||
| } else { | ||
| try await Array(Data(DispatchFD(fileDescriptor: readEnd)._dataStream().collect())) | ||
| } | ||
| }) | ||
| return (.init(result.terminationStatus), Data(result.value)) | ||
| } | ||
| #else | ||
| throw StubError.error("Process spawning is unavailable") | ||
| #endif | ||
| #else | ||
| if #available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *) { | ||
| let pipe = Pipe() | ||
|
|
||
|
|
@@ -150,6 +208,7 @@ extension Process { | |
| } | ||
| return (exitStatus: exitStatus, output: Data(output)) | ||
| } | ||
| #endif | ||
| } | ||
|
|
||
| private static func _getOutput<T, U>(url: URL, arguments: [String], currentDirectoryURL: URL?, environment: Environment?, interruptible: Bool, setup: (Process) -> T, collect: @Sendable (T) async throws -> U) async throws -> (exitStatus: Processes.ExitStatus, output: U) { | ||
|
|
@@ -221,9 +280,8 @@ public enum Processes: Sendable { | |
| case exit(_ code: Int32) | ||
| case uncaughtSignal(_ signal: Int32) | ||
|
|
||
| public init?(rawValue: Int32) { | ||
| #if os(Windows) | ||
| let dwExitCode = DWORD(bitPattern: rawValue) | ||
| #if os(Windows) | ||
| public init(dwExitCode: DWORD) { | ||
| // Do the same thing as swift-corelibs-foundation (the input value is the GetExitCodeProcess return value) | ||
| if (dwExitCode & 0xF0000000) == 0x80000000 // HRESULT | ||
| || (dwExitCode & 0xF0000000) == 0xC0000000 // NTSTATUS | ||
|
|
@@ -233,6 +291,12 @@ public enum Processes: Sendable { | |
| } else { | ||
| self = .exit(Int32(bitPattern: UInt32(dwExitCode))) | ||
| } | ||
| } | ||
| #endif | ||
|
|
||
| public init?(rawValue: Int32) { | ||
| #if os(Windows) | ||
| self = .init(dwExitCode: DWORD(bitPattern: rawValue)) | ||
| #else | ||
| func WSTOPSIG(_ status: Int32) -> Int32 { | ||
| return status >> 8 | ||
|
|
@@ -312,6 +376,37 @@ public enum Processes: Sendable { | |
| } | ||
| } | ||
|
|
||
| #if canImport(Subprocess) && (!canImport(Darwin) || os(macOS)) | ||
| extension Processes.ExitStatus { | ||
| init(_ terminationStatus: TerminationStatus) { | ||
| switch terminationStatus { | ||
| case let .exited(code): | ||
| self = .exit(numericCast(code)) | ||
| case let .unhandledException(code): | ||
| #if os(Windows) | ||
| // Currently swift-subprocess returns the original raw GetExitCodeProcess value as uncaughtSignal for all values other than zero. | ||
| // See also: https://github.com/swiftlang/swift-subprocess/issues/114 | ||
| self = .init(dwExitCode: code) | ||
| #else | ||
| self = .uncaughtSignal(code) | ||
| #endif | ||
| } | ||
| } | ||
| } | ||
|
|
||
| extension [Subprocess.Environment.Key: String] { | ||
| internal init(_ environment: Environment) { | ||
| self.init() | ||
| let sorted = environment.sorted { $0.key < $1.key } | ||
| for (key, value) in sorted { | ||
| if let typedKey = Subprocess.Environment.Key(rawValue: key.rawValue) { | ||
| self[typedKey] = value | ||
| } | ||
| } | ||
| } | ||
| } | ||
| #endif | ||
|
|
||
| extension Processes.ExitStatus { | ||
| public init(_ process: Process) throws { | ||
| assert(!process.isRunning) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
two
*Unsafe*s hereThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
so? we can't use Span yet, this still has to build with 6.1