Sources/OrgPrograms/BabelRunner.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgPrograms/BabelRunner.swift history · blame · raw

132 lines · 7782 bytes

5 symbols in this file
  1#if os(macOS)
  2import Foundation
  3import OrgCore
  4
  5/// Runs Babel jobs as processes, in the file's folder or `:dir`: the interpreter reads the
  6/// program on standard input, or from the file `job.script` is written to.
  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", "/Library/TeX/texbin", "/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    /// Whether `program` is an executable file on `environment`'s PATH, or the path of one.
 22    public static func installed(_ program: String) -> Bool {
 23        let paths = program.contains("/") ? [program] : (environment["PATH"] ?? "").split(separator: ":").map { "\($0)/\(program)" }
 24        return paths.contains { FileManager.default.isExecutableFile(atPath: $0) }
 25    }
 26
 27    /// The words `/bin/sh` makes of `command`, after expanding `~`, variables and quotes. Empty for
 28    /// a command substitution, which would otherwise run here as well as when the block runs.
 29    public static func words(_ command: String) -> [String] {
 30        if command.contains("$(") || command.contains("`") { return [] }
 31        guard command.contains(where: { "~$'\"`\\".contains($0) }) else { return command.split(whereSeparator: \.isWhitespace).map(String.init) }
 32        let process = Process()
 33        process.executableURL = URL(fileURLWithPath: "/bin/sh")
 34        process.arguments = ["-c", "printf '%s\\0' " + command]
 35        process.environment = environment
 36        let out = Pipe()
 37        process.standardOutput = out
 38        process.standardError = FileHandle.nullDevice
 39        guard (try? process.run()) != nil else { return [] }
 40        let data = out.fileHandleForReading.readDataToEndOfFile()
 41        process.waitUntilExit()
 42        return String(decoding: data, as: UTF8.self).split(separator: "\0").map(String.init)
 43    }
 44
 45    public static func run(_ job: BabelJob, fileDirectory: URL, timeout: Duration = .seconds(300)) async throws -> BabelOutput {
 46        for programs in job.programs where !programs.contains(where: installed) {
 47            let names = programs.count == 1 ? programs[0] : "Neither " + programs.joined(separator: " nor ")
 48            throw Failure(description: "\(names) \(programs.count == 1 ? "isn't" : "is") installed, so \(job.language) blocks can't run.")
 49        }
 50        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-babel-\(UUID().uuidString)")
 51        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 52        defer { try? FileManager.default.removeItem(at: folder) }
 53        let resultFile = folder.appendingPathComponent("result")
 54        var input = job.input.replacingOccurrences(of: Babel.resultFileToken, with: resultFile.path)
 55        for (token, contents) in job.dataFiles {
 56            let file = folder.appendingPathComponent("sql-data-\(token.filter(\.isNumber))")
 57            try contents.write(to: file, atomically: true, encoding: .utf8)
 58            input = input.replacingOccurrences(of: token, with: file.path)
 59        }
 60        if case .session(let name, let executable, let kind) = job.runner {
 61            let directory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: fileDirectory).standardizedFileURL } ?? fileDirectory
 62            return try await BabelSessions.shared.run(job, name: name, executable: executable, kind: kind, directory: directory, resultFile: resultFile)
 63        }
 64
 65        let process = Process()
 66        process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
 67        process.environment = environment
 68        switch job.runner {
 69        case .process(let executable, var arguments):
 70            if let script = job.script {
 71                let file = folder.appendingPathComponent("script")
 72                try script.write(to: file, atomically: true, encoding: .utf8)
 73                try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path)
 74                arguments = arguments.map { $0.replacingOccurrences(of: Babel.scriptFileToken, with: file.path) }
 75            }
 76            // In the shell, as Org runs it, so `:cmd "node --no-warnings"` or `~/bin/node` works.
 77            process.arguments = ["/bin/sh", "-c", executable + " \"$@\"", "sh"] + arguments
 78        case .emacs:
 79            // `Programs` runs these natively when Emacs is missing.
 80            let script = folder.appendingPathComponent("babel.el")
 81            try input.write(to: script, atomically: true, encoding: .utf8)
 82            process.arguments = [EmacsRunner.executable()?.path ?? "emacs", "-Q", "--batch", "-l", script.path]
 83        case .session:
 84            return BabelOutput(stdout: "")
 85        }
 86        let directory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: fileDirectory).standardizedFileURL } ?? fileDirectory
 87        guard FileManager.default.fileExists(atPath: directory.path) else { throw Failure(description: "No folder \(directory.path) for :dir.") }
 88        process.currentDirectoryURL = directory
 89        // As Emacs's `call-process` does, so `pwd` prints the folder as written, not resolved.
 90        process.environment?["PWD"] = directory.path
 91        let stdout = folder.appendingPathComponent("stdout")
 92        FileManager.default.createFile(atPath: stdout.path, contents: nil)
 93        let out = try FileHandle(forWritingTo: stdout)
 94        let stderr = folder.appendingPathComponent("stderr")
 95        FileManager.default.createFile(atPath: stderr.path, contents: nil)
 96        let err = try FileHandle(forWritingTo: stderr)
 97        // The input from a file, as `org-babel-eval` gives it.
 98        let stdin = folder.appendingPathComponent("stdin")
 99        if case .process = job.runner { try input.write(to: stdin, atomically: true, encoding: .utf8) } else { FileManager.default.createFile(atPath: stdin.path, contents: nil) }
100        process.standardInput = try FileHandle(forReadingFrom: stdin)
101        process.standardOutput = out
102        process.standardError = err
103        do {
104            try process.run()
105        } catch {
106            throw Failure(description: "Can't start \(process.arguments?.first ?? "the interpreter"): \(error.localizedDescription)")
107        }
108        let deadline = ContinuousClock.now + timeout
109        while process.isRunning {
110            if ContinuousClock.now > deadline {
111                process.terminate()
112                throw Failure(description: "The block took longer than \(timeout) and was stopped.")
113            }
114            do {
115                try await Task.sleep(for: .milliseconds(30))
116            } catch {
117                process.terminate()
118                throw CancellationError()
119            }
120        }
121        try out.close()
122        try err.close()
123        let output = (try? String(contentsOf: stdout, encoding: .utf8)) ?? ""
124        let errors = (try? String(contentsOf: stderr, encoding: .utf8)) ?? ""
125        let result = try? String(contentsOf: resultFile, encoding: .utf8)
126        if case .process(let executable, _) = job.runner, job.programs.isEmpty, process.terminationStatus == 127, output.isEmpty {
127            throw Failure(description: "\(executable) isn't installed.")
128        }
129        return BabelOutput(stdout: output, resultFile: result, stderr: errors, status: process.terminationStatus)
130    }
131}
132#endif