import Foundation /// Starts another Helder process, for a launch outside an app bundle (`swift run`). public enum InstanceLauncher { /// Passed as `-HelderProject `: 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) } } } }