xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XUtils / Subprocess+Utils.swift
Subprocess+Utils.swift74 lines · 2.0 KiBRaw
| 1 | #if canImport(Subprocess) |
| 2 | import Subprocess |
| 3 | import Foundation |
| 4 | |
| 5 | extension ExecutionResult { |
| 6 | @discardableResult |
| 7 | public func checkSuccess() throws(SubprocessFailure) -> Self { |
| 8 | try terminationStatus.checkSuccess() |
| 9 | return self |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | extension TerminationStatus { |
| 14 | fileprivate func checkSuccess() throws(SubprocessFailure) { |
| 15 | if let failure { throw failure } |
| 16 | } |
| 17 | |
| 18 | private var failure: SubprocessFailure? { |
| 19 | if isSuccess { return nil } |
| 20 | switch self { |
| 21 | case .exited(let code): return .exited(code) |
| 22 | case .signaled(let code): return .signaled(code) |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | public enum SubprocessFailure: Error { |
| 28 | case exited(TerminationStatus.Code) |
| 29 | case signaled(TerminationStatus.Code) |
| 30 | } |
| 31 | |
| 32 | extension PlatformOptions { |
| 33 | public static var withGracefulShutDown: Self { |
| 34 | .init().withGracefulShutDown |
| 35 | } |
| 36 | |
| 37 | public var withGracefulShutDown: Self { |
| 38 | var copy = self |
| 39 | copy.teardownSequence = [ |
| 40 | .gracefulShutDown( |
| 41 | allowedDurationToNextStep: .milliseconds(500) |
| 42 | ) |
| 43 | ] |
| 44 | return copy |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | extension Environment { |
| 49 | public static func currentMap() -> [Environment.Key: String] { |
| 50 | Dictionary( |
| 51 | uniqueKeysWithValues: ProcessInfo.processInfo.environment.map { |
| 52 | (Environment.Key(rawValue: $0)!, $1) |
| 53 | } |
| 54 | ) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | extension OutputProtocol where Self == FileDescriptorOutput { |
| 59 | /// Writes subprocess output to `d.out`'s stdout |
| 60 | public static func xtoolOutput() throws -> Self { |
| 61 | try makeXToolOutput(for: .stdout) |
| 62 | } |
| 63 | |
| 64 | /// Writes subprocess output to `d.out`'s stderr |
| 65 | public static func xtoolError() throws -> Self { |
| 66 | try makeXToolOutput(for: .stderr) |
| 67 | } |
| 68 | |
| 69 | private static func makeXToolOutput(for stream: CommandOutput.Stream) throws -> Self { |
| 70 | let fd = try d.out.makeDescriptor(for: stream) |
| 71 | return .fileDescriptor(fd, closeAfterSpawningProcess: true) |
| 72 | } |
| 73 | } |
| 74 | #endif |