Repository Public License
1// ORIX Convert — Packages/ORIXConvertCore/Sources/ConvertCore/Tools.swift2// Description: Locates and runs the helper executables bundled with ORIX Convert (ffmpeg, pandoc, LibreOffice…).3// Tools are looked up ONLY in the app bundle or in the repository's EmbeddedEngines/tools directory —4// never in PATH, Homebrew or /Applications. Arguments are passed as an array; no shell is involved.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import Foundation78public enum BundledTools {9 /// Directories searched, in order:10 /// 1. `ORIX_CONVERT_TOOLS` (tests, CLI during development, Debug builds of the app);11 /// 2. `<App>.app/Contents/Helpers` — of the main bundle, or of the bundle the running executable sits in when12 /// that executable is itself a helper (`…/Contents/Helpers/orix-convert`): its own directory;13 /// 3. `EmbeddedEngines/tools` found by walking up from this source file — **only when the process is not the14 /// shipped application** (package tests and tools started from `.build`; note that `swift test` itself runs15 /// from inside `Xcode.app`). The shipped application is recognised by its main bundle: an `.app` whose16 /// identifier is `ai.spboucher.orix.convert` or that has a `Contents/Helpers` folder, or an executable sitting17 /// in some `.app/Contents/Helpers`. A real app that lacks a tool reports it missing; it never borrows one from18 /// a source tree that happens to exist on the machine.19 public static func searchDirectories() -> [URL] {20 searchDirectories(executable: Bundle.main.executableURL ?? URL(fileURLWithPath: CommandLine.arguments.first ?? "/"),21 mainBundle: Bundle.main.bundleURL, bundleIdentifier: Bundle.main.bundleIdentifier, environment: ProcessInfo.processInfo.environment)22 }2324 public static let applicationBundleIdentifier = "ai.spboucher.orix.convert"2526 /// The rule of `searchDirectories()`, with its inputs explicit (tests).27 static func searchDirectories(executable: URL, mainBundle: URL, bundleIdentifier: String?, environment: [String: String], sourceFile: String = #filePath) -> [URL] {28 var dirs: [URL] = []29 func add(_ url: URL) { if !dirs.contains(where: { $0.standardizedFileURL.path == url.standardizedFileURL.path }) { dirs.append(url) } }30 if let env = environment["ORIX_CONVERT_TOOLS"], !env.isEmpty { add(URL(fileURLWithPath: env, isDirectory: true)) }31 let executableDirectory = executable.resolvingSymlinksInPath().deletingLastPathComponent()32 let components = executableDirectory.pathComponents33 // …/X.app/Contents/Helpers/<tool>: the helpers folder the executable itself lives in.34 let inHelpers = components.count >= 3 && components.last == "Helpers" && components[components.count - 2] == "Contents"35 && components[components.count - 3].hasSuffix(".app")36 if inHelpers { add(executableDirectory) }37 let helpers = mainBundle.appendingPathComponent("Contents/Helpers", isDirectory: true)38 let isApplication = mainBundle.pathExtension == "app"39 if isApplication { add(helpers) }40 let shipped = inHelpers || (isApplication && (bundleIdentifier == applicationBundleIdentifier || FileManager.default.fileExists(atPath: helpers.path)))41 guard !shipped else { return dirs }42 var dir = URL(fileURLWithPath: sourceFile).deletingLastPathComponent()43 for _ in 0..<8 {44 let candidate = dir.appendingPathComponent("EmbeddedEngines/tools", isDirectory: true)45 if FileManager.default.fileExists(atPath: candidate.path) { add(candidate); break }46 dir = dir.deletingLastPathComponent()47 }48 return dirs49 }5051 /// URL of a bundled executable given its path relative to the tools directory52 /// (e.g. `ffmpeg`, `pandoc`, `LibreOffice.app/Contents/MacOS/soffice`), or `nil` when it is not bundled.53 public static func url(for relativePath: String) -> URL? {54 for dir in searchDirectories() {55 let url = dir.appendingPathComponent(relativePath)56 if FileManager.default.isExecutableFile(atPath: url.path) { return url }57 }58 return nil59 }6061 public static func require(_ relativePath: String) throws -> URL {62 guard let url = url(for: relativePath) else {63 throw ConversionError.engineUnavailable("\(relativePath) is not present in this build of ORIX Convert.")64 }65 return url66 }67}6869public struct ProcessResult: Sendable {70 public let status: Int3271 public let stdout: Data72 public let stderr: Data73 public var stdoutString: String { String(decoding: stdout, as: UTF8.self) }74 public var stderrString: String { String(decoding: stderr, as: UTF8.self) }75 /// Last non-empty lines of stderr, for error messages.76 public func stderrTail(_ lines: Int = 6) -> String {77 stderrString.split(whereSeparator: \.isNewline).suffix(lines).joined(separator: "\n")78 }79}8081/// Runs a bundled helper with a minimal environment, a working directory, a time limit and cooperative cancellation.82public enum ProcessRunner {83 private final class Buffer: @unchecked Sendable {84 private let lock = NSLock()85 private var data = Data()86 private let limit: Int87 init(limit: Int) { self.limit = limit }88 func append(_ chunk: Data) {89 lock.lock(); defer { lock.unlock() }90 if data.count < limit { data.append(chunk.prefix(limit - data.count)) }91 }92 var value: Data { lock.lock(); defer { lock.unlock() }; return data }93 }9495 /// - Parameters:96 /// - environment: added on top of a minimal base (`PATH=/usr/bin:/bin`, `HOME`, `TMPDIR`, `LANG`). The97 /// user's shell environment is not inherited.98 /// - onStderrLine / onStdoutLine: called for each complete line (e.g. to parse ffmpeg `-progress`).99 /// - captureLimit: bytes of each stream kept in memory.100 public static func run(_ executable: URL, arguments: [String], workingDirectory: URL? = nil,101 environment: [String: String] = [:], stdin: Data? = nil, timeout: TimeInterval? = nil,102 captureLimit: Int = 8 << 20,103 onStdoutLine: (@Sendable (String) -> Void)? = nil,104 onStderrLine: (@Sendable (String) -> Void)? = nil) async throws -> ProcessResult {105 try Task.checkCancellation()106 let process = Process()107 process.executableURL = executable108 process.arguments = arguments109 if let workingDirectory { process.currentDirectoryURL = workingDirectory }110 var env: [String: String] = [111 "PATH": "/usr/bin:/bin:/usr/sbin:/sbin",112 "HOME": NSHomeDirectory(),113 "TMPDIR": NSTemporaryDirectory(),114 "LANG": "en_US.UTF-8",115 "LC_ALL": "en_US.UTF-8",116 ]117 for (k, v) in environment { env[k] = v }118 process.environment = env119120 let outPipe = Pipe(), errPipe = Pipe()121 process.standardOutput = outPipe122 process.standardError = errPipe123 let inPipe: Pipe? = stdin == nil ? nil : Pipe()124 process.standardInput = inPipe ?? FileHandle.nullDevice125126 let outBuffer = Buffer(limit: captureLimit), errBuffer = Buffer(limit: captureLimit)127 let outLines = LineSplitter(onStdoutLine), errLines = LineSplitter(onStderrLine)128 let group = DispatchGroup()129 group.enter(); group.enter()130 outPipe.fileHandleForReading.readabilityHandler = { handle in131 let chunk = handle.availableData132 if chunk.isEmpty { handle.readabilityHandler = nil; outLines.finish(); group.leave() } else { outBuffer.append(chunk); outLines.feed(chunk) }133 }134 errPipe.fileHandleForReading.readabilityHandler = { handle in135 let chunk = handle.availableData136 if chunk.isEmpty { handle.readabilityHandler = nil; errLines.finish(); group.leave() } else { errBuffer.append(chunk); errLines.feed(chunk) }137 }138139 let timedOut = Flag()140 return try await withTaskCancellationHandler {141 try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<ProcessResult, Error>) in142 process.terminationHandler = { finished in143 group.notify(queue: .global()) {144 if timedOut.isSet {145 continuation.resume(throwing: ConversionError.limitExceeded("\(executable.lastPathComponent) exceeded its time limit."))146 } else {147 continuation.resume(returning: ProcessResult(status: finished.terminationStatus, stdout: outBuffer.value, stderr: errBuffer.value))148 }149 }150 }151 do {152 try process.run()153 } catch {154 outPipe.fileHandleForReading.readabilityHandler = nil155 errPipe.fileHandleForReading.readabilityHandler = nil156 process.terminationHandler = nil157 continuation.resume(throwing: ConversionError.engineUnavailable("\(executable.lastPathComponent) could not be started: \(error.localizedDescription)"))158 return159 }160 if let inPipe, let stdin {161 DispatchQueue.global().async {162 try? inPipe.fileHandleForWriting.write(contentsOf: stdin)163 try? inPipe.fileHandleForWriting.close()164 }165 }166 if let timeout {167 DispatchQueue.global().asyncAfter(deadline: .now() + timeout) {168 if process.isRunning { timedOut.set(); process.terminate() }169 }170 }171 if Task.isCancelled, process.isRunning { process.terminate() }172 }173 } onCancel: {174 if process.isRunning { process.terminate() }175 }176 }177178 /// Like `run`, but throws `ConversionError.toolFailed` on a non-zero status and `CancellationError` if the task179 /// was cancelled while the tool ran.180 @discardableResult181 public static func runChecked(_ executable: URL, arguments: [String], workingDirectory: URL? = nil,182 environment: [String: String] = [:], stdin: Data? = nil, timeout: TimeInterval? = nil,183 onStdoutLine: (@Sendable (String) -> Void)? = nil,184 onStderrLine: (@Sendable (String) -> Void)? = nil) async throws -> ProcessResult {185 let result = try await run(executable, arguments: arguments, workingDirectory: workingDirectory, environment: environment,186 stdin: stdin, timeout: timeout, onStdoutLine: onStdoutLine, onStderrLine: onStderrLine)187 try Task.checkCancellation()188 guard result.status == 0 else {189 throw ConversionError.toolFailed(tool: executable.lastPathComponent, status: result.status, message: result.stderrTail())190 }191 return result192 }193194 private final class Flag: @unchecked Sendable {195 private let lock = NSLock()196 private var value = false197 func set() { lock.lock(); value = true; lock.unlock() }198 var isSet: Bool { lock.lock(); defer { lock.unlock() }; return value }199 }200201 private final class LineSplitter: @unchecked Sendable {202 private let lock = NSLock()203 private var pending = Data()204 private let callback: (@Sendable (String) -> Void)?205 init(_ callback: (@Sendable (String) -> Void)?) { self.callback = callback }206 func feed(_ chunk: Data) {207 guard let callback else { return }208 lock.lock()209 pending.append(chunk)210 var lines: [String] = []211 while let i = pending.firstIndex(where: { $0 == 0x0A || $0 == 0x0D }) {212 let line = pending[pending.startIndex..<i]213 if !line.isEmpty { lines.append(String(decoding: line, as: UTF8.self)) }214 pending.removeSubrange(pending.startIndex...i)215 }216 lock.unlock()217 lines.forEach(callback)218 }219 func finish() {220 guard let callback else { return }221 lock.lock(); let rest = pending; pending = Data(); lock.unlock()222 if !rest.isEmpty { callback(String(decoding: rest, as: UTF8.self)) }223 }224 }225}226