Sources/OrgApp/BabelRunner.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgApp/BabelRunner.swift history · blame · raw

99 lines · 5079 bytes

 1#if os(macOS)
 2import Foundation
 3import OrgCore
 4
 5/// Runs Babel jobs as processes: the interpreter reads the program on standard input, in the
 6/// file's folder or `:dir`.
 7public enum BabelRunner {
 8    public struct Failure: Error, CustomStringConvertible {
 9        public let description: String
10    }
11
12    /// PATH with the usual install locations, which an app launched from the Dock lacks.
13    public static var environment: [String: String] {
14        var environment = ProcessInfo.processInfo.environment
15        let extra = ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"]
16        let path = (environment["PATH"] ?? "").split(separator: ":").map(String.init)
17        environment["PATH"] = (path + extra.filter { !path.contains($0) }).joined(separator: ":")
18        return environment
19    }
20
21    public static func run(_ job: BabelJob, fileDirectory: URL, timeout: Duration = .seconds(300)) async throws -> BabelOutput {
22        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-babel-\(UUID().uuidString)")
23        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
24        defer { try? FileManager.default.removeItem(at: folder) }
25        let resultFile = folder.appendingPathComponent("result")
26        let input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path)
27        if case .session(let name, let executable, let python) = job.runner {
28            let directory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: fileDirectory).standardizedFileURL } ?? fileDirectory
29            return try await BabelSessions.shared.run(job, name: name, executable: executable, python: python, directory: directory, resultFile: resultFile)
30        }
31
32        let process = Process()
33        process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
34        process.environment = environment
35        let stdin = Pipe()
36        switch job.runner {
37        case .process(let executable, let arguments):
38            process.arguments = [executable] + arguments
39        case .emacs:
40            guard let emacs = EmacsRunner.executable() else { throw Failure(description: "Emacs isn't installed, so Emacs Lisp blocks can't run.") }
41            let script = folder.appendingPathComponent("babel.el")
42            try input.write(to: script, atomically: true, encoding: .utf8)
43            process.arguments = [emacs.path, "-Q", "--batch", "-l", script.path]
44        case .session:
45            return BabelOutput(stdout: "")
46        }
47        let directory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: fileDirectory).standardizedFileURL } ?? fileDirectory
48        guard FileManager.default.fileExists(atPath: directory.path) else { throw Failure(description: "No folder \(directory.path) for :dir.") }
49        process.currentDirectoryURL = directory
50        let stdout = folder.appendingPathComponent("stdout")
51        FileManager.default.createFile(atPath: stdout.path, contents: nil)
52        let out = try FileHandle(forWritingTo: stdout)
53        let stderr = folder.appendingPathComponent("stderr")
54        FileManager.default.createFile(atPath: stderr.path, contents: nil)
55        let err = try FileHandle(forWritingTo: stderr)
56        process.standardInput = stdin
57        process.standardOutput = out
58        process.standardError = err
59        do {
60            try process.run()
61        } catch {
62            throw Failure(description: "Can't start \(process.arguments?.first ?? "the interpreter"): \(error.localizedDescription)")
63        }
64        if case .process = job.runner {
65            let handle = stdin.fileHandleForWriting
66            let data = Data(input.utf8)
67            // Large programs would fill the pipe; write off the main thread.
68            Task.detached {
69                try? handle.write(contentsOf: data)
70                try? handle.close()
71            }
72        } else {
73            try stdin.fileHandleForWriting.close()
74        }
75        let deadline = ContinuousClock.now + timeout
76        while process.isRunning {
77            if ContinuousClock.now > deadline {
78                process.terminate()
79                throw Failure(description: "The block took longer than \(timeout) and was stopped.")
80            }
81            do {
82                try await Task.sleep(for: .milliseconds(30))
83            } catch {
84                process.terminate()
85                throw CancellationError()
86            }
87        }
88        try out.close()
89        try err.close()
90        let output = (try? String(contentsOf: stdout, encoding: .utf8)) ?? ""
91        let errors = (try? String(contentsOf: stderr, encoding: .utf8)) ?? ""
92        let result = try? String(contentsOf: resultFile, encoding: .utf8)
93        if case .process(let executable, _) = job.runner, process.terminationStatus == 127, output.isEmpty {
94            throw Failure(description: "\(executable) isn't installed.")
95        }
96        return BabelOutput(stdout: output, resultFile: result, stderr: errors, status: process.terminationStatus)
97    }
98}
99#endif