restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
|
||||
/// Collects the exit status of a child we signalled, so it does not linger as a zombie.
|
||||
public enum ChildReaper {
|
||||
/// Waits for `pid` without blocking a thread, sends SIGKILL once `grace` has passed, and returns once it is reaped.
|
||||
///
|
||||
/// Stops at once when `pid` is not an unreaped child of ours (someone else reaped it), so a
|
||||
/// recycled pid is never signalled.
|
||||
public static func reap(_ pid: pid_t, grace: TimeInterval = 2) async {
|
||||
guard pid > 0 else { return }
|
||||
let deadline = Date().addingTimeInterval(grace)
|
||||
var killed = false
|
||||
while true {
|
||||
var status: Int32 = 0
|
||||
let result = waitpid(pid, &status, WNOHANG)
|
||||
if result == pid { return }
|
||||
if result == -1 && errno != EINTR { return }
|
||||
if result == 0 && !killed && Date() >= deadline {
|
||||
kill(pid, SIGKILL)
|
||||
killed = true
|
||||
}
|
||||
if Task.isCancelled { return }
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
|
||||
/// Finds command-line tools for a GUI app, whose PATH is only /usr/bin:/bin:/usr/sbin:/sbin.
|
||||
public struct ExecutableLocator: Sendable {
|
||||
/// Directories searched in order.
|
||||
public var directories: [String]
|
||||
|
||||
public init(directories: [String]) {
|
||||
self.directories = directories
|
||||
}
|
||||
|
||||
/// The app's own Helpers folder (where bundle.sh puts ripgrep), then PATH, then Homebrew.
|
||||
public static var standard: ExecutableLocator {
|
||||
var dirs: [String] = []
|
||||
dirs.append(Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers").path)
|
||||
let path = ProcessInfo.processInfo.environment["PATH"] ?? "/usr/bin:/bin:/usr/sbin:/sbin"
|
||||
dirs += path.split(separator: ":").map(String.init)
|
||||
dirs += ["/opt/homebrew/bin", "/usr/local/bin"]
|
||||
var seen = Set<String>()
|
||||
return ExecutableLocator(directories: dirs.filter { seen.insert($0).inserted })
|
||||
}
|
||||
|
||||
/// The first executable file called `name`, or nil. A name with a slash is checked as given.
|
||||
public func locate(_ name: String) -> URL? {
|
||||
let fm = FileManager.default
|
||||
if name.contains("/") {
|
||||
return fm.isExecutableFile(atPath: name) ? URL(fileURLWithPath: name) : nil
|
||||
}
|
||||
for dir in directories {
|
||||
let candidate = (dir as NSString).appendingPathComponent(name)
|
||||
var isDir: ObjCBool = false
|
||||
if fm.fileExists(atPath: candidate, isDirectory: &isDir), !isDir.boolValue, fm.isExecutableFile(atPath: candidate) {
|
||||
return URL(fileURLWithPath: candidate)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import Foundation
|
||||
|
||||
/// Starts another Helder process, for a launch outside an app bundle (`swift run`).
|
||||
public enum InstanceLauncher {
|
||||
/// Passed as `-HelderProject <folder>`: AppKit reads a `-Key value` pair as a default, not as a file to open.
|
||||
public static func arguments(for root: URL?) -> [String] {
|
||||
root.map { ["-HelderProject", $0.path] } ?? []
|
||||
}
|
||||
|
||||
/// Runs `executable` on `root` (nil shows the launcher) and reaps it when it exits.
|
||||
/// `HELDER_PROJECT` is dropped from the child's environment, since it wins over the argument.
|
||||
public static func spawn(_ executable: URL, root: URL?,
|
||||
environment: [String: String] = ProcessInfo.processInfo.environment) throws {
|
||||
var environment = environment
|
||||
environment["HELDER_PROJECT"] = nil
|
||||
let process = Process()
|
||||
process.executableURL = executable
|
||||
process.arguments = arguments(for: root)
|
||||
process.environment = environment
|
||||
let id = ObjectIdentifier(process)
|
||||
process.terminationHandler = { _ in children.remove(id) }
|
||||
children.insert(process)
|
||||
do {
|
||||
try process.run()
|
||||
} catch {
|
||||
children.remove(id)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private static let children = Children()
|
||||
|
||||
/// Keeps each child's `Process` alive until it exits, so its exit status is always collected.
|
||||
private final class Children: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var running: [ObjectIdentifier: Process] = [:]
|
||||
|
||||
func insert(_ process: Process) {
|
||||
lock.withLock { running[ObjectIdentifier(process)] = process }
|
||||
}
|
||||
|
||||
func remove(_ id: ObjectIdentifier) {
|
||||
_ = lock.withLock { running.removeValue(forKey: id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import Foundation
|
||||
|
||||
public struct ProcessResult: Sendable, Equatable {
|
||||
public var exitCode: Int32
|
||||
public var stdout: String
|
||||
public var stderr: String
|
||||
|
||||
public init(exitCode: Int32, stdout: String, stderr: String) {
|
||||
self.exitCode = exitCode
|
||||
self.stdout = stdout
|
||||
self.stderr = stderr
|
||||
}
|
||||
|
||||
public var succeeded: Bool { exitCode == 0 }
|
||||
}
|
||||
|
||||
public enum ProcessRunnerError: Error, Equatable {
|
||||
case executableNotFound(String)
|
||||
case launchFailed(String)
|
||||
}
|
||||
|
||||
/// Runs a command to completion. Services depend on this protocol so tests can script the output.
|
||||
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
|
||||
}
|
||||
|
||||
extension ProcessRunning {
|
||||
public func run(_ executable: String, _ arguments: [String], in directory: URL? = nil) async throws -> ProcessResult {
|
||||
try await run(executable, arguments: arguments, in: directory, environment: nil)
|
||||
}
|
||||
}
|
||||
|
||||
public struct ProcessRunner: ProcessRunning {
|
||||
public let locator: ExecutableLocator
|
||||
|
||||
public init(locator: ExecutableLocator = .standard) {
|
||||
self.locator = locator
|
||||
}
|
||||
|
||||
public func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) 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)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
job.start(continuation)
|
||||
}
|
||||
} onCancel: {
|
||||
job.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
private final class Job: @unchecked Sendable {
|
||||
private let process = Process()
|
||||
private let lock = NSLock()
|
||||
private var cancelled = false
|
||||
|
||||
init(url: URL, arguments: [String], directory: URL?, environment: [String: String]?) {
|
||||
process.executableURL = url
|
||||
process.arguments = arguments
|
||||
if let directory { process.currentDirectoryURL = directory }
|
||||
if let environment { process.environment = environment }
|
||||
process.standardInput = FileHandle.nullDevice
|
||||
}
|
||||
|
||||
func start(_ continuation: CheckedContinuation<ProcessResult, Error>) {
|
||||
let out = Pipe()
|
||||
let err = Pipe()
|
||||
process.standardOutput = out
|
||||
process.standardError = err
|
||||
|
||||
let group = DispatchGroup()
|
||||
var outData = Data()
|
||||
var errData = Data()
|
||||
group.enter()
|
||||
process.terminationHandler = { _ in group.leave() }
|
||||
|
||||
lock.lock()
|
||||
let alreadyCancelled = cancelled
|
||||
do {
|
||||
if !alreadyCancelled { try process.run() }
|
||||
} catch {
|
||||
lock.unlock()
|
||||
continuation.resume(throwing: ProcessRunnerError.launchFailed(error.localizedDescription))
|
||||
return
|
||||
}
|
||||
lock.unlock()
|
||||
if alreadyCancelled {
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
|
||||
group.enter()
|
||||
DispatchQueue.global().async {
|
||||
outData = out.fileHandleForReading.readDataToEndOfFile()
|
||||
group.leave()
|
||||
}
|
||||
group.enter()
|
||||
DispatchQueue.global().async {
|
||||
errData = err.fileHandleForReading.readDataToEndOfFile()
|
||||
group.leave()
|
||||
}
|
||||
group.notify(queue: .global()) { [self, process] in
|
||||
if wasCancelled {
|
||||
continuation.resume(throwing: CancellationError())
|
||||
return
|
||||
}
|
||||
continuation.resume(returning: ProcessResult(
|
||||
exitCode: process.terminationStatus,
|
||||
stdout: String(decoding: outData, as: UTF8.self),
|
||||
stderr: String(decoding: errData, as: UTF8.self)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
private var wasCancelled: Bool {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return cancelled
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
cancelled = true
|
||||
if process.isRunning { process.terminate() }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user