diff options
| author | gigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com> | 2026-10-14 20:18:20 +0530 |
|---|---|---|
| committer | gigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com> | 2026-10-14 20:18:20 +0530 |
| commit | aceca8b5dfc8edd378ee9ff891bccb0f94c69f31 (patch) | |
| tree | 08401ce8d050afbbe77514f479601a8e9535f4ec /Sources/BubombCore/Executors/ShellCommandExecutor.swift | |
Diffstat (limited to 'Sources/BubombCore/Executors/ShellCommandExecutor.swift')
| -rw-r--r-- | Sources/BubombCore/Executors/ShellCommandExecutor.swift | 63 |
1 files changed, 63 insertions, 0 deletions
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() + } +} |
