Tests/OrgCoreTests/EmacsOracle.swift
136 lines · 5847 bytes
1import Foundation
2@testable import OrgCore
3
4/// Runs cases through `emacs -Q --batch` with Org's settings pinned, so commands can be
5/// compared with Emacs byte for byte. One Emacs process runs a whole batch.
6///
7/// Pinned versions: Emacs 31.1, Org 9.8.7 (design, "Testing"). `ORGSTAR_EMACS` overrides the
8/// executable.
9enum EmacsOracle {
10 struct Case: Codable {
11 var text: String
12 /// Emacs point: 1 plus the number of characters (code points) before it.
13 var point: Int
14 /// An Emacs Lisp form to run with point there.
15 var form: String
16 }
17
18 struct Result: Codable, Equatable {
19 var text: String
20 var point: Int
21 /// The error message, or empty.
22 var error: String
23 }
24
25 static let script = #"""
26 ;;; -*- lexical-binding: t -*-
27 (require 'org)
28 (require 'json)
29 (require 'cl-lib)
30 (setq org-todo-keywords '((sequence "TODO" "DONE"))
31 org-log-done nil
32 org-log-repeat nil
33 org-adapt-indentation nil
34 org-tags-column -77
35 org-priority-highest ?A
36 org-priority-lowest ?C
37 org-priority-default ?B)
38 ;; Buffer-local when set, so set the default for the case buffers.
39 (setq-default indent-tabs-mode nil)
40 (let* ((input (with-temp-buffer
41 (let ((coding-system-for-read 'utf-8-unix))
42 (insert-file-contents (getenv "ORACLE_INPUT")))
43 (json-parse-buffer :object-type 'alist :array-type 'list)))
44 (results nil))
45 (dolist (c input)
46 (with-temp-buffer
47 (insert (alist-get 'text c))
48 (org-mode)
49 ;; `#+STARTUP' may fold the buffer; cases run with everything visible.
50 (org-fold-show-all)
51 (goto-char (alist-get 'point c))
52 ;; As an interactive call, not a repeat: some commands cycle differently on repeats.
53 (setq this-command 'orgstar-oracle last-command nil)
54 (let ((err (condition-case e
55 (progn (eval (car (read-from-string (alist-get 'form c))) t) "")
56 (error (error-message-string e)))))
57 (push `((text . ,(buffer-substring-no-properties (point-min) (point-max)))
58 (point . ,(point))
59 (error . ,err))
60 results))))
61 (let ((coding-system-for-write 'utf-8-unix))
62 (with-temp-file (getenv "ORACLE_OUTPUT")
63 (insert (json-encode (nreverse results))))))
64 """#
65
66 static var executable: String { ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs" }
67
68 static var isAvailable: Bool {
69 (try? run(["--version"]))?.contains("GNU Emacs") ?? false
70 }
71
72 static func run(_ cases: [Case]) throws -> [Result] {
73 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-oracle-\(UUID().uuidString)")
74 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
75 defer { try? FileManager.default.removeItem(at: folder) }
76 let scriptURL = folder.appendingPathComponent("oracle.el")
77 let input = folder.appendingPathComponent("input.json")
78 let output = folder.appendingPathComponent("output.json")
79 try script.write(to: scriptURL, atomically: true, encoding: .utf8)
80 try JSONEncoder().encode(cases).write(to: input)
81 _ = try run(["-Q", "--batch", "-l", scriptURL.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path])
82 return try JSONDecoder().decode([Result].self, from: Data(contentsOf: output))
83 }
84
85 @discardableResult
86 static func run(_ arguments: [String], environment: [String: String] = [:]) throws -> String {
87 let process = Process()
88 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
89 process.arguments = [executable] + arguments
90 process.environment = ProcessInfo.processInfo.environment.merging(environment) { $1 }
91 let pipe = Pipe()
92 process.standardOutput = pipe
93 process.standardError = pipe
94 try process.run()
95 let data = pipe.fileHandleForReading.readDataToEndOfFile()
96 process.waitUntilExit()
97 return String(decoding: data, as: UTF8.self)
98 }
99
100 /// UTF-16 offset to Emacs point.
101 static func point(_ offset: Int, in text: String) -> Int {
102 let index = String.Index(utf16Offset: offset, in: text)
103 return text.unicodeScalars[..<index].count + 1
104 }
105
106 /// Emacs point to UTF-16 offset.
107 static func offset(_ point: Int, in text: String) -> Int {
108 text.unicodeScalars.prefix(point - 1).reduce(0) { $0 + $1.utf16.count }
109 }
110
111 /// UTF-16 offsets of every unicode scalar boundary, including the end.
112 static func positions(_ text: String) -> [Int] {
113 var positions = [0]
114 var offset = 0
115 for scalar in text.unicodeScalars {
116 offset += scalar.utf16.count
117 positions.append(offset)
118 }
119 return positions
120 }
121}
122
123/// Runs a command the way an editor would: build a context, run, apply the edits.
124func runCommand(_ command: any OrgCommand, _ text: String, caret: Int, answers: [String: String] = [:]) -> (text: String, caret: Int, failure: String?) {
125 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], answers: answers)
126 switch command.run(in: context) {
127 case .commit(let result):
128 var new = text
129 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) }
130 return (new, result.selection?.first?.lowerBound ?? caret, nil)
131 case .failed(let message):
132 return (text, caret, message)
133 case .prompt(let prompt):
134 return (text, caret, "prompt: \(prompt.key)")
135 }
136}