Tests/OrgAppTests/DenoteOracleTests.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Tests/OrgAppTests/DenoteOracleTests.swift history · blame · raw

321 lines · 22350 bytes

6 symbols in this file
  1import Foundation
  2import Testing
  3@testable import OrgApp
  4@testable import OrgCore
  5
  6/// Denote and denote-journal themselves, run in Emacs, when they're installed: the load-path
  7/// directories in `ORGSTAR_DENOTE` (colon-separated), else a Doom or package.el install.
  8struct DenoteOracleTests {
  9    /// The load-path directories of denote and denote-journal, and of denote-org and
 10    /// denote-sequence when they're there too.
 11    static let loadPath: [String]? = {
 12        if let paths = ProcessInfo.processInfo.environment["ORGSTAR_DENOTE"] { return paths.split(separator: ":").map(String.init) }
 13        let fm = FileManager.default, home = NSHomeDirectory()
 14        let roots = ["\(home)/.config/emacs/.local/straight", "\(home)/.emacs.d/.local/straight"].flatMap { root in
 15            ((try? fm.contentsOfDirectory(atPath: root)) ?? []).filter { $0.hasPrefix("build-") }.sorted().reversed().map { "\(root)/\($0)" }
 16        } + ["\(home)/.emacs.d/elpa", "\(home)/.config/emacs/elpa"]
 17        for root in roots {
 18            let names = (try? fm.contentsOfDirectory(atPath: root)) ?? []
 19            let dirs = ["denote", "denote-journal", "denote-org", "denote-sequence"].compactMap { package in
 20                names.filter { $0 == package || ($0.hasPrefix(package + "-") && $0.dropFirst(package.count + 1).first?.isNumber == true) }
 21                    .sorted().last.map { "\(root)/\($0)" }
 22            }
 23            if dirs.count >= 2, dirs[0].hasSuffix("/denote") || dirs[0].contains("/denote-") { return dirs }
 24        }
 25        return nil
 26    }()
 27
 28    static func has(_ package: String) -> Bool { enabled && loadPath!.contains { ($0 as NSString).lastPathComponent == package || ($0 as NSString).lastPathComponent.hasPrefix(package + "-") && ($0 as NSString).lastPathComponent.dropFirst(package.count + 1).first?.isNumber == true } }
 29
 30    static var enabled: Bool { loadPath != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil }
 31
 32    /// Runs `body` with Denote loaded, `denote-directory` at `folder` and nothing backed up.
 33    static func denote(_ folder: URL, _ body: String) throws {
 34        let paths = loadPath!.map(\.debugDescription).joined(separator: " ")
 35        _ = try DailiesTests.emacs("""
 36            (progn (setq load-path (append (list \(paths)) load-path) make-backup-files nil auto-save-default nil create-lockfiles nil
 37                         coding-system-for-read 'utf-8 coding-system-for-write 'utf-8)
 38              (require 'denote) (require 'denote-journal)
 39              (setq denote-directory \((folder.path + "/").debugDescription) denote-rename-confirmations nil)
 40              \(body))
 41            """)
 42    }
 43
 44    static func folder() throws -> URL {
 45        let url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").resolvingSymlinksInPath()
 46        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
 47        return url
 48    }
 49
 50    static func lines(_ url: URL) throws -> [String] {
 51        try String(contentsOf: url, encoding: .utf8).split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
 52    }
 53
 54    @Test(.enabled(if: enabled)) func slugsMatchDenote() throws {
 55        let titles = ["Hello, World: a_test -- Note!", "  Café au lait  ", "C++ & Rust!", "Привет мир", "x=y/z", "a  -  b", "It's [done]", "日本語のノート", "a <b> c\\d"]
 56        let words = ["Emacs", "org-mode", "two words", "a_b", "Café", "x=1"]
 57        let dir = try Self.folder()
 58        defer { try? FileManager.default.removeItem(at: dir) }
 59        let input = dir.appendingPathComponent("in.txt"), output = dir.appendingPathComponent("out.txt")
 60        try (titles + words).joined(separator: "\n").write(to: input, atomically: true, encoding: .utf8)
 61        try Self.denote(dir, """
 62            (let ((lines (split-string (with-temp-buffer (insert-file-contents \(input.path.debugDescription)) (buffer-string)) "\\n")))
 63              (with-temp-file \(output.path.debugDescription)
 64                (dotimes (i (length lines))
 65                  (insert (denote-sluggify (if (< i \(titles.count)) 'title 'keyword) (nth i lines)) "\\n"))))
 66            """)
 67        let theirs = try Self.lines(output)
 68        #expect(Array(theirs.prefix(titles.count)) == titles.map(Denote.slug))
 69        #expect(Array(theirs.dropFirst(titles.count).prefix(words.count)) == words.map(Denote.keyword))
 70    }
 71
 72    /// A note, a journal entry and a rename, as files Denote and orgstar each make.
 73    @Test(.enabled(if: enabled)) func filesMatchDenote() throws {
 74        let theirs = try Self.folder(), ours = try Self.folder()
 75        defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
 76        let front = "#+title:      New Title\n#+signature:  Two Words\n#+filetags:   :Zeta:alpha:\n#+identifier: 20261011T080000\n\nBody\n"
 77        let old = "20261011T080000==1a--old__x.org"
 78        for dir in [theirs, ours] { try front.write(to: dir.appendingPathComponent(old), atomically: true, encoding: .utf8) }
 79        try Self.denote(theirs, """
 80            (progn
 81              (denote "Field Notes" (denote-keywords-sort (list "work" "ideas")) 'org nil "2026-10-11 12:00:05")
 82              (save-buffer)
 83              (let ((denote-journal-directory nil)) (denote-journal-new-entry "2026-10-11 12:00:00") (save-buffer))
 84              (denote-rename-file-using-front-matter \(theirs.appendingPathComponent(old).path.debugDescription)))
 85            """)
 86        _ = try DenoteNote.create(title: "Field Notes", keywords: ["work", "ideas"], in: ours.path, now: DailiesTests.day.addingTimeInterval(5))
 87        _ = try Dailies(directory: ours.path, journal: Dailies.Journal()).ensure(DailiesTests.day)
 88        let renamed = Denote.renamed(ours.appendingPathComponent(old).path, text: front)!
 89        try FileManager.default.moveItem(atPath: ours.appendingPathComponent(old).path, toPath: renamed)
 90
 91        let names = try FileManager.default.contentsOfDirectory(atPath: theirs.path).sorted()
 92        #expect(names.count == 3)
 93        #expect(try FileManager.default.contentsOfDirectory(atPath: ours.path).sorted() == names)
 94        for name in names {
 95            #expect(try String(contentsOf: ours.appendingPathComponent(name), encoding: .utf8)
 96                == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)")
 97        }
 98    }
 99
