Tests/OrgAppTests/RefileTargetTests.swift

106 lines · 5642 bytes

  1import Foundation
  2import Testing
  3@testable import OrgApp
  4import OrgCore
  5import OrgDocument
  6
  7/// `org-refile-get-targets` against Emacs.
  8@MainActor
  9struct RefileTargetTests {
 10    static let files = [
 11        ("a.org", "* Projects :proj:\n** TODO Website\n*** Plan the copy\n** Taxes/2026\n* NEXT Write report\n* Notes\n"),
 12        ("b.org", "* Inbox\n** Plan ahead :proj:\n* Someday\n** NEXT Read\n"),
 13        ("sub/x.org", "#+TITLE: Extra file\n* Deep\n** Deeper\n"),
 14    ]
 15
 16    static var emacs: String { ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs" }
 17
 18    /// Emacs's labels as `org-refile-get-location` shows them, without the `/` it adds for
 19    /// completion, with the file and the heading's start (0-based) of each.
 20    static func emacsTargets(_ folder: URL, targets: String, mode: String) throws -> [String] {
 21        let form = """
 22        (progn
 23          (require 'org) (require 'org-refile) (require 'json)
 24          (let* ((dir "\(folder.path)/")
 25                 (a (expand-file-name "a.org" dir)))
 26            (setq org-agenda-files (list a (expand-file-name "b.org" dir)))
 27            (with-current-buffer (find-file-noselect a)
 28              (let* ((org-refile-targets '\(targets))
 29                     (org-refile-use-outline-path '\(mode))
 30                     (extra (if org-refile-use-outline-path "/" ""))
 31                     (out nil))
 32                (dolist (x (org-refile-get-targets))
 33                  (let ((label (if (and (not (memq org-refile-use-outline-path '(file full-file-path title)))
 34                                        (not (equal (file-truename a) (file-truename (nth 1 x)))))
 35                                   (concat (car x) " (" (file-name-nondirectory (nth 1 x)) ")")
 36                                 (car x))))
 37                    (push (format "%s | %s | %s" label (file-name-nondirectory (nth 1 x))
 38                                  (let ((p (nth 3 x))) (if p (1- (if (markerp p) (marker-position p) p)) "-")))
 39                          out)))
 40                (princ (json-encode (nreverse out)))))))
 41        """
 42        let process = Process()
 43        process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
 44        process.arguments = [emacs, "-Q", "--batch", "--eval", form]
 45        let pipe = Pipe()
 46        process.standardOutput = pipe
 47        let errors = Pipe()
 48        process.standardError = errors
 49        try process.run()
 50        let data = pipe.fileHandleForReading.readDataToEndOfFile()
 51        process.waitUntilExit()
 52        guard let decoded = try? JSONDecoder().decode([String].self, from: data) else {
 53            Issue.record("Emacs printed \(String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self))")
 54            return []
 55        }
 56        return decoded
 57    }
 58
 59    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 60    func targetsLikeOrg() async throws {
 61        let notes = try Folder()
 62        for (name, text) in Self.files { try notes.write(name, text) }
 63        let workspace = try WorkspaceModel(directory: nil)
 64        try await workspace.addRoot(notes.url)
 65        let a = notes.url.appendingPathComponent("a.org").standardizedFileURL.path
 66        let document = DocumentState(bytes: Array(Self.files[0].1.utf8))
 67        let cases: [(String, String)] = [
 68            ("((nil :maxlevel . 2))", "file"),
 69            ("((org-agenda-files :level . 2))", "t"),
 70            ("((nil :tag . \"proj\") (org-agenda-files :todo . \"NEXT\"))", "nil"),
 71            ("((org-agenda-files :regexp . \"Plan\"))", "buffer-name"),
 72            ("((\"sub/x.org\" :maxlevel . 9) (nil . t))", "title"),
 73            ("((org-agenda-files :maxlevel . 1))", "file"),
 74        ]
 75        for (targets, mode) in cases {
 76            let parsed = try RefileSettings.parseTargets(targets).get()
 77            let settings = RefileSettings(targets: parsed, outlinePath: RefileSettings.OutlinePath(rawValue: mode)!)
 78            let ours = workspace.refileTargets(openPath: a, document: document, settings: settings).map {
 79                "\($0.label) | \(($0.path as NSString).lastPathComponent) | \($0.start.map(String.init) ?? "-")"
 80            }
 81            let theirs = try Self.emacsTargets(notes.url, targets: targets, mode: mode).map {
 82                $0.replacingOccurrences(of: "/ (", with: " (").replacingOccurrences(of: "/ | ", with: " | ")
 83            }
 84            #expect(ours == theirs, "\(targets) \(mode)")
 85        }
 86    }
 87
 88    @Test func newChildGoesAtTheSubtreesEnd() {
 89        func run(_ text: String, _ start: Int?, _ title: String) -> (String, Int, Int) {
 90            let r = DocumentSession.newChild(text, under: .some(start), title: title)
 91            return (r.edit.apply(to: text), r.start, r.level)
 92        }
 93        #expect(run("* A\nbody\n\n* B\n", 0, "New") == ("* A\nbody\n\n** New\n\n* B\n", 10, 2))
 94        #expect(run("* A\n** a1\n* B", 0, "New") == ("* A\n** a1\n\n** New\n* B", 11, 2))
 95        #expect(run("* A\nx", nil, "New") == ("* A\nx\n\n* New\n", 7, 1))
 96        #expect(run("* A\n\n\n", nil, "New") == ("* A\n\n* New\n\n\n", 5, 1))
 97    }
 98
 99    @Test func splitsNewNodes() {
100        let parent = RefileTarget(label: "a.org/Projects", path: "/a.org", start: 0, title: "Projects", level: 1, contentHash: "")
101        #expect(RefileSettings.newNode("a.org/Projects/Garden", in: [parent])?.child == "Garden")
102        #expect(RefileSettings.newNode("a.org/Projects//Garden", in: [parent])?.child == "Garden")
103        #expect(RefileSettings.newNode("a.org/Other/Garden", in: [parent]) == nil)
104        #expect(RefileSettings.newNode("Garden", in: [parent]) == nil)
105    }
106}