summaryrefslogtreecommitdiff
path: root/Sources/BubombCore/Executors/SequenceExecutor.swift
blob: 29a03315d5cce653068c0a39850c3838c503f182 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
    }
}