100    /// A note in a subfolder with a signature and a template, dated a second some file's
101    /// identifier already has.
102    @Test(.enabled(if: enabled)) func optionsMatchDenote() throws {
103        let theirs = try Self.folder(), ours = try Self.folder()
104        defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
105        let taken = "20261011T093000--taken.org"
106        for dir in [theirs, ours] {
107            try FileManager.default.createDirectory(at: dir.appendingPathComponent("work"), withIntermediateDirectories: true)
108            try "x\n".write(to: dir.appendingPathComponent(taken), atomically: true, encoding: .utf8)
109        }
110        let template = "* Goals\n\n* Notes\n"
111        try Self.denote(theirs, """
112            (let ((denote-templates '((plan . \(template.debugDescription)))))
113              (denote "Q4 Plan: draft" (denote-keywords-sort (list "work" "ideas")) 'org \(theirs.appendingPathComponent("work/").path.debugDescription)
114                      "2026-10-11 09:30" 'plan "Part One")
115              (save-buffer))
116            """)
117        let date = try #require(RoamActions.date("2026-10-11 09:30"))
118        _ = try DenoteNote.create(title: "Q4 Plan: draft", keywords: ["work", "ideas"], in: ours.appendingPathComponent("work").path, roots: [ours.path],
119                                  now: date, signature: "Part One", template: template)
120        let names = try FileManager.default.contentsOfDirectory(atPath: theirs.appendingPathComponent("work").path)
121        #expect(names.count == 1)
122        #expect(try FileManager.default.contentsOfDirectory(atPath: ours.appendingPathComponent("work").path) == names)
123        for name in names {
124            #expect(try String(contentsOf: ours.appendingPathComponent("work/" + name), encoding: .utf8)
125                == String(contentsOf: theirs.appendingPathComponent("work/" + name), encoding: .utf8), "\(name)")
126        }
127    }
128
129    /// denote-org's dynamic blocks, each updated in a note by Emacs and by orgstar.
130    @Test(.enabled(if: has("denote-org"))) func blocksMatchDenoteOrg() throws {
131        let dir = try Self.folder()
132        defer { try? FileManager.default.removeItem(at: dir) }
133        try FileManager.default.createDirectory(at: dir.appendingPathComponent("sub"), withIntermediateDirectories: true)
134        let notes = [
135            "20261001T090000--alpha-note__emacs_work.org": "#+title:      Alpha Note\n#+filetags:   :emacs:work:\n#+identifier: 20261001T090000\n\n* First\nSee [[denote:20261119T120000][Current]].\n** Deeper\n#+begin_src sh\necho\n#+end_src\n",
136            "20261002T090000==1a--beta__emacs.org": "#+title:      Beta\n#+filetags:   :emacs:\n#+identifier: 20261002T090000\n\nBeta body.\n",
137            "sub/20260930T090000--gamma-in-sub__work.org": "#+title:      Gamma in Sub\n#+filetags:   :work:\n#+identifier: 20260930T090000\n\nGamma links [[denote:20261119T120000::#top][here]].\n",
138            "20261003T090000--delta__misc.md": "---\ntitle: Delta\n---\n\nDelta.\n",
139            "plain.org": "* Not a note\n",
140            "20261004T090000==1--root__seq.org": "#+title:      Root\n\nR\n",
141            "20261005T090000==1=1--first__seq.org": "#+title:      First\n\nF\n",
142            "20261006T090000==1=2--second__seq.org": "#+title:      Second\n\nS\n",
143            "20261007T090000==1=1=1--deep__seq.org": "#+title:      Deep\n\nD\n",
144            "20261008T090000==2--other__seq.org": "#+title:      Other\n\nO\n",
145        ]
146        for (name, text) in notes { try text.write(to: dir.appendingPathComponent(name), atomically: true, encoding: .utf8) }
147        let current = dir.appendingPathComponent("20261119T120000--current.org")
148        let head = "#+title:      Current\n#+identifier: 20261119T120000\n\nAlready: [[denote:20261002T090000][Beta]]\n\n"
149        let blocks = [
150            "denote-links :regexp \"_emacs\"",
151            "denote-links :regexp \".\" :sort-by-component title :reverse-sort t",
152            "denote-links :regexp \"_work\" :id-only t",
153            "denote-links :regexp \"_work\" :include-date t :block-name \"mine\"",
154            "denote-links :regexp \".\" :not-regexp \"sub\" :sort-by-component signature",
155            "denote-missing-links :regexp \".\"",
156            "denote-backlinks",
157            "denote-files :regexp \"beta\"",
158            "denote-files :regexp \"_work\" :no-front-matter t :add-links t :file-separator t",
159            "denote-files :regexp \"_work\" :no-front-matter 2",
160            "denote-files-as-headings :regexp \"_work\"",
161            "denote-files-as-headings :regexp \"_work\" :add-links t :exclude-tags t",
162            "denote-sequence :sequence \"1\" :depth 2",
163            "denote-sequence :sequence \"1=1\"",
164            "denote-sequence :sequence \"\"",
165        ]
166        let paths = Self.loadPath!.map(\.debugDescription).joined(separator: " ")
167        for block in blocks {
168            let text = head + "#+BEGIN: \(block)\nold\n#+END:\n"
169            try text.write(to: current, atomically: true, encoding: .utf8)
170            let theirs = try DailiesTests.emacs("""
171                (progn (setq load-path (append (list \(paths)) load-path) coding-system-for-read 'utf-8 coding-system-for-write 'utf-8)
172                  (require 'org) (require 'denote) (require 'denote-sequence nil t) (require 'denote-org)
173                  (setq denote-directory \((dir.path + "/").debugDescription))
174                  (find-file \(current.path.debugDescription))
175                  (goto-char (point-min)) (re-search-forward "^#\\\\+BEGIN:") (beginning-of-line)
176                  (org-update-dblock)
177                  (princ (buffer-string)))
178                """)
179            var options = EditingOptions.org
180            options.filePath = current.path
181            options.denoteDirectories = [dir.path]
182            let begin = (text as NSString).range(of: "#+BEGIN:").location
183            let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [begin..<begin], options: options)
184            var ours = text
185            if case .commit(let result) = UpdateDynamicBlock().run(in: context) {
186                for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { ours = edit.apply(to: ours) }
187            } else {
188                ours = "failed"
189            }
190            #expect(ours == theirs, "\(block)\nours:\n\(ours)\ntheirs:\n\(theirs)")
191        }
192        // The insert commands, at the end of a line of text and on an empty line.
193        let inserts: [(lisp: String, kind: InsertDenoteBlock.Kind, answers: [String: String])] = [
194            ("(denote-org-dblock-insert-links \"_emacs\")", .links, ["regexp": "_emacs"]),
195            ("(denote-org-dblock-insert-missing-links \".\")", .missingLinks, ["regexp": "."]),
196            ("(denote-org-dblock-insert-backlinks)", .backlinks, [:]),
197            ("(denote-org-dblock-insert-files \"beta\" 'title)", .files, ["regexp": "beta", "sort": "title"]),
198            ("(denote-org-dblock-insert-files-as-headings \"_work\" nil)", .filesAsHeadings, ["regexp": "_work", "sort": ""]),
199            ("(denote-org-dblock-insert-sequence \(dir.appendingPathComponent("20261004T090000==1--root__seq.org").path.debugDescription) 2)", .sequence,
200             ["sequence": "20261004T090000==1--root__seq.org", "depth": "2"]),
201        ]
202        for (lisp, kind, answers) in inserts {
203            for text in [head + "Last line", head] {
204                try text.write(to: current, atomically: true, encoding: .utf8)
205                let theirs = try DailiesTests.emacs("""
206                    (progn (setq load-path (append (list \(paths)) load-path) coding-system-for-read 'utf-8 coding-system-for-write 'utf-8)
207                      (require 'org) (require 'denote) (require 'denote-sequence nil t) (require 'denote-org)
208                      (setq denote-directory \((dir.path + "/").debugDescription))
209                      (find-file \(current.path.debugDescription))
210                      (goto-char (point-max))
211                      \(lisp)
212                      (princ (buffer-string)))
213                    """)
214                var options = EditingOptions.org
215                options.filePath = current.path
216                options.denoteDirectories = [dir.path]
217                let end = (text as NSString).length
218                let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [end..<end], answers: answers, options: options)
219                var ours = text
220                if case .commit(let result) = InsertDenoteBlock(kind).run(in: context) {
221                    for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { ours = edit.apply(to: ours) }
222                } else {
223                    ours = "failed"
224                }
225                #expect(ours == theirs, "\(lisp)\nours:\n\(ours)\ntheirs:\n\(theirs)")
226            }
227        }
228    }
229
230    /// denote-sequence's new parents, children and siblings, relatives and conversions, for
231    /// notes in each scheme, from Emacs and from orgstar.
232    @Test(.enabled(if: has("denote-sequence"))) func sequencesMatchDenoteSequence() throws {
233        let sets: [(DenoteSequence.Scheme, [String])] = [
234            (.numeric, ["1", "1=1", "1=2", "1=1=1", "1=1=1=1", "2", "3=1", "10", "10=9", "10=10", "2=1=5"]),
235            (.alphanumeric, ["1", "1a", "1b", "1a1", "1a2", "1z", "2", "2a1a", "3", "1za"]),
236            (.alphanumericDelimited, ["1", "1=a", "1=b", "1=a1b", "1=a1b=1", "2", "2=a", "1=a2"]),
237        ]
238        let paths = Self.loadPath!.map(\.debugDescription).joined(separator: " ")
239        for (scheme, sequences) in sets {
240            let dir = try Self.folder()
241            defer { try? FileManager.default.removeItem(at: dir) }
242            for (index, sequence) in sequences.enumerated() {
243                try "x\n".write(to: dir.appendingPathComponent(String(format: "20260101T%06d==%@--n%d.org", index, sequence, index)), atomically: true, encoding: .utf8)
244            }
245            let names = sequences.map(\.debugDescription).joined(separator: " ")
246            let relations = DenoteSequence.Relation.allCases.map(\.rawValue).joined(separator: " ")
247            let theirs = try DailiesTests.emacs("""
248                (progn (setq load-path (append (list \(paths)) load-path))
249                  (require 'denote) (require 'denote-sequence)
250                  (setq denote-directory \((dir.path + "/").debugDescription) denote-sequence-scheme '\(scheme.rawValue))
251                  (defmacro try (form) `(condition-case nil ,form (error "ERR")))
252                  (princ (format "parent %s\\n" (try (denote-sequence-get-new 'parent))))
253                  (dolist (s (list \(names)))
254                    (princ (format "child %s %s\\n" s (try (denote-sequence-get-new 'child s))))
255                    (princ (format "sibling %s %s\\n" s (try (denote-sequence-get-new 'sibling s))))
256                    (dolist (target '(numeric alphanumeric alphanumeric-delimited))
257                      (princ (format "convert %s %s %s\\n" s target (try (denote-sequence-make-conversion s target)))))
258                    (dolist (relation '(\(relations)))
259                      (princ (format "%s %s %s\\n" relation s
260                                     (try (let ((found (denote-sequence-get-relative s relation)))
261                                            (string-join (sort (mapcar #'file-name-nondirectory (if (stringp found) (list found) found)) #'string<) ","))))))))
262                """)
263            let model = DenoteSequence(scheme: scheme)
264            let files = DenoteSequence.files(DenoteBlocks.files(in: [dir.path]).map(\.path))
265            let all = files.map(\.sequence)
266            func attempt(_ body: () throws -> String) -> String { (try? body()) ?? "ERR" }
267            var ours = "parent \(attempt { try model.newParent(among: all) })\n"
268            for s in sequences {
269                ours += "child \(s) \(attempt { try model.newChild(of: s, among: all) })\n"
270                ours += "sibling \(s) \(attempt { try model.newSibling(of: s, among: all) })\n"
271                for target in DenoteSequence.Scheme.allCases {
272                    ours += "convert \(s) \(target.rawValue) \(attempt { try model.converted(s, to: target) })\n"
273                }
274                for relation in DenoteSequence.Relation.allCases {
275                    ours += "\(relation.rawValue) \(s) \(attempt { try model.relatives(of: s, relation, in: files).map { ($0 as NSString).lastPathComponent }.sorted().joined(separator: ",") })\n"
276                }
277            }
278            let theirLines = theirs.split(separator: "\n").map(String.init), ourLines = ours.split(separator: "\n").map(String.init)
279            #expect(theirLines.count == ourLines.count, "\(scheme)\n\(theirs)")
280            for (a, b) in zip(ourLines, theirLines) where a != b {
281                Issue.record("\(scheme): ours \(a) | theirs \(b)")
282            }
283        }
284    }
285
286    /// `denote-rename-file` with a new title, keywords, signature and date: on a note, on one
287    /// whose signature goes, and on a file without front matter or identifier.
288    @Test(.enabled(if: enabled)) func renamesMatchDenote() throws {
289        let theirs = try Self.folder(), ours = try Self.folder()
290        defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
291        let files = [
292            "20261011T120000--old-title__x.org": "#+title:      Old Title\n#+date:       [2026-10-11 Sun 12:00]\n#+filetags:   :x:\n#+identifier: 20261011T120000\n#+startup: overview\n\nBody\n",
293            "20261011T130000==zz--has-sig.org": "#+title:      Has Sig\n#+date:       [2026-10-11 Sun 12:00]\n#+filetags:   \n#+identifier: 20261011T130000\n#+signature:  zz\n\nBody\n",
294            "plain.org": "* Heading\nNo front matter\n",
295        ]
296        for dir in [theirs, ours] { for (name, text) in files { try text.write(to: dir.appendingPathComponent(name), atomically: true, encoding: .utf8) } }
297        let renames: [(file: String, title: String, keywords: [String], signature: String)] = [
298            ("20261011T120000--old-title__x.org", "New Title", ["zeta", "Alpha"], "Part One"),
299            ("20261011T130000==zz--has-sig.org", "Has Sig", [], ""),
300            ("plain.org", "Plain Note", ["k"], ""),
301        ]
302        let calls = renames.map { r in
303            "(denote-rename-file \(theirs.appendingPathComponent(r.file).path.debugDescription) \(r.title.debugDescription) (list \(r.keywords.map(\.debugDescription).joined(separator: " "))) \(r.signature.debugDescription) \"2026-10-11 12:00:00\" \((Denote.identifier(ofFile: r.file) ?? "").debugDescription))"
304        }.joined(separator: "\n")
305        try Self.denote(theirs, calls + "\n(save-some-buffers t)")
306        let date = Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 11, hour: 12))!
307        for r in renames {
308            let path = ours.appendingPathComponent(r.file).path
309            let text = try String(contentsOfFile: path, encoding: .utf8)
310            let (target, rewritten) = DenoteNote.renaming(path, text: text, title: r.title, keywords: r.keywords, signature: r.signature, date: date, roots: [ours.path])
311            try rewritten.write(toFile: path, atomically: true, encoding: .utf8)
312            if target != path { try FileManager.default.moveItem(atPath: path, toPath: target) }
313        }
314        let names = try FileManager.default.contentsOfDirectory(atPath: theirs.path).sorted()
315        #expect(try FileManager.default.contentsOfDirectory(atPath: ours.path).sorted() == names)
316        for name in names {
317            #expect(try String(contentsOf: ours.appendingPathComponent(name), encoding: .utf8)
318                == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)")
319        }
320    }
321}