Tests/OrgCoreTests/EmacsOracle.swift

397c9ad69a596cfff75844141c5e537217661eb3
orgstar/Tests/OrgCoreTests/EmacsOracle.swift history · blame · raw

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