Tests/OrgAppTests/RoamOracleTests.swift
cmc org-roam: aliases, refs, excludes, chooser tags, template choice, capture buffer
ed22b081d6 3 hours ago222 lines · 12016 bytes
1import Foundation
2import OrgCore
3import OrgDocument
4import OrgIndex
5import Testing
6@testable import OrgApp
7
8/// org-roam itself, run in Emacs, when it's installed: the load-path directories in
9/// `ORGSTAR_ROAM` (colon-separated), else a Doom (straight) install.
10enum RoamOracle {
11 static let packages = ["org-roam", "emacsql", "magit-section", "dash", "compat", "llama", "cond-let"]
12
13 static let loadPath: [String]? = {
14 if let paths = ProcessInfo.processInfo.environment["ORGSTAR_ROAM"] { return paths.split(separator: ":").map(String.init) }
15 let fm = FileManager.default, home = NSHomeDirectory()
16 let roots = ["\(home)/.config/emacs/.local/straight", "\(home)/.emacs.d/.local/straight"].flatMap { root in
17 ((try? fm.contentsOfDirectory(atPath: root)) ?? []).filter { $0.hasPrefix("build-") && !$0.hasSuffix(".el") }.sorted().reversed().map { "\(root)/\($0)" }
18 }
19 for root in roots {
20 let dirs = packages.map { "\(root)/\($0)" }.filter { fm.fileExists(atPath: $0) }
21 if dirs.first == "\(root)/org-roam", dirs.count >= 5 { return dirs }
22 }
23 return nil
24 }()
25
26 static var enabled: Bool { loadPath != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil }
27
28 /// Runs `body` with org-roam loaded, `org-roam-directory` at `folder`, its database and
29 /// `org-id-locations-file` in a folder beside it, and the database synced.
30 static func run(_ folder: URL, _ body: String) throws -> String {
31 let paths = loadPath!.map(\.debugDescription).joined(separator: " ")
32 let state = folder.deletingLastPathComponent().appendingPathComponent(folder.lastPathComponent + "-state").path
33 try FileManager.default.createDirectory(atPath: state, withIntermediateDirectories: true)
34 return try DailiesTests.emacs("""
35 (progn (setq load-path (append (list \(paths)) load-path) make-backup-files nil auto-save-default nil create-lockfiles nil
36 coding-system-for-read 'utf-8 coding-system-for-write 'utf-8 org-id-locations-file \((state + "/ids").debugDescription))
37 (require 'org-roam) (require 'org-roam-dailies)
38 (setq org-roam-directory \((folder.path + "/").debugDescription) org-roam-db-location \((state + "/db.sqlite").debugDescription))
39 (org-roam-db-sync)
40 \(body))
41 """)
42 }
43
44 static func folder() throws -> URL {
45 let url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roam-\(UUID().uuidString)").resolvingSymlinksInPath()
46 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
47 return url
48 }
49
50 static func remove(_ folder: URL) {
51 try? FileManager.default.removeItem(at: folder)
52 try? FileManager.default.removeItem(at: folder.deletingLastPathComponent().appendingPathComponent(folder.lastPathComponent + "-state"))
53 }
54
55 /// IDs as one placeholder, since each side makes its own.
56 static func withoutIDs(_ text: String) -> String {
57 text.replacing(/(?m)^:ID:[ \t]+\S+$/, with: ":ID: x")
58 }
59}
60
61struct RoamOracleTests {
62 static let files: [(name: String, text: String)] = [
63 ("a.org", """
64 :PROPERTIES:
65 :ID: f1
66 :ROAM_ALIASES: "Alias One" two "say \\"hi\\""
67 :ROAM_REFS: https://example.com @key2020 [cite:@other2021;@third] [[https://x.org/page][Page]] junk
68 :END:
69 #+title: File One
70 #+filetags: :alpha:beta:
71 * Head :gamma:
72 :PROPERTIES:
73 :ID: h1
74 :ROAM_REFS: @headkey
75 :END:
76 ** Deeper :delta:
77 :PROPERTIES:
78 :ID: h1b
79 :ROAM_ALIASES: Deep
80 :END:
81 * Excl
82 :PROPERTIES:
83 :ID: h2
84 :ROAM_EXCLUDE: t
85 :END:
86 ** Child
87 :PROPERTIES:
88 :ID: h3
89 :END:
90 * ExNil
91 :PROPERTIES:
92 :ID: h4
93 :ROAM_EXCLUDE: nil
94 :END:
95 * No ID :epsilon:
96
97 """),
98 ("b.org", """
99 :PROPERTIES:
100 :ID: f2
101 :ROAM_EXCLUDE: t
102 :END:
103 #+title: Excluded file
104 * Inside
105 :PROPERTIES:
106 :ID: h5
107 :ROAM_ALIASES: x
108 :END:
109
110 """),
111 ("c.org", """
112 :PROPERTIES:
113 :ID: f3
114 :END:
115 #+title: Third
116 * Untitled file's heading
117 :PROPERTIES:
118 :ID: h6
119 :END:
120
121 """),
122 ]
123
124 /// Nodes, aliases, refs and tags as org-roam's database has them after `org-roam-db-sync`.
125 @Test(.enabled(if: RoamOracle.enabled)) func nodesMatchOrgRoam() throws {
126 let folder = try RoamOracle.folder()
127 defer { RoamOracle.remove(folder) }
128 let store = try IndexStore()
129 for file in Self.files {
130 let path = folder.appendingPathComponent(file.name).path
131 try file.text.write(toFile: path, atomically: true, encoding: .utf8)
132 try store.write(FileRecord(path: path, root: folder.path, kind: .org, bytes: Array(file.text.utf8), mtime: 1, settings: IndexSettings()))
133 }
134 let output = try RoamOracle.run(folder, """
135 (dolist (row (org-roam-db-query [:select [id title] :from nodes]))
136 (let ((id (car row)))
137 (princ (format "%s\\t%s\\t%s\\t%s\\t%s\\n" id (cadr row)
138 (string-join (sort (mapcar #'car (org-roam-db-query [:select alias :from aliases :where (= node-id $s1)] id)) #'string<) "|")
139 (string-join (sort (mapcar (lambda (r) (concat (cadr r) ":" (car r))) (org-roam-db-query [:select [ref type] :from refs :where (= node-id $s1)] id)) #'string<) "|")
140 (string-join (sort (mapcar #'car (org-roam-db-query [:select tag :from tags :where (= node-id $s1)] id)) #'string<) "|")))))
141 """)
142 let theirs = output.split(separator: "\n").map(String.init).filter { $0.contains("\t") }.sorted()
143 let ours = try store.nodes().map { node in
144 [node.id, node.title, node.aliases.sorted().joined(separator: "|"), node.refs.sorted().joined(separator: "|"), node.tags.sorted().joined(separator: "|")].joined(separator: "\t")
145 }.sorted()
146 #expect(!theirs.isEmpty)
147 #expect(ours == theirs)
148 }
149
150 /// New nodes from `org-roam-capture-` with `:immediate-finish`: a `file+head` template
151 /// and a `file+head+olp` one, twice, whose headings are made the first time.
152 @MainActor
153 @Test(.enabled(if: RoamOracle.enabled)) func captureMatchesOrgRoam() throws {
154 let theirs = try RoamOracle.folder(), ours = try RoamOracle.folder()
155 defer {
156 RoamOracle.remove(theirs)
157 RoamOracle.remove(ours)
158 }
159 _ = try RoamOracle.run(theirs, """
160 (setq org-roam-capture-templates
161 '(("d" "default" plain "%?" :target (file+head "${slug}.org" "#+title: ${title}\\n") :unnarrowed t :immediate-finish t)
162 ("p" "project" entry "* ${title} %?\\nbody" :target (file+head+olp "proj.org" "#+title: Projects" ("Work" "Active")) :immediate-finish t)
163 ("e" "plain end" plain "Some ${slug} text" :target (file+head "end-${slug}.org" "#+title: ${title}") :immediate-finish t)))
164 (org-roam-capture- :node (org-roam-node-create :title "Field Notes") :keys "d" :props '(:finalize find-file))
165 (org-roam-capture- :node (org-roam-node-create :title "Big Thing") :keys "p" :props '(:finalize find-file))
166 (org-roam-capture- :node (org-roam-node-create :title "Other Thing") :keys "p" :props '(:finalize find-file))
167 (org-roam-capture- :node (org-roam-node-create :title "Café Time") :keys "e" :props '(:finalize find-file))
168 """)
169 let session = DocumentSession(recovery: FileRecoveryStore(directory: ours.appendingPathComponent(".r")))
170 let templates = [
171 RoamTemplate(key: "d", name: "default", kind: .plain, template: "%?", file: "${slug}.org", head: "#+title: ${title}\n"),
172 RoamTemplate(key: "p", name: "project", kind: .entry, template: "* ${title} %?\nbody", file: "proj.org", head: "#+title: Projects", olp: ["Work", "Active"]),
173 RoamTemplate(key: "e", name: "plain end", kind: .plain, template: "Some ${slug} text", file: "end-${slug}.org", head: "#+title: ${title}"),
174 ]
175 for (key, title) in [("d", "Field Notes"), ("p", "Big Thing"), ("p", "Other Thing"), ("e", "Café Time")] {
176 let capture = RoamCapture(templates.filter { $0.key == key }, title: title, directory: ours.path, session: session, refresh: {}) { _, _, _ in }
177 if case .failure(let error) = capture.fileFirst() { Issue.record("\(error.message)") }
178 }
179 for name in ["field_notes.org", "proj.org", "end-cafe_time.org"] {
180 var expected = try String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8)
181 let actual = try String(contentsOf: ours.appendingPathComponent(name), encoding: .utf8)
182 // A plain template of only `%?` leaves an empty line in Emacs, which orgstar's
183 // capture doesn't add, for org-roam or org-capture.
184 if name == "field_notes.org", expected.hasSuffix("\n\n") { expected.removeLast() }
185 #expect(RoamOracle.withoutIDs(actual) == RoamOracle.withoutIDs(expected), "\(name)")
186 }
187 }
188
189 /// `org-roam-dailies-capture-date` with two templates into the same day's file, the second
190 /// under an outline path.
191 @MainActor
192 @Test(.enabled(if: RoamOracle.enabled)) func dailiesCaptureMatchesOrgRoam() throws {
193 let theirs = try RoamOracle.folder(), ours = try RoamOracle.folder()
194 defer {
195 RoamOracle.remove(theirs)
196 RoamOracle.remove(ours)
197 }
198 let seconds = Int(DailiesTests.day.timeIntervalSince1970)
199 try FileManager.default.createDirectory(at: theirs.appendingPathComponent("daily"), withIntermediateDirectories: true)
200 _ = try RoamOracle.run(theirs, """
201 (setq org-roam-dailies-capture-templates
202 '(("d" "default" entry "* Note %?" :target (file+head "%<%Y-%m-%d>.org" "#+title: %<%Y-%m-%d>\\n") :immediate-finish t)
203 ("j" "journal" entry "* Entry %?" :target (file+head+olp "%<%Y-%m-%d>.org" "#+title: %<%Y-%m-%d>\\n" ("Journal")) :immediate-finish t)))
204 (org-roam-dailies--capture (seconds-to-time \(seconds)) nil "d")
205 (org-roam-dailies--capture (seconds-to-time \(seconds)) nil "j")
206 (org-roam-dailies--capture (seconds-to-time \(seconds)) nil "d")
207 """)
208 let session = DocumentSession(recovery: FileRecoveryStore(directory: ours.appendingPathComponent(".r")))
209 let directory = ours.appendingPathComponent("daily").path
210 let templates = [
211 RoamTemplate(key: "d", name: "default", kind: .entry, template: "* Note %?", file: "%<%Y-%m-%d>.org", head: "#+title: %<%Y-%m-%d>\n"),
212 RoamTemplate(key: "j", name: "journal", kind: .entry, template: "* Entry %?", file: "%<%Y-%m-%d>.org", head: "#+title: %<%Y-%m-%d>\n", olp: ["Journal"]),
213 ]
214 for key in ["d", "j", "d"] {
215 let capture = RoamCapture(templates.filter { $0.key == key }, title: "", directory: directory, now: DailiesTests.day, session: session, refresh: {}) { _, _, _ in }
216 if case .failure(let error) = capture.fileFirst() { Issue.record("\(error.message)") }
217 }
218 let expected = try String(contentsOf: theirs.appendingPathComponent("daily/2026-10-11.org"), encoding: .utf8)
219 let actual = try String(contentsOf: ours.appendingPathComponent("daily/2026-10-11.org"), encoding: .utf8)
220 #expect(RoamOracle.withoutIDs(actual) == RoamOracle.withoutIDs(expected))
221 }
222}