Tests/OrgCoreTests/ArchiveTests.swift

126 lines · 8223 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct ArchiveTests {
  6    static let now = Date(timeIntervalSince1970: 1_789_000_000)
  7    static var utc: Calendar {
  8        var calendar = Calendar(identifier: .gregorian)
  9        calendar.timeZone = TimeZone(identifier: "UTC")!
 10        return calendar
 11    }
 12
 13    func context(_ text: String, _ caret: Int) -> EditContext {
 14        EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], now: Self.now, calendar: Self.utc)
 15    }
 16
 17    @Test func destinations() throws {
 18        let plain = try Archive.destination(context("* a\n", 0), sourcePath: "/n/a.org").get()
 19        #expect(plain == Archive.Destination(path: "/n/a.org_archive", heading: nil, isSameFile: false))
 20        let keyword = try Archive.destination(context("#+ARCHIVE: done.org::* %s\n* a\n", 27), sourcePath: "/n/a.org").get()
 21        #expect(keyword == Archive.Destination(path: "/n/done.org", heading: "* a.org", isSameFile: false))
 22        let local = try Archive.destination(context("* a\n:PROPERTIES:\n:ARCHIVE: ::* Old\n:END:\n", 0), sourcePath: "/n/a.org").get()
 23        #expect(local.isSameFile && local.heading == "* Old")
 24        // org-archive-location, under the keyword and the property.
 25        var options = EditingOptions.org
 26        options.archiveLocation = "old/%s::* From %s"
 27        func optioned(_ text: String, _ caret: Int) -> EditContext {
 28            EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], now: Self.now, calendar: Self.utc, options: options)
 29        }
 30        let global = try Archive.destination(optioned("* a\n", 0), sourcePath: "/n/a.org").get()
 31        #expect(global == Archive.Destination(path: "/n/old/a.org", heading: "* From a.org", isSameFile: false))
 32        let overridden = try Archive.destination(optioned("#+ARCHIVE: done.org::\n* a\n", 22), sourcePath: "/n/a.org").get()
 33        #expect(overridden.path == "/n/done.org" && overridden.heading == nil)
 34    }
 35
 36    @Test func archivesToANewFile() throws {
 37        let text = "* P\n** TODO a :t:\nbody\n** b\n"
 38        let ctx = context(text, 6)
 39        let destination = try Archive.destination(ctx, sourcePath: "/n/a.org").get()
 40        let edits = try Archive.run(ctx, sourcePath: "/n/a.org", destination: destination, archiveText: nil).get()
 41        #expect(edits.source.edits.reduce(text) { $1.apply(to: $0) } == "* P\n** b\n")
 42        let archived = try #require(edits.archive).apply(to: "")
 43        #expect(archived.hasPrefix("\nArchived entries from file /n/a.org\n\n\n* TODO a"))
 44        #expect(archived.contains(":ARCHIVE_OLPATH: P\n"))
 45        #expect(archived.contains(":ARCHIVE_TIME: 2026-09-10 Thu 00:26\n"))
 46    }
 47
 48    static let sources = [
 49        "* a\nbody\n* b\n",
 50        "#+FILETAGS: :f:\n* P :p:\n** TODO a :t:\nbody\n** DONE b\n",
 51        "* P [1/2]\n** TODO a\n** DONE b\n",
 52        "#+CATEGORY: work\n* a [[https://x.org][link]]\n* b\n",
 53        "#+ARCHIVE: ::* Archive\n* a :x:\n* Archive\n** old\n",
 54        "* P\n:PROPERTIES:\n:ARCHIVE: ::* Old :t:\n:CATEGORY: c\n:END:\n** a\n* Old :t:\n",
 55        "* a\nSCHEDULED: <2026-01-01 Thu>\n:PROPERTIES:\n:ID: 1\n:END:\n* b",
 56        "#+ARCHIVE: ::datetree/\n* a\nbody\n* b\n",
 57        "#+ARCHIVE: %s_archive::datetree/\n* DONE a\nCLOSED: [2026-08-15 Sat 09:00]\n* b\n",
 58        "#+ARCHIVE: ::datetree/* Notes\n* a\n** sub\n* b\n",
 59    ]
 60    static let archives: [String?] = [nil, "", "* existing\n", "\n#+TITLE: arch\n\n* x\n:PROPERTIES:\n:ARCHIVE_TIME: t\n:END:\n\n",
 61                                      "* 2026\n** 2026-09 September\n*** 2026-09-10 Thursday\n**** prior\n*** 2026-09-12 Saturday\n"]
 62
 63    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 64    func archiveMatchesEmacs() throws {
 65        try #require(EmacsOracle.isAvailable)
 66        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-archive-\(UUID().uuidString)")
 67        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 68        defer { try? FileManager.default.removeItem(at: folder) }
 69        var cases: [EmacsOracle.Case] = []
 70        var ours: [(label: String, text: String, caret: Int, failed: Bool)] = []
 71        var index = 0
 72        for source in Self.sources {
 73            let tree = OrgParser.parse(source)
 74            let carets = tree.root.descendants().filter { $0.kind == .heading }.flatMap { [$0.range.lowerBound, $0.range.lowerBound + 2] }
 75            for caret in carets {
 76                for archiveText in Self.archives {
 77                    index += 1
 78                    let path = folder.appendingPathComponent("s\(index).org").path
 79                    let ctx = context(source, caret)
 80                    guard case .success(let destination) = Archive.destination(ctx, sourcePath: path) else { continue }
 81                    if destination.isSameFile, archiveText != nil { continue }
 82                    let archivePath = destination.path
 83                    let escaped = { (s: String) in s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") }
 84                    let writeArchive = archiveText.map { "(with-temp-file \"\(escaped(archivePath))\" (insert \"\(escaped($0))\"))" } ?? "(when (file-exists-p \"\(escaped(archivePath))\") (delete-file \"\(escaped(archivePath))\"))"
 85                    let form = """
 86                        (let ((p (point)) (src (buffer-string)) s1 s2)
 87                          \(writeArchive)
 88                          (with-temp-file "\(escaped(path))" (insert src))
 89                          (with-current-buffer (find-file-noselect "\(escaped(path))")
 90                            (org-fold-show-all) (goto-char p)
 91                            (cl-letf* ((orig (symbol-function 'format-time-string))
 92                                       ((symbol-function 'format-time-string) (lambda (f &optional time zone) (funcall orig f (or time 1789000000) zone))))
 93                              (org-archive-subtree))
 94                            (setq p (point) s1 (buffer-string))
 95                            (set-buffer-modified-p nil) (kill-buffer))
 96                          (let ((b (get-file-buffer "\(escaped(archivePath))")))
 97                            (when b (with-current-buffer b (setq s2 (buffer-string)) (set-buffer-modified-p nil) (kill-buffer))))
 98                          (erase-buffer) (insert s1 "\\n@@@@\\n" (or s2 "")) (goto-char p))
 99                        """
100                    cases.append(EmacsOracle.Case(text: source, point: EmacsOracle.point(caret, in: source), form: form))
101                    let label = "\(caret) in \(source.debugDescription) to \(archiveText.debugDescription)"
102                    switch Archive.run(ctx, sourcePath: path, destination: destination, archiveText: archiveText) {
103                    case .success(let edits):
104                        let newSource = edits.source.edits.reduce(source) { $1.apply(to: $0) }
105                        let newArchive = destination.isSameFile ? "" : (edits.archive.map { $0.apply(to: archiveText ?? "") } ?? (archiveText ?? ""))
106                        ours.append((label, newSource + "\n@@@@\n" + newArchive, edits.source.selection?.first?.lowerBound ?? caret, false))
107                    case .failure:
108                        ours.append((label, "", 0, true))
109                    }
110                }
111            }
112        }
113        var mismatches = 0
114        for (mine, emacs) in zip(ours, try EmacsOracle.run(cases)) {
115            let failed = !emacs.error.isEmpty
116            let caret = EmacsOracle.offset(emacs.point, in: emacs.text)
117            guard mine.failed != failed || (!failed && (mine.text != emacs.text || mine.caret != caret)) else { continue }
118            mismatches += 1
119            if mismatches <= 8 {
120                let (a, b) = excerpts(mine.text, emacs.text)
121                Issue.record("\(mine.label)\n  ours:  \(mine.failed ? "failed" : "\(a.debugDescription) @\(mine.caret)")\n  emacs: \(failed ? emacs.error : "\(b.debugDescription) @\(caret)")")
122            }
123        }
124        #expect(mismatches == 0, "\(mismatches) of \(ours.count) differ")
125    }
126}