adds nice git interface
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
|
||||
public struct ProcessResult: Sendable, Equatable {
|
||||
@@ -24,9 +25,21 @@ public protocol ProcessRunning: Sendable {
|
||||
/// Runs `executable` (a name looked up on the search path, or a path) and collects its output.
|
||||
/// A non-zero exit is a normal result, not an error; `environment: nil` inherits ours.
|
||||
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult
|
||||
/// Like `run`, but hands each output line to `onLine` as it arrives (`isError` for stderr).
|
||||
func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult
|
||||
}
|
||||
|
||||
extension ProcessRunning {
|
||||
/// Runs to completion, then emits the stdout lines and after them the stderr lines.
|
||||
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
|
||||
let result = try await run(executable, arguments: arguments, in: directory, environment: environment)
|
||||
for line in OutputLines.split(result.stdout) { onLine(line, false) }
|
||||
for line in OutputLines.split(result.stderr) { onLine(line, true) }
|
||||
return result
|
||||
}
|
||||
|
||||
public func run(_ executable: String, _ arguments: [String], in directory: URL? = nil) async throws -> ProcessResult {
|
||||
try await run(executable, arguments: arguments, in: directory, environment: nil)
|
||||
}
|
||||
@@ -40,8 +53,18 @@ public struct ProcessRunner: ProcessRunning {
|
||||
}
|
||||
|
||||
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
|
||||
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: nil)
|
||||
}
|
||||
|
||||
public func stream(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async throws -> ProcessResult {
|
||||
try await launch(executable, arguments: arguments, in: directory, environment: environment, onLine: onLine)
|
||||
}
|
||||
|
||||
private func launch(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?,
|
||||
onLine: (@Sendable (String, Bool) -> Void)?) async throws -> ProcessResult {
|
||||
guard let url = locator.locate(executable) else { throw ProcessRunnerError.executableNotFound(executable) }
|
||||
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment)
|
||||
let job = Job(url: url, arguments: arguments, directory: directory, environment: environment, onLine: onLine)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
job.start(continuation)
|
||||
@@ -52,14 +75,55 @@ public struct ProcessRunner: ProcessRunning {
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits output into lines on "\n" and "\r", so a progress update ends a line too; empty lines are dropped.
|
||||
enum OutputLines {
|
||||
static func split(_ text: String) -> [String] {
|
||||
text.split(omittingEmptySubsequences: true) { $0 == "\n" || $0 == "\r" || $0 == "\r\n" }.map(String.init)
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects one pipe's bytes and, when streaming, cuts them into lines as they arrive.
|
||||
private final class LineBuffer {
|
||||
private(set) var all = Data()
|
||||
private var pending = Data()
|
||||
|
||||
/// Appends a chunk and returns the lines it completed.
|
||||
func append(_ chunk: Data) -> [String] {
|
||||
all.append(chunk)
|
||||
pending.append(chunk)
|
||||
var lines: [String] = []
|
||||
while let end = pending.firstIndex(where: { $0 == 0x0A || $0 == 0x0D }) {
|
||||
let line = pending[pending.startIndex..<end]
|
||||
if !line.isEmpty { lines.append(String(decoding: line, as: UTF8.self)) }
|
||||
pending.removeSubrange(pending.startIndex...end)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
/// The last line when the output did not end with a line break.
|
||||
func finish() -> String? {
|
||||
defer { pending.removeAll() }
|
||||
return pending.isEmpty ? nil : String(decoding: pending, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
|
||||
/// One child process. Both pipes are drained on their own threads, because a child that
|
||||
/// fills one pipe while we wait on the other would deadlock.
|
||||
///
|
||||
/// A cancel resumes at once and signals the child and every descendant: a grandchild such as
|
||||
/// `ssh` can hold a pipe open long after the child is gone, so waiting for EOF could hang.
|
||||
private final class Job: @unchecked Sendable {
|
||||
private let process = Process()
|
||||
private let lock = NSLock()
|
||||
private var cancelled = false
|
||||
private var continuation: CheckedContinuation<ProcessResult, Error>?
|
||||
private let onLine: (@Sendable (String, Bool) -> Void)?
|
||||
/// Keeps `onLine` to one call at a time, though both pipes feed it.
|
||||
private let emitLock = NSLock()
|
||||
|
||||
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?) {
|
||||
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?,
|
||||
onLine: (@Sendable (String, Bool) -> Void)?) {
|
||||
self.onLine = onLine
|
||||
process.executableURL = url
|
||||
process.arguments = arguments
|
||||
if let directory { process.currentDirectoryURL = directory }
|
||||
@@ -80,53 +144,102 @@ private final class Job: @unchecked Sendable {
|
||||
process.terminationHandler = { _ in group.leave() }
|
||||
|
||||
lock.lock()
|
||||
let alreadyCancelled = cancelled
|
||||
if cancelled {
|
||||
lock.unlock()
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
do {
|
||||
if !alreadyCancelled { try process.run() }
|
||||
try process.run()
|
||||
} catch {
|
||||
lock.unlock()
|
||||
continuation.resume(throwing: ProcessRunnerError.launchFailed(error.localizedDescription))
|
||||
return
|
||||
}
|
||||
self.continuation = continuation
|
||||
lock.unlock()
|
||||
if alreadyCancelled {
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
|
||||
group.enter()
|
||||
DispatchQueue.global().async {
|
||||
outData = out.fileHandleForReading.readDataToEndOfFile()
|
||||
DispatchQueue.global().async { [self] in
|
||||
outData = drain(out.fileHandleForReading, isError: false)
|
||||
group.leave()
|
||||
}
|
||||
group.enter()
|
||||
DispatchQueue.global().async {
|
||||
errData = err.fileHandleForReading.readDataToEndOfFile()
|
||||
DispatchQueue.global().async { [self] in
|
||||
errData = drain(err.fileHandleForReading, isError: true)
|
||||
group.leave()
|
||||
}
|
||||
group.notify(queue: .global()) { [self, process] in
|
||||
if wasCancelled {
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
continuation.resume(returning: ProcessResult(
|
||||
resume(with: .success(ProcessResult(
|
||||
exitCode: process.terminationStatus,
|
||||
stdout: String(decoding: outData, as: UTF8.self),
|
||||
stderr: String(decoding: errData, as: UTF8.self)
|
||||
))
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
private var wasCancelled: Bool {
|
||||
/// Resumes the caller once; whichever of finish and cancel comes second is dropped.
|
||||
private func resume(with result: Result<ProcessResult, Error>) {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return cancelled
|
||||
let pending = continuation
|
||||
continuation = nil
|
||||
lock.unlock()
|
||||
pending?.resume(with: result)
|
||||
}
|
||||
|
||||
/// Reads a pipe to its end, emitting each line on the way when streaming.
|
||||
private func drain(_ handle: FileHandle, isError: Bool) -> Data {
|
||||
guard let onLine else { return handle.readDataToEndOfFile() }
|
||||
let buffer = LineBuffer()
|
||||
// `read(upToCount:)` waits for the full count; `availableData` returns each chunk as it lands.
|
||||
while true {
|
||||
let chunk = handle.availableData
|
||||
if chunk.isEmpty { break }
|
||||
emit(buffer.append(chunk), isError: isError, onLine)
|
||||
}
|
||||
if let last = buffer.finish() { emit([last], isError: isError, onLine) }
|
||||
return buffer.all
|
||||
}
|
||||
|
||||
private func emit(_ lines: [String], isError: Bool, _ onLine: @Sendable (String, Bool) -> Void) {
|
||||
guard !lines.isEmpty else { return }
|
||||
emitLock.lock()
|
||||
defer { emitLock.unlock() }
|
||||
for line in lines { onLine(line, isError) }
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
cancelled = true
|
||||
if process.isRunning { process.terminate() }
|
||||
if process.isRunning {
|
||||
let pid = process.processIdentifier
|
||||
// Descendants first: once the child is gone its children are reparented and out of reach.
|
||||
for descendant in ProcessTree.descendants(of: pid).reversed() { kill(descendant, SIGTERM) }
|
||||
kill(pid, SIGTERM)
|
||||
}
|
||||
lock.unlock()
|
||||
resume(with: .failure(CancellationError()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The process tree below a pid, read through libproc.
|
||||
enum ProcessTree {
|
||||
/// Children before grandchildren.
|
||||
static func descendants(of pid: pid_t) -> [pid_t] {
|
||||
var out: [pid_t] = []
|
||||
var queue = [pid]
|
||||
while !queue.isEmpty {
|
||||
let children = Self.children(of: queue.removeFirst())
|
||||
out += children
|
||||
queue += children
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private static func children(of pid: pid_t) -> [pid_t] {
|
||||
var buffer = [pid_t](repeating: 0, count: 64)
|
||||
let bytes = proc_listchildpids(pid, &buffer, Int32(buffer.count * MemoryLayout<pid_t>.size))
|
||||
guard bytes > 0 else { return [] }
|
||||
return buffer.filter { $0 > 0 }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user