-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProcess.swift
More file actions
273 lines (219 loc) · 10.5 KB
/
Copy pathProcess.swift
File metadata and controls
273 lines (219 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import Foundation
@preconcurrency import Path
import os
import os.log
public typealias ProcessOutput = (status: Int32, out: String, err: String)
public enum XcodesProcess: Sendable {
public static func sudo<P: Pathish>(password: String? = nil, _ executable: P, workingDirectory: URL? = nil, _ arguments: String...) async throws -> ProcessOutput {
try await sudo(password: password, executable, workingDirectory: workingDirectory, arguments)
}
public static func sudo<P: Pathish>(password: String? = nil, _ executable: P, workingDirectory: URL? = nil, _ arguments: [String]) async throws -> ProcessOutput {
var arguments = [executable.string] + arguments
if password != nil {
arguments.insert("-S", at: 0)
}
return try await run(Path.root.usr.bin.sudo.url, workingDirectory: workingDirectory, input: password, arguments)
}
public static func run<P: Pathish>(_ executable: P, workingDirectory: URL? = nil, input: String? = nil, _ arguments: String...) async throws -> ProcessOutput {
try await run(executable, workingDirectory: workingDirectory, input: input, arguments)
}
public static func run<P: Pathish>(_ executable: P, workingDirectory: URL? = nil, input: String? = nil, _ arguments: [String]) async throws -> ProcessOutput {
try await run(executable.url, workingDirectory: workingDirectory, input: input, arguments)
}
public static func run(_ executable: Path, workingDirectory: URL? = nil, input: String? = nil, _ arguments: String...) async throws -> ProcessOutput {
try await Process.run(executable.url, workingDirectory: workingDirectory, input: input, arguments)
}
public static func run(_ executable: URL, workingDirectory: URL? = nil, input: String? = nil, _ arguments: [String]) async throws -> ProcessOutput {
try await Process.run(executable, workingDirectory: workingDirectory, input: input, arguments)
}
}
public extension Process {
@discardableResult
static func sudoAsync<P: Pathish>(password: String? = nil, _ executable: P, workingDirectory: URL? = nil, _ arguments: String...) async throws -> ProcessOutput {
try await XcodesProcess.sudo(password: password, executable, workingDirectory: workingDirectory, arguments)
}
@discardableResult
static func runAsync<P: Pathish>(_ executable: P, workingDirectory: URL? = nil, input: String? = nil, _ arguments: String...) async throws -> ProcessOutput {
try await XcodesProcess.run(executable, workingDirectory: workingDirectory, input: input, arguments)
}
@discardableResult
static func runAsync(_ executable: URL, workingDirectory: URL? = nil, input: String? = nil, _ arguments: [String]) async throws -> ProcessOutput {
try await XcodesProcess.run(executable, workingDirectory: workingDirectory, input: input, arguments)
}
}
extension Process {
static func run(_ executable: Path, workingDirectory: URL? = nil, input: String? = nil, _ arguments: String...) async throws -> ProcessOutput {
return try await run(executable.url, workingDirectory: workingDirectory, input: input, arguments)
}
static func run(_ executable: Path, workingDirectory: URL? = nil, input: String? = nil, _ arguments: String...) throws -> ProcessOutput {
return try run(executable.url, workingDirectory: workingDirectory, input: input, arguments)
}
static func run(_ executable: URL, workingDirectory: URL? = nil, input: String? = nil, _ arguments: [String]) throws -> ProcessOutput {
let process = Process()
process.currentDirectoryURL = workingDirectory ?? executable.deletingLastPathComponent()
process.executableURL = executable
process.arguments = arguments
let (stdout, stderr) = (Pipe(), Pipe())
process.standardOutput = stdout
process.standardError = stderr
if let input = input {
let inputPipe = Pipe()
process.standardInput = inputPipe.fileHandleForReading
inputPipe.fileHandleForWriting.write(Data(input.utf8))
inputPipe.fileHandleForWriting.closeFile()
}
do {
Logger.subprocess.info("Process.run executable: \(executable), input: \(input ?? ""), arguments: \(arguments.joined(separator: ", "))")
try process.run()
process.waitUntilExit()
let output = String(data: stdout.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
let error = String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
Logger.subprocess.info("Process.run output: \(output)")
if !error.isEmpty {
Logger.subprocess.error("Process.run error: \(error)")
}
guard process.terminationReason == .exit, process.terminationStatus == 0 else {
throw ProcessExecutionError(process: process, terminationStatus: process.terminationStatus, standardOutput: output, standardError: error)
}
return (process.terminationStatus, output, error)
} catch {
throw error
}
}
static func run(_ executable: URL, workingDirectory: URL? = nil, input: String? = nil, _ arguments: [String]) async throws -> ProcessOutput {
let process = Process()
process.currentDirectoryURL = workingDirectory ?? executable.deletingLastPathComponent()
process.executableURL = executable
process.arguments = arguments
let (stdout, stderr) = (Pipe(), Pipe())
process.standardOutput = stdout
process.standardError = stderr
if let input = input {
let inputPipe = Pipe()
process.standardInput = inputPipe.fileHandleForReading
inputPipe.fileHandleForWriting.write(Data(input.utf8))
inputPipe.fileHandleForWriting.closeFile()
}
Logger.subprocess.info("Process.run executable: \(executable), input: \(input ?? ""), arguments: \(arguments.joined(separator: ", "))")
let runner = AsyncProcessRunner(process: process, stdout: stdout, stderr: stderr)
return try await withTaskCancellationHandler {
try await runner.run()
} onCancel: {
runner.cancel()
}
}
}
private final class AsyncProcessRunner: Sendable {
private let process: Process
private let stdout: Pipe
private let stderr: Pipe
private let request = OneShotContinuation<ProcessOutput>()
private let output = OSAllocatedUnfairLock(initialState: OutputStorage())
init(process: Process, stdout: Pipe, stderr: Pipe) {
self.process = process
self.stdout = stdout
self.stderr = stderr
}
func run() async throws -> ProcessOutput {
try await request.value {
startReadingOutput()
process.terminationHandler = { [weak self] process in
self?.finish(process: process)
}
do {
try process.run()
} catch {
clearReadabilityHandlers()
throw error
}
}
}
func cancel() {
if process.isRunning {
process.terminate()
}
clearReadabilityHandlers()
request.resume(throwing: CancellationError())
}
private func finish(process: Process) {
clearReadabilityHandlers()
appendRemainingOutput()
let data = output.withLock { $0 }
let output = string(from: data.stdout)
let error = string(from: data.stderr)
Logger.subprocess.info("Process.run output: \(output)")
if !error.isEmpty {
Logger.subprocess.error("Process.run error: \(error)")
}
guard process.terminationReason == .exit, process.terminationStatus == 0 else {
resume(throwing: ProcessExecutionError(process: process, terminationStatus: process.terminationStatus, standardOutput: output, standardError: error))
return
}
resume(returning: (process.terminationStatus, output, error))
}
private func resume(returning output: ProcessOutput) {
request.resume(with: .success(output))
}
private func resume(throwing error: Swift.Error) {
request.resume(throwing: error)
}
private func startReadingOutput() {
stdout.fileHandleForReading.readabilityHandler = { [weak self] handle in
self?.appendAvailableData(from: handle, stream: .stdout)
}
stderr.fileHandleForReading.readabilityHandler = { [weak self] handle in
self?.appendAvailableData(from: handle, stream: .stderr)
}
}
private func appendAvailableData(from handle: FileHandle, stream: OutputStream) {
let data = handle.availableData
guard data.isEmpty == false else { return }
output.withLock {
append(data, to: stream, storage: &$0)
}
}
private func appendRemainingOutput() {
let remainingStdout = stdout.fileHandleForReading.readDataToEndOfFile()
let remainingStderr = stderr.fileHandleForReading.readDataToEndOfFile()
output.withLock {
append(remainingStdout, to: .stdout, storage: &$0)
append(remainingStderr, to: .stderr, storage: &$0)
}
}
private func append(_ data: Data, to stream: OutputStream, storage: inout OutputStorage) {
guard data.isEmpty == false else { return }
switch stream {
case .stdout:
storage.stdout.append(data)
case .stderr:
storage.stderr.append(data)
}
}
private func clearReadabilityHandlers() {
stdout.fileHandleForReading.readabilityHandler = nil
stderr.fileHandleForReading.readabilityHandler = nil
}
private func string(from data: Data) -> String {
String(data: data, encoding: .utf8) ?? ""
}
private enum OutputStream {
case stdout
case stderr
}
private struct OutputStorage: Sendable {
var stdout = Data()
var stderr = Data()
}
}
public struct ProcessExecutionError: Error, Sendable {
public let processDescription: String
public let terminationStatus: Int32
public let standardOutput: String
public let standardError: String
public init(process: Process, terminationStatus: Int32 = 0, standardOutput: String?, standardError: String?) {
self.processDescription = process.description
self.terminationStatus = terminationStatus
self.standardOutput = standardOutput ?? ""
self.standardError = standardError ?? ""
}
}