Commit bff4593da6
Verified · cmc
Layout: unified · split
Package.swift +4 −1
| @@ -93,7 +93,9 @@ let package = Package( | ||
| 93 | 93 | // The watch app and its complications, bundled by scripts/build-watch-app.sh. |
| 94 | 94 | .executableTarget(name: "OrgstarWatch", dependencies: ["OrgWatchData"]), |
| 95 | 95 | .executableTarget(name: "OrgstarWatchWidgets", dependencies: ["OrgWatchData"]), |
| 96 | .executableTarget(name: "Orgstar", dependencies: ["OrgApp", "OrgEditorAppKit", "OrgHighlight", .product(name: "Sparkle", package: "Sparkle")]), | |
| 96 | // Babel, Emacs and gnuplot as processes; the Developer ID app alone links it. | |
| 97 | .target(name: "OrgPrograms", dependencies: ["OrgApp"]), | |
| 98 | .executableTarget(name: "Orgstar", dependencies: ["OrgApp", "OrgPrograms", "OrgEditorAppKit", "OrgHighlight", .product(name: "Sparkle", package: "Sparkle")]), | |
| 97 | 99 | // The iOS app, bundled by scripts/build-ios-app.sh. |
| 98 | 100 | .executableTarget(name: "OrgstarMobile", dependencies: ["OrgApp", "OrgHighlight"]), |
| 99 | 101 | // App extensions, bundled into orgstar.app by scripts/build-app.sh. |
| @@ -112,6 +114,7 @@ let package = Package( | ||
| 112 | 114 | .testTarget(name: "OrgPresentationTests", dependencies: ["OrgPresentation"]), |
| 113 | 115 | .testTarget(name: "OrgEditorAppKitTests", dependencies: ["OrgEditorAppKit", "OrgApp"]), |
| 114 | 116 | .testTarget(name: "OrgAppTests", dependencies: ["OrgApp", "OrgDocument"]), |
| 117 | .testTarget(name: "OrgProgramsTests", dependencies: ["OrgPrograms", "OrgApp", "OrgDocument"]), | |
| 115 | 118 | .testTarget(name: "OrgHighlightTests", dependencies: ["OrgHighlight", "OrgCore", "OrgPresentation"]) |
| 116 | 119 | ] |
| 117 | 120 | ) |
Sources/OrgApp/DocumentSession.swift +17 −10
| @@ -877,7 +877,13 @@ public final class DocumentSession { | ||
| 877 | 877 | /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table |
| 878 | 878 | /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area. |
| 879 | 879 | public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String { |
| 880 | #if os(macOS) | |
| 880 | guard let programs = Self.runner else { | |
| 881 | #if os(macOS) | |
| 882 | return "Tables that need Emacs aren't recalculated in this version of orgstar." | |
| 883 | #else | |
| 884 | return "Tables that need Emacs aren't recalculated on iOS." | |
| 885 | #endif | |
| 886 | } | |
| 881 | 887 | guard let entry = current else { return "No file is open." } |
| 882 | 888 | let path = entry.path |
| 883 | 889 | let snapshot = entry.buffer.document.text as NSString |
| @@ -885,7 +891,7 @@ public final class DocumentSession { | ||
| 885 | 891 | let old = snapshot.substring(with: NSRange(table)) |
| 886 | 892 | let directory = URL(fileURLWithPath: path).deletingLastPathComponent() |
| 887 | 893 | do { |
| 888 | let new = try await EmacsRunner.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form) | |
| 894 | let new = try await programs.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form) | |
| 889 | 895 | guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." } |
| 890 | 896 | let current = entry.buffer |
| 891 | 897 | let text = current.document.text as NSString |
| @@ -902,9 +908,6 @@ public final class DocumentSession { | ||
| 902 | 908 | } catch { |
| 903 | 909 | return "\(error)" |
| 904 | 910 | } |
| 905 | #else | |
| 906 | return "Tables that need Emacs aren't recalculated on iOS." | |
| 907 | #endif | |
| 908 | 911 | } |
| 909 | 912 | |
| 910 | 913 | /// Runs a src block and writes its result under it, unless the block changed while it |
| @@ -912,18 +915,22 @@ public final class DocumentSession { | ||
| 912 | 915 | public func runBabel(_ job: BabelJob) async -> String { |
| 913 | 916 | guard let entry = current else { return "No file is open." } |
| 914 | 917 | let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent() |
| 915 | /// A program on the Mac; on iOS, Emacs Lisp in `Elisp`, and nothing else. | |
| 918 | let programs = Self.runner | |
| 919 | /// A program through `programs`; without it, Emacs Lisp in `Elisp`, and nothing else. | |
| 916 | 920 | func run(_ job: BabelJob) async throws -> BabelOutput { |
| 917 | #if os(macOS) | |
| 918 | return try await BabelRunner.run(job, fileDirectory: directory) | |
| 919 | #else | |
| 921 | if let programs { return try await programs.runBabel(job, fileDirectory: directory) } | |
| 920 | 922 | guard let output = try Babel.evaluateNatively(job) else { |
| 923 | #if os(macOS) | |
| 924 | throw Babel.Failure.message(job.lispForm == nil | |
| 925 | ? "\(job.language) blocks don't run in this version of orgstar." | |
| 926 | : "This block uses Emacs Lisp that runs only in Emacs.") | |
| 927 | #else | |
| 921 | 928 | throw Babel.Failure.message(job.lispForm == nil |
| 922 | 929 | ? "\(job.language) blocks need the Mac to run." |
| 923 | 930 | : "This block uses Emacs Lisp that runs only in Emacs, on the Mac.") |
| 931 | #endif | |
| 924 | 932 | } |
| 925 | 933 | return output |
| 926 | #endif | |
| 927 | 934 | } |
| 928 | 935 | do { |
| 929 | 936 | // Blocks the `:var`s refer to run first, one at a time. |
Sources/OrgApp/PlotChart.swift +2 −44
| @@ -216,6 +216,8 @@ struct Wireframe: View { | ||
| 216 | 216 | public enum PlotOutput { |
| 217 | 217 | public struct Failure: Error, CustomStringConvertible { |
| 218 | 218 | public let description: String |
| 219 | ||
| 220 | public init(description: String) { self.description = description } | |
| 219 | 221 | } |
| 220 | 222 | |
| 221 | 223 | /// `file:` relative to the Org file's folder. |
| @@ -254,48 +256,4 @@ public enum PlotOutput { | ||
| 254 | 256 | throw Failure(description: "Without gnuplot, plots are written as .png, .jpg or .pdf, not .\(url.pathExtension)") |
| 255 | 257 | } |
| 256 | 258 | } |
| 257 | ||
| 258 | #if os(macOS) | |
| 259 | /// gnuplot on the `PATH` Babel uses, when installed. | |
| 260 | public static var gnuplot: URL? { | |
| 261 | let path = BabelRunner.environment["PATH"] ?? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" | |
| 262 | return path.split(separator: ":").map { URL(fileURLWithPath: String($0)).appendingPathComponent("gnuplot") } | |
| 263 | .first { FileManager.default.isExecutableFile(atPath: $0.path) } | |
| 264 | } | |
| 265 | ||
| 266 | /// `org-plot/gnuplot` through gnuplot: the data file and script org-plot writes, run with | |
| 267 | /// the output at `file:`, or a PNG for showing when there's none. Returns the image. | |
| 268 | public static func runGnuplot(_ plot: TablePlot.Plot, directory: URL?, gnuplot: URL) async throws -> URL { | |
| 269 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)") | |
| 270 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | |
| 271 | let dataFile = folder.appendingPathComponent("data.tsv") | |
| 272 | var plot = plot | |
| 273 | let output = file(plot, directory: directory) ?? folder.appendingPathComponent("plot.png") | |
| 274 | if plot.options.file == nil { plot.options.values["file"] = .string(output.path) } | |
| 275 | let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot), []) | |
| 276 | try data.write(to: dataFile, atomically: true, encoding: .utf8) | |
| 277 | var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels) | |
| 278 | if let custom = plot.options["script"]?.description { | |
| 279 | let path = (custom as NSString).expandingTildeInPath | |
| 280 | let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path) | |
| 281 | guard let text = try? String(contentsOf: url, encoding: .utf8) else { throw Failure(description: "Can't read \(custom)") } | |
| 282 | script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, preface: true) | |
| 283 | + "\n" + text.replacingOccurrences(of: "$datafile", with: dataFile.path) | |
| 284 | } | |
| 285 | let scriptFile = folder.appendingPathComponent("plot.gp") | |
| 286 | try script.write(to: scriptFile, atomically: true, encoding: .utf8) | |
| 287 | let process = Process() | |
| 288 | process.executableURL = gnuplot | |
| 289 | process.arguments = [scriptFile.path] | |
| 290 | process.currentDirectoryURL = directory | |
| 291 | let errors = Pipe() | |
| 292 | process.standardError = errors | |
| 293 | try process.run() | |
| 294 | while process.isRunning { try await Task.sleep(for: .milliseconds(50)) } | |
| 295 | guard process.terminationStatus == 0 else { | |
| 296 | throw Failure(description: "gnuplot: " + String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)) | |
| 297 | } | |
| 298 | return output | |
| 299 | } | |
| 300 | #endif | |
| 301 | 259 | } |
Sources/OrgApp/ProgramRunning.swift added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | ||
| 4 | /// Runs Babel jobs and Emacs as processes, for an app allowed to start them. | |
| 5 | public protocol ProgramRunning: Sendable { | |
| 6 | /// Runs `job` in `fileDirectory`, or its `:dir`. | |
| 7 | func runBabel(_ job: BabelJob, fileDirectory: URL) async throws -> BabelOutput | |
| 8 | /// Runs `form` in Emacs on a copy of `text`; returns the table that starts at `table.lowerBound`. | |
| 9 | func recalculateTable(text: String, directory: URL, table: Range<Int>, point: Int, form: String) async throws -> String | |
| 10 | } | |
| 11 | ||
| 12 | extension DocumentSession { | |
| 13 | /// The runner for programs, set at launch by an app that may start them. Without one, | |
| 14 | /// only what runs natively runs. | |
| 15 | public static var programs: (any ProgramRunning)? | |
| 16 | ||
| 17 | /// Overrides `programs` for the current task and the tasks it starts. | |
| 18 | @TaskLocal public static var scopedPrograms: (any ProgramRunning)? | |
| 19 | ||
| 20 | static var runner: (any ProgramRunning)? { scopedPrograms ?? programs } | |
| 21 | } | |
Sources/OrgApp/BabelRunner.swift → Sources/OrgPrograms/BabelRunner.swift renamed
Sources/OrgApp/BabelSessions.swift → Sources/OrgPrograms/BabelSessions.swift renamed
Sources/OrgApp/EmacsRunner.swift → Sources/OrgPrograms/EmacsRunner.swift renamed
Sources/OrgPrograms/Gnuplot.swift added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | #if os(macOS) | |
| 2 | import Foundation | |
| 3 | import OrgApp | |
| 4 | import OrgCore | |
| 5 | ||
| 6 | extension PlotOutput { | |
| 7 | /// gnuplot on the `PATH` Babel uses, when installed. | |
| 8 | public static var gnuplot: URL? { | |
| 9 | let path = BabelRunner.environment["PATH"] ?? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" | |
| 10 | return path.split(separator: ":").map { URL(fileURLWithPath: String($0)).appendingPathComponent("gnuplot") } | |
| 11 | .first { FileManager.default.isExecutableFile(atPath: $0.path) } | |
| 12 | } | |
| 13 | ||
| 14 | /// `org-plot/gnuplot` through gnuplot: the data file and script org-plot writes, run with | |
| 15 | /// the output at `file:`, or a PNG for showing when there's none. Returns the image. | |
| 16 | public static func runGnuplot(_ plot: TablePlot.Plot, directory: URL?, gnuplot: URL) async throws -> URL { | |
| 17 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)") | |
| 18 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | |
| 19 | let dataFile = folder.appendingPathComponent("data.tsv") | |
| 20 | var plot = plot | |
| 21 | let output = file(plot, directory: directory) ?? folder.appendingPathComponent("plot.png") | |
| 22 | if plot.options.file == nil { plot.options.values["file"] = .string(output.path) } | |
| 23 | let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot), []) | |
| 24 | try data.write(to: dataFile, atomically: true, encoding: .utf8) | |
| 25 | var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels) | |
| 26 | if let custom = plot.options["script"]?.description { | |
| 27 | let path = (custom as NSString).expandingTildeInPath | |
| 28 | let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path) | |
| 29 | guard let text = try? String(contentsOf: url, encoding: .utf8) else { throw Failure(description: "Can't read \(custom)") } | |
| 30 | script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, preface: true) | |
| 31 | + "\n" + text.replacingOccurrences(of: "$datafile", with: dataFile.path) | |
| 32 | } | |
| 33 | let scriptFile = folder.appendingPathComponent("plot.gp") | |
| 34 | try script.write(to: scriptFile, atomically: true, encoding: .utf8) | |
| 35 | let process = Process() | |
| 36 | process.executableURL = gnuplot | |
| 37 | process.arguments = [scriptFile.path] | |
| 38 | process.currentDirectoryURL = directory | |
| 39 | let errors = Pipe() | |
| 40 | process.standardError = errors | |
| 41 | try process.run() | |
| 42 | while process.isRunning { try await Task.sleep(for: .milliseconds(50)) } | |
| 43 | guard process.terminationStatus == 0 else { | |
| 44 | throw Failure(description: "gnuplot: " + String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)) | |
| 45 | } | |
| 46 | return output | |
| 47 | } | |
| 48 | } | |
| 49 | #endif | |
Sources/OrgPrograms/Programs.swift added +18
| @@ -0,0 +1,18 @@ | ||
| 1 | #if os(macOS) | |
| 2 | import Foundation | |
| 3 | import OrgApp | |
| 4 | import OrgCore | |
| 5 | ||
| 6 | /// Babel and Emacs as processes, for `DocumentSession.programs`. | |
| 7 | public struct Programs: ProgramRunning { | |
| 8 | public init() {} | |
| 9 | ||
| 10 | public func runBabel(_ job: BabelJob, fileDirectory: URL) async throws -> BabelOutput { | |
| 11 | try await BabelRunner.run(job, fileDirectory: fileDirectory) | |
| 12 | } | |
| 13 | ||
| 14 | public func recalculateTable(text: String, directory: URL, table: Range<Int>, point: Int, form: String) async throws -> String { | |
| 15 | try await EmacsRunner.recalculateTable(text: text, directory: directory, table: table, point: point, form: form) | |
| 16 | } | |
| 17 | } | |
| 18 | #endif | |
Sources/Orgstar/ContentView.swift +12 −1
| @@ -5,6 +5,9 @@ import OrgEditorAppKit | ||
| 5 | 5 | import OrgPresentation |
| 6 | 6 | import OrgWorkspace |
| 7 | 7 | import OrgIndex |
| 8 | #if !APPSTORE | |
| 9 | import OrgPrograms | |
| 10 | #endif | |
| 8 | 11 | import SwiftUI |
| 9 | 12 | import UniformTypeIdentifiers |
| 10 | 13 | import WidgetKit |
| @@ -624,6 +627,7 @@ struct ContentView: View { | ||
| 624 | 627 | } |
| 625 | 628 | } |
| 626 | 629 | default: |
| 630 | #if !APPSTORE | |
| 627 | 631 | let functions = ["pdf": "org-latex-export-to-pdf", "odt": "org-odt-export-to-odt", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"] |
| 628 | 632 | guard let function = functions[format] else { return } |
| 629 | 633 | commands.show("Exporting with Emacs…") |
| @@ -647,6 +651,9 @@ struct ContentView: View { | ||
| 647 | 651 | commands.show("\(error)") |
| 648 | 652 | } |
| 649 | 653 | } |
| 654 | #else | |
| 655 | break | |
| 656 | #endif | |
| 650 | 657 | } |
| 651 | 658 | } |
| 652 | 659 | |
| @@ -783,6 +790,7 @@ struct ContentView: View { | ||
| 783 | 790 | let plot: TablePlot.Plot |
| 784 | 791 | do { plot = try TablePlot.plot(context.text, at: context.caret) } catch { return commands.show("\(error)") } |
| 785 | 792 | let directory = URL(fileURLWithPath: path).deletingLastPathComponent() |
| 793 | #if !APPSTORE | |
| 786 | 794 | if let gnuplot = PlotOutput.gnuplot { |
| 787 | 795 | commands.show("Plotting with gnuplot…") |
| 788 | 796 | Task { |
| @@ -793,7 +801,10 @@ struct ContentView: View { | ||
| 793 | 801 | commands.show("\(error)") |
| 794 | 802 | } |
| 795 | 803 | } |
| 796 | } else if let url = PlotOutput.file(plot, directory: directory) { | |
| 804 | return | |
| 805 | } | |
| 806 | #endif | |
| 807 | if let url = PlotOutput.file(plot, directory: directory) { | |
| 797 | 808 | do { |
| 798 | 809 | try PlotOutput.write(plot, to: url) |
| 799 | 810 | plotWritten(url, editor: editor) |
Sources/Orgstar/OrgstarApp.swift +8
| @@ -3,6 +3,9 @@ import OrgApp | ||
| 3 | 3 | import OrgCore |
| 4 | 4 | import OrgEditorAppKit |
| 5 | 5 | import OrgPresentation |
| 6 | #if !APPSTORE | |
| 7 | import OrgPrograms | |
| 8 | #endif | |
| 6 | 9 | import SwiftUI |
| 7 | 10 | import UserNotifications |
| 8 | 11 | |
| @@ -189,7 +192,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent | ||
| 189 | 192 | |
| 190 | 193 | /// `:session` interpreters end with the app. |
| 191 | 194 | func applicationWillTerminate(_ notification: Notification) { |
| 195 | #if !APPSTORE | |
| 192 | 196 | BabelSessions.shared.stopAll() |
| 197 | #endif | |
| 193 | 198 | } |
| 194 | 199 | |
| 195 | 200 | /// Reminders show while Orgstar is in front too. |
| @@ -324,6 +329,9 @@ struct OrgstarApp: App { | ||
| 324 | 329 | }() |
| 325 | 330 | |
| 326 | 331 | init() { |
| 332 | #if !APPSTORE | |
| 333 | DocumentSession.programs = Programs() | |
| 334 | #endif | |
| 327 | 335 | MacPro.resolve() |
| 328 | 336 | MacPro.renewInBackground() |
| 329 | 337 | // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console. |
Tests/OrgAppTests/AppTests.swift +14 −145
| @@ -949,157 +949,26 @@ struct ReminderSchedulerTests { | ||
| 949 | 949 | } |
| 950 | 950 | } |
| 951 | 951 | |
| 952 | /// Without `DocumentSession.programs`, only Emacs Lisp runs, natively. | |
| 952 | 953 | @MainActor |
| 953 | struct EmacsFallbackTests { | |
| 954 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 955 | func recalculatesTablesNativeCodeCannot() async throws { | |
| 954 | struct NativeProgramsTests { | |
| 955 | @Test func runsOnlyNativeBlocksWithoutARunner() async throws { | |
| 956 | #expect(DocumentSession.runner == nil) | |
| 956 | 957 | let notes = try Folder() |
| 957 | let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=$2*2\n") | |
| 958 | let file = try notes.write("b.org", "#+begin_src sh\necho hi\n#+end_src\n\n#+begin_src emacs-lisp\n(+ 1 2)\n#+end_src\n") | |
| 958 | 959 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) |
| 959 | 960 | session.open(file.path) |
| 960 | let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil) | |
| 961 | guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp)) = step else { | |
| 962 | Issue.record("\(step)") | |
| 961 | guard case .external(.babel(let sh)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil), | |
| 962 | case .external(.babel(let lisp)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 40, expect: nil) else { | |
| 963 | Issue.record("not planned") | |
| 963 | 964 | return |
| 964 | 965 | } |
| 965 | #expect(reason == "non-numeric field a") | |
| 966 | #expect(!lisp) | |
| 967 | let message = await session.recalculateInEmacs(table: table, point: point, form: form) | |
| 968 | #expect(message == "Recalculated in Emacs") | |
| 969 | #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | 2 a |\n| y | 2 | 4 |\n#+TBLFM: $3=$2*2\n") | |
| 970 | } | |
| 971 | ||
| 972 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 973 | func cancelingARecalculationLeavesTheTable() async throws { | |
| 974 | let notes = try Folder() | |
| 975 | let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=$1*2\n" | |
| 976 | let file = try notes.write("t.org", text) | |
| 977 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 978 | session.open(file.path) | |
| 979 | let step = session.perform(TableRecalculate(all: true), path: file.path, at: 2, expect: nil) | |
| 980 | guard case .external(.emacsTable(let table, let point, let form, _, _)) = step else { | |
| 981 | Issue.record("\(step)") | |
| 982 | return | |
| 983 | } | |
| 984 | let task = Task { await session.recalculateInEmacs(table: table, point: point, form: form) } | |
| 985 | task.cancel() | |
| 986 | #expect(await task.value == "Recalculation canceled") | |
| 987 | #expect(session.document?.text == text) | |
| 988 | } | |
| 989 | } | |
| 990 | ||
| 991 | @MainActor | |
| 992 | struct BabelSessionTests { | |
| 993 | @Test func runsBlocksAndWritesResults() async throws { | |
| 994 | let notes = try Folder() | |
| 995 | let file = try notes.write("b.org", "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n") | |
| 996 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 997 | session.open(file.path) | |
| 998 | let step = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil) | |
| 999 | guard case .external(.babel(let job)) = step else { | |
| 1000 | Issue.record("\(step)") | |
| 1001 | return | |
| 1002 | } | |
| 1003 | #expect(await session.runBabel(job) == "Code block evaluation complete.") | |
| 1004 | // A column that is half numbers is right-aligned, as org-table-align does. | |
| 1005 | #expect(session.document?.text == "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n\n#+RESULTS:\n| answer |\n| 42 |\n") | |
| 1006 | } | |
| 1007 | } | |
| 1008 | ||
| 1009 | @MainActor | |
| 1010 | struct BabelErrorTests { | |
| 1011 | func job(_ session: DocumentSession, _ path: String) throws -> BabelJob { | |
| 1012 | guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: path, at: 3, expect: nil) else { | |
| 1013 | throw CancellationError() | |
| 1014 | } | |
| 1015 | return job | |
| 1016 | } | |
| 1017 | ||
| 1018 | /// Like `org-babel-eval`: the results go in, and the error output and status are shown. | |
| 1019 | @Test func reportsErrorsAndStillInsertsResults() async throws { | |
| 1020 | let notes = try Folder() | |
| 1021 | let file = try notes.write("e.org", "#+begin_src sh\necho out\necho oops >&2\nexit 3\n#+end_src\n") | |
| 1022 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 1023 | session.open(file.path) | |
| 1024 | #expect(await session.runBabel(try job(session, file.path)) == "Exited with status 3: oops") | |
| 1025 | #expect(session.document?.text.hasSuffix("#+RESULTS:\n: out\n") == true) | |
| 1026 | } | |
| 1027 | ||
| 1028 | @Test func cancelsARunningBlock() async throws { | |
| 1029 | let notes = try Folder() | |
| 1030 | let file = try notes.write("s.org", "#+begin_src sh\nsleep 20\necho late\n#+end_src\n") | |
| 1031 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 1032 | session.open(file.path) | |
| 1033 | let start = ContinuousClock.now | |
| 1034 | var message: String? | |
| 1035 | session.startBabel(try job(session, file.path)) { message = $0 } | |
| 1036 | #expect(session.isRunningBabel) | |
| 1037 | try await Task.sleep(for: .milliseconds(200)) | |
| 1038 | session.cancelBabel() | |
| 1039 | while message == nil, ContinuousClock.now - start < .seconds(5) { try await Task.sleep(for: .milliseconds(20)) } | |
| 1040 | #expect(message == "Code block canceled.") | |
| 1041 | #expect(!session.isRunningBabel) | |
| 1042 | #expect(ContinuousClock.now - start < .seconds(5)) | |
| 1043 | #expect(session.document?.text.contains("#+RESULTS:") == false) | |
| 1044 | } | |
| 1045 | } | |
| 1046 | ||
| 1047 | struct EmacsExportTests { | |
| 1048 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 1049 | func exportsBesideTheFile() async throws { | |
| 1050 | let notes = try Folder() | |
| 1051 | let file = try notes.write("doc.org", "#+TITLE: On disk\n") | |
| 1052 | // The buffer's text is exported, not the file's. | |
| 1053 | let written = try await EmacsRunner.export(text: "#+TITLE: In the buffer\n\n* Heading\nBody.\n", path: file.path, function: "org-ascii-export-to-ascii") | |
| 1054 | #expect(URL(fileURLWithPath: written).lastPathComponent == "doc.txt") | |
| 1055 | let text = try String(contentsOfFile: written, encoding: .utf8) | |
| 1056 | #expect(text.uppercased().contains("IN THE BUFFER") && text.contains("Body."), "\(text)") | |
| 1057 | #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n") | |
| 1058 | } | |
| 1059 | ||
| 1060 | /// The dispatcher's `C-s` and `C-b`: the subtree at point alone, its EXPORT_FILE_NAME used. | |
| 1061 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 1062 | func exportsTheSubtreeBodyOnly() async throws { | |
| 1063 | let notes = try Folder() | |
| 1064 | let file = try notes.write("doc.org", "") | |
| 1065 | let text = "#+TITLE: Doc\n* Ünï\nFirst.\n* Second\n:PROPERTIES:\n:EXPORT_FILE_NAME: second\n:END:\nOnly this.\n" | |
| 1066 | let point = (text as NSString).substring(to: (text as NSString).range(of: "Only").location).unicodeScalars.count + 1 | |
| 1067 | let written = try await EmacsRunner.export(text: text, path: file.path, function: "org-ascii-export-to-ascii", subtree: point, bodyOnly: true) | |
| 1068 | #expect(URL(fileURLWithPath: written).lastPathComponent == "second.txt") | |
| 1069 | let out = try String(contentsOfFile: written, encoding: .utf8) | |
| 1070 | #expect(out.contains("Only this.") && !out.contains("First.") && !out.uppercased().contains("DOC"), "\(out)") | |
| 1071 | } | |
| 1072 | ||
| 1073 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 1074 | func exportUsesBabelPath() async throws { | |
| 1075 | let notes = try Folder() | |
| 1076 | let file = try notes.write("doc.org", "") | |
| 1077 | let function = #"(lambda () (with-temp-file "path.txt" (insert (getenv "PATH"))) "path.txt")"# | |
| 1078 | let written = try await EmacsRunner.export(text: "", path: file.path, function: function) | |
| 1079 | #expect(try String(contentsOfFile: written, encoding: .utf8) == BabelRunner.environment["PATH"]) | |
| 1080 | } | |
| 1081 | ||
| 1082 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 1083 | func cancellingStopsTheExport() async throws { | |
| 1084 | let notes = try Folder() | |
| 1085 | let file = try notes.write("doc.org", "") | |
| 1086 | let pidFile = notes.url.appendingPathComponent("pid") | |
| 1087 | let function = #"(lambda () (with-temp-file "pid" (insert (number-to-string (emacs-pid)))) (sleep-for 60) "x")"# | |
| 1088 | let export = Task { try await EmacsRunner.export(text: "", path: file.path, function: function) } | |
| 1089 | var pid: pid_t? | |
| 1090 | for _ in 0..<200 where pid == nil { | |
| 1091 | try await Task.sleep(for: .milliseconds(50)) | |
| 1092 | pid = (try? String(contentsOf: pidFile, encoding: .utf8)).flatMap { pid_t($0) } | |
| 1093 | } | |
| 1094 | let started = try #require(pid) | |
| 1095 | export.cancel() | |
| 1096 | await #expect(throws: CancellationError.self) { try await export.value } | |
| 1097 | var alive = true | |
| 1098 | for _ in 0..<100 where alive { | |
| 1099 | alive = kill(started, 0) == 0 | |
| 1100 | if alive { try await Task.sleep(for: .milliseconds(50)) } | |
| 1101 | } | |
| 1102 | #expect(!alive) | |
| 966 | #if os(macOS) | |
| 967 | #expect(await session.runBabel(sh) == "sh blocks don't run in this version of orgstar.") | |
| 968 | #expect(await session.recalculateInEmacs(table: 0..<1, point: 0, form: "") == "Tables that need Emacs aren't recalculated in this version of orgstar.") | |
| 969 | #endif | |
| 970 | #expect(await session.runBabel(lisp) == "Code block evaluation complete.") | |
| 971 | #expect(session.document?.text.hasSuffix("#+RESULTS:\n: 3\n") == true) | |
| 1103 | 972 | } |
| 1104 | 973 | } |
| 1105 | 974 | |
Tests/OrgAppTests/BabelSessionTests.swift → Tests/OrgProgramsTests/BabelSessionTests.swift renamed +1
| @@ -2,6 +2,7 @@ import Foundation | ||
| 2 | 2 | import Testing |
| 3 | 3 | import OrgCore |
| 4 | 4 | @testable import OrgApp |
| 5 | @testable import OrgPrograms | |
| 5 | 6 | |
| 6 | 7 | /// Serial: the sessions are shared, and each test stops them all when it ends. |
| 7 | 8 | @Suite(.serialized) |
Tests/OrgProgramsTests/Folder.swift added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// A temporary folder that removes itself. | |
| 4 | final class Folder { | |
| 5 | let url: URL | |
| 6 | ||
| 7 | init() throws { | |
| 8 | url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)").standardizedFileURL | |
| 9 | try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) | |
| 10 | } | |
| 11 | ||
| 12 | deinit { | |
| 13 | try? FileManager.default.removeItem(at: url) | |
| 14 | } | |
| 15 | ||
| 16 | @discardableResult | |
| 17 | func write(_ path: String, _ text: String) throws -> URL { | |
| 18 | let file = url.appendingPathComponent(path) | |
| 19 | try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) | |
| 20 | try Data(text.utf8).write(to: file) | |
| 21 | return file.standardizedFileURL | |
| 22 | } | |
| 23 | } | |
Tests/OrgProgramsTests/ProgramsTests.swift added +175
| @@ -0,0 +1,175 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import OrgDocument | |
| 4 | import Testing | |
| 5 | @testable import OrgApp | |
| 6 | @testable import OrgPrograms | |
| 7 | ||
| 8 | /// Runs each test with `Programs` as the session's runner, scoped to the test's task so | |
| 9 | /// suites without one are unaffected. | |
| 10 | struct WithPrograms: SuiteTrait, TestTrait, TestScoping { | |
| 11 | func provideScope(for test: Test, testCase: Test.Case?, performing function: @Sendable () async throws -> Void) async throws { | |
| 12 | try await DocumentSession.$scopedPrograms.withValue(Programs()) { try await function() } | |
| 13 | } | |
| 14 | } | |
| 15 | ||
| 16 | extension Trait where Self == WithPrograms { | |
| 17 | static var programs: Self { WithPrograms() } | |
| 18 | } | |
| 19 | ||
| 20 | @MainActor | |
| 21 | @Suite(.programs) | |
| 22 | struct EmacsFallbackTests { | |
| 23 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 24 | func recalculatesTablesNativeCodeCannot() async throws { | |
| 25 | let notes = try Folder() | |
| 26 | let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=$2*2\n") | |
| 27 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 28 | session.open(file.path) | |
| 29 | let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil) | |
| 30 | guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp)) = step else { | |
| 31 | Issue.record("\(step)") | |
| 32 | return | |
| 33 | } | |
| 34 | #expect(reason == "non-numeric field a") | |
| 35 | #expect(!lisp) | |
| 36 | let message = await session.recalculateInEmacs(table: table, point: point, form: form) | |
| 37 | #expect(message == "Recalculated in Emacs") | |
| 38 | #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | 2 a |\n| y | 2 | 4 |\n#+TBLFM: $3=$2*2\n") | |
| 39 | } | |
| 40 | ||
| 41 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 42 | func cancelingARecalculationLeavesTheTable() async throws { | |
| 43 | let notes = try Folder() | |
| 44 | let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=$1*2\n" | |
| 45 | let file = try notes.write("t.org", text) | |
| 46 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 47 | session.open(file.path) | |
| 48 | let step = session.perform(TableRecalculate(all: true), path: file.path, at: 2, expect: nil) | |
| 49 | guard case .external(.emacsTable(let table, let point, let form, _, _)) = step else { | |
| 50 | Issue.record("\(step)") | |
| 51 | return | |
| 52 | } | |
| 53 | let task = Task { await session.recalculateInEmacs(table: table, point: point, form: form) } | |
| 54 | task.cancel() | |
| 55 | #expect(await task.value == "Recalculation canceled") | |
| 56 | #expect(session.document?.text == text) | |
| 57 | } | |
| 58 | } | |
| 59 | ||
| 60 | @MainActor | |
| 61 | @Suite(.programs) | |
| 62 | struct BabelSessionTests { | |
| 63 | @Test func runsBlocksAndWritesResults() async throws { | |
| 64 | let notes = try Folder() | |
| 65 | let file = try notes.write("b.org", "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n") | |
| 66 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 67 | session.open(file.path) | |
| 68 | let step = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil) | |
| 69 | guard case .external(.babel(let job)) = step else { | |
| 70 | Issue.record("\(step)") | |
| 71 | return | |
| 72 | } | |
| 73 | #expect(await session.runBabel(job) == "Code block evaluation complete.") | |
| 74 | // A column that is half numbers is right-aligned, as org-table-align does. | |
| 75 | #expect(session.document?.text == "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n\n#+RESULTS:\n| answer |\n| 42 |\n") | |
| 76 | } | |
| 77 | } | |
| 78 | ||
| 79 | @MainActor | |
| 80 | @Suite(.programs) | |
| 81 | struct BabelErrorTests { | |
| 82 | func job(_ session: DocumentSession, _ path: String) throws -> BabelJob { | |
| 83 | guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: path, at: 3, expect: nil) else { | |
| 84 | throw CancellationError() | |
| 85 | } | |
| 86 | return job | |
| 87 | } | |
| 88 | ||
| 89 | /// Like `org-babel-eval`: the results go in, and the error output and status are shown. | |
| 90 | @Test func reportsErrorsAndStillInsertsResults() async throws { | |
| 91 | let notes = try Folder() | |
| 92 | let file = try notes.write("e.org", "#+begin_src sh\necho out\necho oops >&2\nexit 3\n#+end_src\n") | |
| 93 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 94 | session.open(file.path) | |
| 95 | #expect(await session.runBabel(try job(session, file.path)) == "Exited with status 3: oops") | |
| 96 | #expect(session.document?.text.hasSuffix("#+RESULTS:\n: out\n") == true) | |
| 97 | } | |
| 98 | ||
| 99 | @Test func cancelsARunningBlock() async throws { | |
| 100 | let notes = try Folder() | |
| 101 | let file = try notes.write("s.org", "#+begin_src sh\nsleep 20\necho late\n#+end_src\n") | |
| 102 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 103 | session.open(file.path) | |
| 104 | let start = ContinuousClock.now | |
| 105 | var message: String? | |
| 106 | session.startBabel(try job(session, file.path)) { message = $0 } | |
| 107 | #expect(session.isRunningBabel) | |
| 108 | try await Task.sleep(for: .milliseconds(200)) | |
| 109 | session.cancelBabel() | |
| 110 | while message == nil, ContinuousClock.now - start < .seconds(5) { try await Task.sleep(for: .milliseconds(20)) } | |
| 111 | #expect(message == "Code block canceled.") | |
| 112 | #expect(!session.isRunningBabel) | |
| 113 | #expect(ContinuousClock.now - start < .seconds(5)) | |
| 114 | #expect(session.document?.text.contains("#+RESULTS:") == false) | |
| 115 | } | |
| 116 | } | |
| 117 | ||
| 118 | struct EmacsExportTests { | |
| 119 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 120 | func exportsBesideTheFile() async throws { | |
| 121 | let notes = try Folder() | |
| 122 | let file = try notes.write("doc.org", "#+TITLE: On disk\n") | |
| 123 | // The buffer's text is exported, not the file's. | |
| 124 | let written = try await EmacsRunner.export(text: "#+TITLE: In the buffer\n\n* Heading\nBody.\n", path: file.path, function: "org-ascii-export-to-ascii") | |
| 125 | #expect(URL(fileURLWithPath: written).lastPathComponent == "doc.txt") | |
| 126 | let text = try String(contentsOfFile: written, encoding: .utf8) | |
| 127 | #expect(text.uppercased().contains("IN THE BUFFER") && text.contains("Body."), "\(text)") | |
| 128 | #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n") | |
| 129 | } | |
| 130 | ||
| 131 | /// The dispatcher's `C-s` and `C-b`: the subtree at point alone, its EXPORT_FILE_NAME used. | |
| 132 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 133 | func exportsTheSubtreeBodyOnly() async throws { | |
| 134 | let notes = try Folder() | |
| 135 | let file = try notes.write("doc.org", "") | |
| 136 | let text = "#+TITLE: Doc\n* Ünï\nFirst.\n* Second\n:PROPERTIES:\n:EXPORT_FILE_NAME: second\n:END:\nOnly this.\n" | |
| 137 | let point = (text as NSString).substring(to: (text as NSString).range(of: "Only").location).unicodeScalars.count + 1 | |
| 138 | let written = try await EmacsRunner.export(text: text, path: file.path, function: "org-ascii-export-to-ascii", subtree: point, bodyOnly: true) | |
| 139 | #expect(URL(fileURLWithPath: written).lastPathComponent == "second.txt") | |
| 140 | let out = try String(contentsOfFile: written, encoding: .utf8) | |
| 141 | #expect(out.contains("Only this.") && !out.contains("First.") && !out.uppercased().contains("DOC"), "\(out)") | |
| 142 | } | |
| 143 | ||
| 144 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 145 | func exportUsesBabelPath() async throws { | |
| 146 | let notes = try Folder() | |
| 147 | let file = try notes.write("doc.org", "") | |
| 148 | let function = #"(lambda () (with-temp-file "path.txt" (insert (getenv "PATH"))) "path.txt")"# | |
| 149 | let written = try await EmacsRunner.export(text: "", path: file.path, function: function) | |
| 150 | #expect(try String(contentsOfFile: written, encoding: .utf8) == BabelRunner.environment["PATH"]) | |
| 151 | } | |
| 152 | ||
| 153 | @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | |
| 154 | func cancellingStopsTheExport() async throws { | |
| 155 | let notes = try Folder() | |
| 156 | let file = try notes.write("doc.org", "") | |
| 157 | let pidFile = notes.url.appendingPathComponent("pid") | |
| 158 | let function = #"(lambda () (with-temp-file "pid" (insert (number-to-string (emacs-pid)))) (sleep-for 60) "x")"# | |
| 159 | let export = Task { try await EmacsRunner.export(text: "", path: file.path, function: function) } | |
| 160 | var pid: pid_t? | |
| 161 | for _ in 0..<200 where pid == nil { | |
| 162 | try await Task.sleep(for: .milliseconds(50)) | |
| 163 | pid = (try? String(contentsOf: pidFile, encoding: .utf8)).flatMap { pid_t($0) } | |
| 164 | } | |
| 165 | let started = try #require(pid) | |
| 166 | export.cancel() | |
| 167 | await #expect(throws: CancellationError.self) { try await export.value } | |
| 168 | var alive = true | |
| 169 | for _ in 0..<100 where alive { | |
| 170 | alive = kill(started, 0) == 0 | |
| 171 | if alive { try await Task.sleep(for: .milliseconds(50)) } | |
| 172 | } | |
| 173 | #expect(!alive) | |
| 174 | } | |
| 175 | } | |