Tests/OrgCoreTests/EmacsOracle.swift
138 lines · 5996 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 ;; Archive files open in Org mode, as in usual configurations.
41 (add-to-list 'auto-mode-alist '("\\.org_archive\\'" . org-mode))
42 (let* ((input (with-temp-buffer
43 (let ((coding-system-for-read 'utf-8-unix))
44 (insert-file-contents (getenv "ORACLE_INPUT")))
45 (json-parse-buffer :object-type 'alist :array-type 'list)))
46 (results nil))
47 (dolist (c input)
48 (with-temp-buffer
49 (insert (alist-get 'text c))
50 (org-mode)
51 ;; `#+STARTUP' may fold the buffer; cases run with everything visible.
52 (org-fold-show-all)
53 (goto-char (alist-get 'point c))
54 ;; As an interactive call, not a repeat: some commands cycle differently on repeats.
55 (setq this-command 'orgstar-oracle last-command nil)
56 (let ((err (condition-case e
57 (progn (eval (car (read-from-string (alist-get 'form c))) t) "")
58 (error (error-message-string e)))))
59 (push `((text . ,(buffer-substring-no-properties (point-min) (point-max)))
60 (point . ,(point))
61 (error . ,err))
62 results))))
63 (let ((coding-system-for-write 'utf-8-unix))
64 (with-temp-file (getenv "ORACLE_OUTPUT")
65 (insert (json-encode (nreverse results))))))
66 """#
67
68 static var executable: String { ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs" }
69
70 static var isAvailable: Bool {
71 (try? run(["--version"]))?.contains("GNU Emacs") ?? false
72 }
73
74 static func run(_ cases: [Case]) throws -> [Result] {
75 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-oracle-\(UUID().uuidString)")
76 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
77 defer { try? FileManager.default.removeItem(at: folder) }
78 let scriptURL = folder.appendingPathComponent("oracle.el")
79 let input = folder.appendingPathComponent("input.json")
80 let output = folder.appendingPathComponent("output.json")
81 try script.write(to: scriptURL, atomically: true, encoding: .utf8)
82 try JSONEncoder().encode(cases).write(to: input)
83 _ = try run(["-Q", "--batch", "-l", scriptURL.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "TZ": "UTC"])
84 return try JSONDecoder().decode([Result].self, from: Data(contentsOf: output))
85 }
86
87 @discardableResult
88 static func run(_ arguments: [String], environment: [String: String] = [:]) throws -> String {
89 let process = Process()
90 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
91 process.arguments = [executable] + arguments
92 process.environment = ProcessInfo.processInfo.environment.merging(environment) { $1 }
93 let pipe = Pipe()
94 process.standardOutput = pipe
95 process.standardError = pipe
96 try process.run()
97 let data = pipe.fileHandleForReading.readDataToEndOfFile()
98 process.waitUntilExit()
99 return String(decoding: data, as: UTF8.self)
100 }
101
102 /// UTF-16 offset to Emacs point.
103 static func point(_ offset: Int, in text: String) -> Int {
104 let index = String.Index(utf16Offset: offset, in: text)
105 return text.unicodeScalars[..<index].count + 1
106 }
107
108 /// Emacs point to UTF-16 offset.
109 static func offset(_ point: Int, in text: String) -> Int {
110 text.unicodeScalars.prefix(point - 1).reduce(0) { $0 + $1.utf16.count }
111 }
112
113 /// UTF-16 offsets of every unicode scalar boundary, including the end.
114 static func positions(_ text: String) -> [Int] {
115 var positions = [0]
116 var offset = 0
117 for scalar in text.unicodeScalars {
118 offset += scalar.utf16.count
119 positions.append(offset)
120 }
121 return positions
122 }
123}
124
125/// Runs a command the way an editor would: build a context, run, apply the edits.
126func runCommand(_ command: any OrgCommand, _ text: String, caret: Int, answers: [String: String] = [:]) -> (text: String, caret: Int, failure: String?) {
127 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], answers: answers)
128 switch command.run(in: context) {
129 case .commit(let result):
130 var new = text
131 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) }
132 return (new, result.selection?.first?.lowerBound ?? caret, nil)
133 case .failed(let message):
134 return (text, caret, message)
135 case .prompt(let prompt):
136 return (text, caret, "prompt: \(prompt.key)")
137 }
138}