-
Notifications
You must be signed in to change notification settings - Fork 123
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
Open
jakepetroules
wants to merge
1
commit into
swiftlang:main
Choose a base branch
from
jakepetroules:eng/PR-swift-subprocess
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
|
||
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) { | ||
|
@@ -215,9 +274,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 | ||
|
@@ -227,6 +285,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 | ||
|
@@ -306,6 +370,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] { | ||
fileprivate 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) | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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