diff options
Diffstat (limited to 'Sources/BubombCore/Executors')
| -rw-r--r-- | Sources/BubombCore/Executors/ApplicationLauncher.swift | 78 | ||||
| -rw-r--r-- | Sources/BubombCore/Executors/ExecutionResult.swift | 21 | ||||
| -rw-r--r-- | Sources/BubombCore/Executors/PayloadExecutor.swift | 242 | ||||
| -rw-r--r-- | Sources/BubombCore/Executors/ProcessRunner.swift | 219 | ||||
| -rw-r--r-- | Sources/BubombCore/Executors/ScriptExecutor.swift | 77 | ||||
| -rw-r--r-- | Sources/BubombCore/Executors/SequenceExecutor.swift | 131 | ||||
| -rw-r--r-- | Sources/BubombCore/Executors/ShellCommandExecutor.swift | 63 | ||||
| -rw-r--r-- | Sources/BubombCore/Executors/URLLauncher.swift | 45 |
8 files changed, 876 insertions, 0 deletions
diff --git a/Sources/BubombCore/Executors/ApplicationLauncher.swift b/Sources/BubombCore/Executors/ApplicationLauncher.swift new file mode 100644 index 0000000..27bfd1b --- /dev/null +++ b/Sources/BubombCore/Executors/ApplicationLauncher.swift @@ -0,0 +1,78 @@ +import Foundation +#if canImport(AppKit) +import AppKit +#endif + +/// Launches macOS applications safely using native APIs. +public final class ApplicationLauncher: Sendable { + public init() {} + + public func launch(appPath: String, arguments: [String] = []) async throws -> ExecutionResult { + let startTime = Date() + let validatedPath = try PathValidator.validateApplication(at: appPath).get() + let appURL = URL(fileURLWithPath: validatedPath) + + #if canImport(AppKit) + let config = NSWorkspace.OpenConfiguration() + if !arguments.isEmpty { + config.arguments = arguments + } + + do { + _ = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<NSRunningApplication, Error>) in + NSWorkspace.shared.openApplication(at: appURL, configuration: config) { app, error in + if let error = error { + continuation.resume(throwing: error) + } else if let app = app { + continuation.resume(returning: app) + } else { + continuation.resume(throwing: ExecutionError.applicationLaunchFailed("Application launch failed without error info.")) + } + } + } + let duration = Date().timeIntervalSince(startTime) + return ExecutionResult( + exitCode: 0, + stdout: "Successfully launched application: \(appURL.lastPathComponent)", + stderr: "", + duration: duration + ) + } catch { + // If native NSWorkspace openApplication threw, try /usr/bin/open as fallback + let runner = ProcessRunner() + var args = ["-a", validatedPath] + if !arguments.isEmpty { + args.append("--args") + args.append(contentsOf: arguments) + } + let res = try await runner.run( + executableURL: URL(fileURLWithPath: "/usr/bin/open"), + arguments: args + ) + return ExecutionResult( + exitCode: res.exitCode, + stdout: "Launched via open tool: \(appURL.lastPathComponent)", + stderr: res.stderr, + duration: Date().timeIntervalSince(startTime) + ) + } + #else + let runner = ProcessRunner() + var args = ["-a", validatedPath] + if !arguments.isEmpty { + args.append("--args") + args.append(contentsOf: arguments) + } + let res = try await runner.run( + executableURL: URL(fileURLWithPath: "/usr/bin/open"), + arguments: args + ) + return ExecutionResult( + exitCode: res.exitCode, + stdout: "Launched via open tool: \(appURL.lastPathComponent)", + stderr: res.stderr, + duration: Date().timeIntervalSince(startTime) + ) + #endif + } +} diff --git a/Sources/BubombCore/Executors/ExecutionResult.swift b/Sources/BubombCore/Executors/ExecutionResult.swift new file mode 100644 index 0000000..2abfa60 --- /dev/null +++ b/Sources/BubombCore/Executors/ExecutionResult.swift @@ -0,0 +1,21 @@ +import Foundation + +/// Output result from any single executor. +public struct ExecutionResult: Sendable { + public var exitCode: Int? + public var stdout: String + public var stderr: String + public var duration: TimeInterval + + public init( + exitCode: Int? = 0, + stdout: String = "", + stderr: String = "", + duration: TimeInterval = 0 + ) { + self.exitCode = exitCode + self.stdout = stdout + self.stderr = stderr + self.duration = duration + } +} diff --git a/Sources/BubombCore/Executors/PayloadExecutor.swift b/Sources/BubombCore/Executors/PayloadExecutor.swift new file mode 100644 index 0000000..2142934 --- /dev/null +++ b/Sources/BubombCore/Executors/PayloadExecutor.swift @@ -0,0 +1,242 @@ +import Foundation +import Combine + +/// Lifecycle state during payload detonation. +public enum DetonationState: Equatable, Sendable { + case idle + case burning(payloadName: String, progressInfo: String?) + case exploded(record: ExecutionRecord) + case failed(record: ExecutionRecord) + + public var isRunning: Bool { + if case .burning = self { return true } + return false + } +} + +/// Central coordinator for executing payloads safely, preventing duplicates, +/// broadcasting state changes, and recording history. +@MainActor +public final class PayloadExecutor: ObservableObject { + public static let shared = PayloadExecutor() + + @Published public private(set) var currentState: DetonationState = .idle + + private let settingsStore: SettingsStore + private var currentShellExecutor: ShellCommandExecutor? + private var currentScriptExecutor: ScriptExecutor? + private var currentSequenceExecutor: SequenceExecutor? + + public init(settingsStore: SettingsStore = .shared) { + self.settingsStore = settingsStore + } + + /// Detonates a payload immediately. + /// - Parameters: + /// - payload: The payload to execute. If nil, uses the store's activePayload. + /// - ignoreSafetyConfirmation: Set to true only after the user explicitly confirmed a destructive action dialog. + /// - Returns: The resulting ExecutionRecord. + @discardableResult + public func detonate( + payload: Payload? = nil, + ignoreSafetyConfirmation: Bool = false + ) async throws -> ExecutionRecord { + let targetPayload: Payload + if let p = payload { + targetPayload = p + } else if let active = settingsStore.settings.activePayload { + targetPayload = active + } else { + let error = ExecutionError.noPayloadConfigured + let dummyRecord = ExecutionRecord( + payloadId: UUID(), + payloadName: "None", + payloadTypeDescription: "None", + startedAt: Date(), + finishedAt: Date(), + duration: 0, + status: .failed, + errorMessage: error.localizedDescription + ) + self.currentState = .failed(record: dummyRecord) + throw error + } + + // Validate payload before launching + do { + try targetPayload.validate() + } catch let err as ExecutionError { + let record = ExecutionRecord( + payloadId: targetPayload.id, + payloadName: targetPayload.name, + payloadTypeDescription: targetPayload.type.typeDisplayName, + startedAt: Date(), + finishedAt: Date(), + duration: 0, + status: .failed, + errorMessage: err.localizedDescription + ) + settingsStore.addExecutionRecord(record) + self.currentState = .failed(record: record) + throw err + } + + // Safety check + if !ignoreSafetyConfirmation { + let alwaysConfirm = settingsStore.settings.confirmDestructiveActions + let (requiresConfirm, _) = SafetyPolicy.requiresConfirmation( + command: commandStringForPayload(targetPayload), + userSettingAlwaysConfirmDestructive: alwaysConfirm || targetPayload.requiresConfirmation + ) + if requiresConfirm { + throw ExecutionError.destructiveActionRejected + } + } + + // Check duplicate execution + if currentState.isRunning { + throw ExecutionError.duplicateExecution + } + self.currentState = .burning(payloadName: targetPayload.name, progressInfo: "Detonating...") + + let startTime = Date() + + do { + let result = try await executeInternal(payload: targetPayload) + let finishedAt = Date() + let duration = finishedAt.timeIntervalSince(startTime) + + let record = ExecutionRecord( + payloadId: targetPayload.id, + payloadName: targetPayload.name, + payloadTypeDescription: targetPayload.type.typeDisplayName, + startedAt: startTime, + finishedAt: finishedAt, + duration: duration, + status: .succeeded, + exitCode: result.exitCode, + standardOutput: result.stdout, + standardError: result.stderr, + errorMessage: nil + ) + + settingsStore.addExecutionRecord(record) + self.currentState = .exploded(record: record) + + // Reset back to idle after short delay to let animations complete + scheduleIdleReset(delay: 1.2) + return record + + } catch { + let finishedAt = Date() + let duration = finishedAt.timeIntervalSince(startTime) + let errString = error.localizedDescription + let exitCode: Int? + + if case .nonZeroExitStatus(let code, _) = (error as? ExecutionError) { + exitCode = code + } else { + exitCode = nil + } + + let status: ExecutionStatus + if case .timeout = (error as? ExecutionError) { + status = .timedOut + } else if case .cancelled = (error as? ExecutionError) { + status = .cancelled + } else { + status = .failed + } + + let record = ExecutionRecord( + payloadId: targetPayload.id, + payloadName: targetPayload.name, + payloadTypeDescription: targetPayload.type.typeDisplayName, + startedAt: startTime, + finishedAt: finishedAt, + duration: duration, + status: status, + exitCode: exitCode, + standardOutput: "", + standardError: "", + errorMessage: errString + ) + + settingsStore.addExecutionRecord(record) + self.currentState = .failed(record: record) + + scheduleIdleReset(delay: 2.0) + throw error + } + } + + /// Cancels any currently running payload execution. + public func cancel() { + currentShellExecutor?.cancel() + currentScriptExecutor?.cancel() + currentSequenceExecutor?.cancel() + + self.currentState = .idle + } + + // MARK: - Private Helpers + + private func executeInternal(payload: Payload) async throws -> ExecutionResult { + switch payload.type { + case .shellCommand(let config): + let executor = ShellCommandExecutor() + self.currentShellExecutor = executor + defer { self.currentShellExecutor = nil } + return try await executor.execute(config: config) + + case .openApplication(let config): + let launcher = ApplicationLauncher() + return try await launcher.launch(appPath: config.applicationPath, arguments: config.arguments) + + case .openURL(let config): + let launcher = URLLauncher() + return try await launcher.open(urlString: config.urlString) + + case .runScript(let config): + let executor = ScriptExecutor() + self.currentScriptExecutor = executor + defer { self.currentScriptExecutor = nil } + return try await executor.execute(config: config) + + case .sequence(let config): + let executor = SequenceExecutor() + self.currentSequenceExecutor = executor + defer { self.currentSequenceExecutor = nil } + return try await executor.execute(config: config) { [weak self] stepIndex, totalSteps, stepName in + Task { @MainActor [weak self] in + self?.currentState = .burning( + payloadName: payload.name, + progressInfo: "Step \(stepIndex)/\(totalSteps): \(stepName)" + ) + } + } + } + } + + private func commandStringForPayload(_ payload: Payload) -> String { + switch payload.type { + case .shellCommand(let config): + return config.command + case .runScript(let config): + return config.scriptPath + case .sequence(let config): + return config.steps.map { $0.summary }.joined(separator: " && ") + default: + return "" + } + } + + private func scheduleIdleReset(delay: TimeInterval) { + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in + guard let self = self else { return } + if !self.currentState.isRunning { + self.currentState = .idle + } + } + } +} diff --git a/Sources/BubombCore/Executors/ProcessRunner.swift b/Sources/BubombCore/Executors/ProcessRunner.swift new file mode 100644 index 0000000..add19fa --- /dev/null +++ b/Sources/BubombCore/Executors/ProcessRunner.swift @@ -0,0 +1,219 @@ +import Foundation + +/// Safe, asynchronous wrapper around Foundation.Process with deadlock-free pipe reading via readabilityHandler, +/// timeout supervision, and cancellation support. +public final class ProcessRunner: @unchecked Sendable { + private let state = ProcessState() + + public init() {} + + /// Runs an executable process with arguments, environment, working directory, and timeout. + public func run( + executableURL: URL, + arguments: [String], + workingDirectory: String? = nil, + environment: [String: String] = [:], + timeoutSeconds: TimeInterval? = nil + ) async throws -> ExecutionResult { + let startTime = Date() + + let proc = Process() + proc.executableURL = executableURL + proc.arguments = arguments + + if let workDir = workingDirectory, !workDir.isEmpty { + proc.currentDirectoryURL = URL(fileURLWithPath: (workDir as NSString).expandingTildeInPath) + } + + var env = ProcessInfo.processInfo.environment + for (k, v) in environment { + env[k] = v + } + proc.environment = env + + let outPipe = Pipe() + let errPipe = Pipe() + proc.standardOutput = outPipe + proc.standardError = errPipe + + let stdoutAccumulator = ThreadSafeAccumulator() + let stderrAccumulator = ThreadSafeAccumulator() + + outPipe.fileHandleForReading.readabilityHandler = { handle in + let chunk = handle.availableData + if chunk.isEmpty { + outPipe.fileHandleForReading.readabilityHandler = nil + } else { + stdoutAccumulator.append(chunk) + } + } + + errPipe.fileHandleForReading.readabilityHandler = { handle in + let chunk = handle.availableData + if chunk.isEmpty { + errPipe.fileHandleForReading.readabilityHandler = nil + } else { + stderrAccumulator.append(chunk) + } + } + + try await state.setProcess(proc) + + do { + try proc.run() + } catch { + outPipe.fileHandleForReading.readabilityHandler = nil + errPipe.fileHandleForReading.readabilityHandler = nil + _ = await state.clearProcess() + throw ExecutionError.processLaunchFailed(error.localizedDescription) + } + + // Timeout supervisor + let timeoutRef = TimeoutRef() + var timeoutTimer: DispatchSourceTimer? + + if let timeout = timeoutSeconds, timeout > 0 { + let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global(qos: .userInteractive)) + timer.schedule(deadline: .now() + timeout) + timer.setEventHandler { [weak proc] in + timeoutRef.markTimedOut() + proc?.terminate() + + // Force kill if still unresponsive after 500ms + DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { + if let pid = proc?.processIdentifier, proc?.isRunning == true { + kill(pid, SIGKILL) + } + } + } + timer.resume() + timeoutTimer = timer + } + + // Wait for process exit asynchronously on a global queue + await withCheckedContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { + proc.waitUntilExit() + continuation.resume() + } + } + + timeoutTimer?.cancel() + timeoutTimer = nil + + // Clean up readability handlers + outPipe.fileHandleForReading.readabilityHandler = nil + errPipe.fileHandleForReading.readabilityHandler = nil + + // Drain any remaining buffered data + let remainingOut = outPipe.fileHandleForReading.readDataToEndOfFile() + stdoutAccumulator.append(remainingOut) + + let remainingErr = errPipe.fileHandleForReading.readDataToEndOfFile() + stderrAccumulator.append(remainingErr) + + let duration = Date().timeIntervalSince(startTime) + let stdoutString = String(data: stdoutAccumulator.getData(), encoding: .utf8) ?? "" + let stderrString = String(data: stderrAccumulator.getData(), encoding: .utf8) ?? "" + + let wasCancelled = await state.clearProcess() + + if wasCancelled { + throw ExecutionError.cancelled + } + + if timeoutRef.isTimedOut { + throw ExecutionError.timeout(timeoutSeconds ?? 0) + } + + let exitCode = Int(proc.terminationStatus) + if exitCode != 0 { + let combined = stdoutString + (stderrString.isEmpty ? "" : "\n" + stderrString) + throw ExecutionError.nonZeroExitStatus(exitCode, output: combined) + } + + return ExecutionResult( + exitCode: exitCode, + stdout: stdoutString, + stderr: stderrString, + duration: duration + ) + } + + /// Cancels the running process immediately. + public func cancel() { + Task { + let proc = await state.cancel() + if let proc = proc, proc.isRunning { + proc.terminate() + DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { + if proc.isRunning { + kill(proc.processIdentifier, SIGKILL) + } + } + } + } + } +} + +// MARK: - Helper Types + +private actor ProcessState { + private var process: Process? + private var isCancelled = false + + func setProcess(_ proc: Process) throws { + if isCancelled { + throw ExecutionError.cancelled + } + self.process = proc + } + + func cancel() -> Process? { + isCancelled = true + let proc = self.process + self.process = nil + return proc + } + + func clearProcess() -> Bool { + let wasCancelled = self.isCancelled + self.process = nil + return wasCancelled + } +} + +private final class ThreadSafeAccumulator: @unchecked Sendable { + private var data = Data() + private let lock = NSLock() + + func append(_ newChunk: Data) { + guard !newChunk.isEmpty else { return } + lock.lock() + data.append(newChunk) + lock.unlock() + } + + func getData() -> Data { + lock.lock() + defer { lock.unlock() } + return data + } +} + +private final class TimeoutRef: @unchecked Sendable { + private var timedOut = false + private let lock = NSLock() + + var isTimedOut: Bool { + lock.lock() + defer { lock.unlock() } + return timedOut + } + + func markTimedOut() { + lock.lock() + timedOut = true + lock.unlock() + } +} diff --git a/Sources/BubombCore/Executors/ScriptExecutor.swift b/Sources/BubombCore/Executors/ScriptExecutor.swift new file mode 100644 index 0000000..55be037 --- /dev/null +++ b/Sources/BubombCore/Executors/ScriptExecutor.swift @@ -0,0 +1,77 @@ +import Foundation + +/// Executes local scripts safely without mutating file permissions or user scripts. +public final class ScriptExecutor: @unchecked Sendable { + private let runner = ProcessRunner() + + public init() {} + + public func execute(config: ScriptConfig) async throws -> ExecutionResult { + let validPath = try PathValidator.validateScript(at: config.scriptPath).get() + + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + let isExecutable = FileManager.default.isExecutableFile(atPath: validPath) + let (interpreterURL, leadingArgs) = resolveInterpreter(forScriptAt: validPath, isExecutable: isExecutable) + + var finalArgs = leadingArgs + finalArgs.append(validPath) + finalArgs.append(contentsOf: config.arguments) + + return try await runner.run( + executableURL: interpreterURL, + arguments: finalArgs, + workingDirectory: config.workingDirectory, + environment: config.environmentVariables, + timeoutSeconds: config.timeoutSeconds + ) + } + + public func cancel() { + runner.cancel() + } + + /// Determines the appropriate interpreter for a script based on its shebang or file extension. + private func resolveInterpreter(forScriptAt path: String, isExecutable: Bool) -> (interpreterURL: URL, leadingArgs: [String]) { + // First check shebang + if let fileHandle = FileHandle(forReadingAtPath: path) { + defer { try? fileHandle.close() } + let headerData = fileHandle.readData(ofLength: 256) + if let headerString = String(data: headerData, encoding: .utf8), headerString.hasPrefix("#!") { + let firstLine = headerString.components(separatedBy: .newlines).first ?? "" + let shebangBody = firstLine.dropFirst(2).trimmingCharacters(in: .whitespaces) + let tokens = shebangBody.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + if let interpreter = tokens.first { + if interpreter == "/usr/bin/env" && tokens.count > 1 { + let actualBin = tokens[1] + return (URL(fileURLWithPath: "/usr/bin/env"), [actualBin]) + } else if FileManager.default.isExecutableFile(atPath: interpreter) { + return (URL(fileURLWithPath: interpreter), Array(tokens.dropFirst())) + } + } + } + } + + // If file is directly marked executable and no shebang, run directly + if isExecutable { + return (URL(fileURLWithPath: path), []) + } + + // Fallback by extension + let ext = (path as NSString).pathExtension.lowercased() + switch ext { + case "sh", "zsh", "bash": + return (URL(fileURLWithPath: "/bin/zsh"), []) + case "py": + return (URL(fileURLWithPath: "/usr/bin/python3"), []) + case "rb": + return (URL(fileURLWithPath: "/usr/bin/ruby"), []) + case "pl": + return (URL(fileURLWithPath: "/usr/bin/perl"), []) + default: + return (URL(fileURLWithPath: "/bin/sh"), []) + } + } +} diff --git a/Sources/BubombCore/Executors/SequenceExecutor.swift b/Sources/BubombCore/Executors/SequenceExecutor.swift new file mode 100644 index 0000000..29a0331 --- /dev/null +++ b/Sources/BubombCore/Executors/SequenceExecutor.swift @@ -0,0 +1,131 @@ +import Foundation + +/// Executes a sequence of payload steps in defined order with progress updates and failure policies. +public final class SequenceExecutor: @unchecked Sendable { + public typealias ProgressHandler = @Sendable (Int, Int, String) -> Void + + private let state = SequenceState() + + public init() {} + + public func execute( + config: SequenceConfig, + progress: ProgressHandler? = nil + ) async throws -> ExecutionResult { + let startTime = Date() + let totalSteps = config.steps.count + guard totalSteps > 0 else { + throw ExecutionError.invalidConfiguration("Sequence has no steps configured.") + } + + var fullStdout = "" + var fullStderr = "" + + for (index, step) in config.steps.enumerated() { + if await state.checkCancelled() { + throw ExecutionError.cancelled + } + + progress?(index + 1, totalSteps, step.name) + + let stepHeader = "--- [Step \(index + 1)/\(totalSteps): \(step.name)] ---\n" + fullStdout += stepHeader + + do { + let result = try await executeStep(step) + if !result.stdout.isEmpty { + fullStdout += result.stdout + (result.stdout.hasSuffix("\n") ? "" : "\n") + } + if !result.stderr.isEmpty { + fullStderr += "[\(step.name) stderr]: " + result.stderr + (result.stderr.hasSuffix("\n") ? "" : "\n") + } + } catch { + let errString = error.localizedDescription + let failureLog = "❌ Step \(index + 1) failed: \(errString)\n" + fullStderr += failureLog + + if config.stopOnError { + throw ExecutionError.stepFailed(stepIndex: index, stepName: step.name, reason: errString) + } + } + } + + let duration = Date().timeIntervalSince(startTime) + return ExecutionResult( + exitCode: 0, + stdout: fullStdout, + stderr: fullStderr, + duration: duration + ) + } + + private func executeStep(_ step: SequenceStep) async throws -> ExecutionResult { + switch step.action { + case .openApplication(let appPath): + let launcher = ApplicationLauncher() + return try await launcher.launch(appPath: appPath) + + case .openURL(let urlString): + let launcher = URLLauncher() + return try await launcher.open(urlString: urlString) + + case .runCommand(let cmd, let workDir, let timeout): + let executor = ShellCommandExecutor() + await state.setShell(executor) + defer { + Task { await self.state.setShell(nil) } + } + let shellConfig = ShellConfig( + command: cmd, + shellPath: "/bin/zsh", + workingDirectory: workDir, + timeoutSeconds: timeout + ) + return try await executor.execute(config: shellConfig) + + case .runScript(let scriptPath, let args, let workDir, let timeout): + let executor = ScriptExecutor() + await state.setScript(executor) + defer { + Task { await self.state.setScript(nil) } + } + let scriptConfig = ScriptConfig( + scriptPath: scriptPath, + arguments: args, + workingDirectory: workDir, + timeoutSeconds: timeout + ) + return try await executor.execute(config: scriptConfig) + } + } + + public func cancel() { + Task { + await state.cancel() + } + } +} + +private actor SequenceState { + private var isCancelled = false + private var shellExecutor: ShellCommandExecutor? + private var scriptExecutor: ScriptExecutor? + + func setShell(_ executor: ShellCommandExecutor?) { + self.shellExecutor = executor + } + + func setScript(_ executor: ScriptExecutor?) { + self.scriptExecutor = executor + } + + func cancel() { + self.isCancelled = true + shellExecutor?.cancel() + scriptExecutor?.cancel() + } + + func checkCancelled() -> Bool { + return isCancelled + } +} diff --git a/Sources/BubombCore/Executors/ShellCommandExecutor.swift b/Sources/BubombCore/Executors/ShellCommandExecutor.swift new file mode 100644 index 0000000..36c606b --- /dev/null +++ b/Sources/BubombCore/Executors/ShellCommandExecutor.swift @@ -0,0 +1,63 @@ +import Foundation + +/// Executes shell commands using an explicit shell or direct binary invocation. +public final class ShellCommandExecutor: @unchecked Sendable { + private let runner = ProcessRunner() + + public init() {} + + public func execute(config: ShellConfig) async throws -> ExecutionResult { + // Validate working directory if specified + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + let trimmedCommand = config.command.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedCommand.isEmpty else { + throw ExecutionError.invalidConfiguration("Command cannot be empty.") + } + + let executableURL: URL + let arguments: [String] + + let shell = config.shellPath.trimmingCharacters(in: .whitespacesAndNewlines) + if !shell.isEmpty { + // Validate shell executable exists + let validShell = try PathValidator.validateExecutable(at: shell).get() + executableURL = URL(fileURLWithPath: validShell) + + var fullCommand = trimmedCommand + if !config.arguments.isEmpty { + let appended = config.arguments.map { arg -> String in + if arg.contains(" ") || arg.contains("\"") { + return "\"\(arg.replacingOccurrences(of: "\"", with: "\\\""))\"" + } + return arg + }.joined(separator: " ") + fullCommand += " " + appended + } + arguments = ["-c", fullCommand] + } else { + // Direct binary invocation + let components = trimmedCommand.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + guard let binaryName = components.first else { + throw ExecutionError.invalidConfiguration("No binary specified.") + } + let validBinary = try PathValidator.validateExecutable(at: binaryName).get() + executableURL = URL(fileURLWithPath: validBinary) + arguments = Array(components.dropFirst()) + config.arguments + } + + return try await runner.run( + executableURL: executableURL, + arguments: arguments, + workingDirectory: config.workingDirectory, + environment: config.environmentVariables, + timeoutSeconds: config.timeoutSeconds + ) + } + + public func cancel() { + runner.cancel() + } +} diff --git a/Sources/BubombCore/Executors/URLLauncher.swift b/Sources/BubombCore/Executors/URLLauncher.swift new file mode 100644 index 0000000..c56e121 --- /dev/null +++ b/Sources/BubombCore/Executors/URLLauncher.swift @@ -0,0 +1,45 @@ +import Foundation +#if canImport(AppKit) +import AppKit +#endif + +/// Validates and opens URLs in the user's default web browser. +public final class URLLauncher: Sendable { + public init() {} + + public func open(urlString: String) async throws -> ExecutionResult { + let startTime = Date() + let validatedURL = try PathValidator.validateURL(urlString).get() + + var success = false + + #if canImport(AppKit) + success = await MainActor.run { + NSWorkspace.shared.open(validatedURL) + } + #endif + + if !success { + // Fallback to /usr/bin/open if NSWorkspace is not available or failed + let runner = ProcessRunner() + let result = try await runner.run( + executableURL: URL(fileURLWithPath: "/usr/bin/open"), + arguments: [validatedURL.absoluteString] + ) + return ExecutionResult( + exitCode: result.exitCode, + stdout: "Opened \(validatedURL.absoluteString) via open tool", + stderr: result.stderr, + duration: Date().timeIntervalSince(startTime) + ) + } + + let duration = Date().timeIntervalSince(startTime) + return ExecutionResult( + exitCode: 0, + stdout: "Successfully opened URL: \(validatedURL.absoluteString)", + stderr: "", + duration: duration + ) + } +} |
