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