Tests/OrgAppTests/DailiesTests.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Tests/OrgAppTests/DailiesTests.swift

404 lines · 27484 bytes

25 symbols in this file
  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import OrgIndex
  5import Testing
  6@testable import OrgApp
  7
  8struct DailiesTests {
  9    /// Sun 2026-10-11 12:00 local time.
 10    static var day: Date { Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 11, hour: 12))! }
 11
 12    static func emacs(_ form: String) throws -> String {
 13        let process = Process()
 14        process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
 15        process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
 16        let pipe = Pipe()
 17        process.standardOutput = pipe
 18        process.standardError = FileHandle.nullDevice
 19        try process.run()
 20        let data = pipe.fileHandleForReading.readDataToEndOfFile()
 21        process.waitUntilExit()
 22        return String(decoding: data, as: UTF8.self)
 23    }
 24
 25    /// A new daily note's text: the head under the ID drawer `org-entry-put` makes, and the
 26    /// file name, as org-roam-capture fills them.
 27    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 28    func newNotesMatchEmacs() throws {
 29        let seconds = Int(Self.day.timeIntervalSince1970)
 30        let heads = ["#+title: %<%Y-%m-%d>\n", "#+title: %<%A, %d %B %Y>", "#+title: Day %<%j>\n#+filetags: :daily:\n"]
 31        for head in heads {
 32            let theirs = try Self.emacs("""
 33                (progn (require 'org)
 34                  (let ((head (replace-regexp-in-string "%<\\\\([^>]*\\\\)>" (lambda (m) (format-time-string (match-string 1 m) (seconds-to-time \(seconds)))) \(head.debugDescription) t t)))
 35                    (with-temp-buffer (org-mode) (insert head) (unless (bolp) (insert "\\n"))
 36                      (org-entry-put (point-min) "ID" "abc") (princ (buffer-string)))))
 37                """)
 38            #expect(Dailies(directory: "/n", head: head).newText(Self.day, id: "abc") == theirs, "\(head)")
 39        }
 40        let name = try Self.emacs("(princ (format-time-string \"%Y-%m-%d.org\" (seconds-to-time \(seconds))))")
 41        #expect((Dailies(directory: "/n/daily").path(for: Self.day) as NSString).lastPathComponent == name)
 42    }
 43
 44    @Test func nextAndPreviousNotes() throws {
 45        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-daily-\(UUID().uuidString)").resolvingSymlinksInPath()
 46        defer { try? FileManager.default.removeItem(at: folder) }
 47        let dailies = Dailies(directory: folder.path)
 48        for offset in [-3, -1, 0] { try dailies.ensure(Calendar.current.date(byAdding: .day, value: offset, to: Self.day)!) }
 49        try "x".write(to: folder.appendingPathComponent(".hidden.org"), atomically: true, encoding: .utf8)
 50        let today = dailies.path(for: Self.day)
 51        #expect(dailies.files().map { ($0 as NSString).lastPathComponent } == ["2026-10-08.org", "2026-10-10.org", "2026-10-11.org"])
 52        #expect(try (dailies.neighbor(of: today, by: -1) as NSString).lastPathComponent == "2026-10-10.org")
 53        #expect(throws: Dailies.Failure("Already at newest note")) { try dailies.neighbor(of: today, by: 1) }
 54        #expect(throws: Dailies.Failure("Not in a daily-note")) { try dailies.neighbor(of: "/elsewhere/x.org", by: 1) }
 55        // A new note isn't written over.
 56        #expect(try dailies.ensure(Self.day).created == false)
 57    }
 58
 59    @Test func denoteJournalEntries() throws {
 60        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-journal-\(UUID().uuidString)").resolvingSymlinksInPath()
 61        defer { try? FileManager.default.removeItem(at: folder) }
 62        let journal = Dailies(directory: folder.path, journal: Dailies.Journal())
 63        let made = try journal.ensure(Self.day)
 64        #expect(made.created && (made.path as NSString).lastPathComponent == "20261011T120000--sunday-11-october-2026-1200__journal.org")
 65        #expect(try String(contentsOfFile: made.path, encoding: .utf8).hasPrefix("#+title:      Sunday 11 October 2026 12:00\n#+date:       [2026-10-11 Sun 12:00]\n#+filetags:   :journal:\n"))
 66        // Another time the same day finds the entry.
 67        let later = Calendar.current.date(byAdding: .hour, value: 3, to: Self.day)!
 68        #expect(try journal.ensure(later) == (made.path, false))
 69        try journal.ensure(Calendar.current.date(byAdding: .day, value: -2, to: Self.day)!)
 70        try "x".write(to: folder.appendingPathComponent("20261010T080000--not-a-journal__work.org"), atomically: true, encoding: .utf8)
 71        #expect(journal.files().map { ($0 as NSString).lastPathComponent } == ["20261009T120000--friday-9-october-2026-1200__journal.org", (made.path as NSString).lastPathComponent])
 72        #expect(try (journal.neighbor(of: made.path, by: -1) as NSString).lastPathComponent == "20261009T120000--friday-9-october-2026-1200__journal.org")
 73    }
 74
 75    /// `denote-journal-interval`: one entry a week (Monday to Sunday), month or year.
 76    @Test func denoteJournalIntervals() throws {
 77        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-journal-\(UUID().uuidString)").resolvingSymlinksInPath()
 78        defer { try? FileManager.default.removeItem(at: folder) }
 79        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 80        let entry = folder.appendingPathComponent("20261005T080000--monday__journal.org").path
 81        try "x".write(toFile: entry, atomically: true, encoding: .utf8)
 82        func found(_ interval: String, _ days: Int) -> Bool {
 83            Dailies(directory: folder.path, journal: Dailies.Journal(interval: interval)).path(for: Calendar.current.date(byAdding: .day, value: days, to: Self.day)!) == entry
 84        }
 85        // Self.day is Sunday 11 October 2026.
 86        #expect(found("weekly", 0) && found("weekly", -6) && !found("weekly", 1) && !found("weekly", -7))
 87        #expect(!found("daily", 0) && found("daily", -6))
 88        #expect(found("monthly", 20) && !found("monthly", 21))
 89        #expect(found("yearly", 81) && !found("yearly", 82))
 90    }
 91
 92    @Test func newDenoteNote() throws {
 93        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").path
 94        defer { try? FileManager.default.removeItem(atPath: folder) }
 95        let note = try DenoteNote.create(title: "Field Notes", keywords: ["Work", "ideas"], in: folder, now: Self.day)
 96        #expect((note.path as NSString).lastPathComponent == "20261011T120000--field-notes__ideas_work.org" && note.id == "20261011T120000")
 97        #expect(try String(contentsOfFile: note.path, encoding: .utf8).hasPrefix("#+title:      Field Notes\n"))
 98        // The same second again under the folder: the next unused one, the date unchanged.
 99        let again = try DenoteNote.create(title: "Field Notes", keywords: ["work", "ideas"], in: folder, now: Self.day)
100        #expect((again.path as NSString).lastPathComponent == "20261011T120001--field-notes__ideas_work.org")
101        let sub = (folder as NSString).appendingPathComponent("projects")
102        let other = try DenoteNote.create(title: "Plan", keywords: [], in: sub, roots: [folder], now: Self.day, signature: "Two Words", template: "* Goals\n")
103        #expect((other.path as NSString).lastPathComponent == "20261011T120002==two=words--plan.org")
104        #expect(try String(contentsOfFile: other.path, encoding: .utf8)
105            == "#+title:      Plan\n#+date:       [2026-10-11 Sun 12:00]\n#+filetags:   \n#+identifier: 20261011T120002\n#+signature:  two=words\n\n* Goals\n")
106        #expect(DenoteNote.subdirectories(of: folder) == ["projects"])
107    }
108
109    /// A RoamActions on `folder` that answers each prompt from `answers` by key, recording
110    /// what it asked, what it opened and showed, and links inserted.
111    @MainActor
112    final class Harness {
113        let folder: URL
114        let session: DocumentSession
115        var answers: [String: String] = [:]
116        var asked: [Prompt] = []
117        var opened: [String] = []
118        var shown: [String] = []
119        var links: [(String, String)] = []
120        init() throws {
121            folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").resolvingSymlinksInPath()
122            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
123            session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
124        }
125        deinit { try? FileManager.default.removeItem(at: folder) }
126        var actions: RoamActions {
127            RoamActions(session: session, roots: { [self.folder.path] }, nodes: { [] }, show: { self.shown.append($0) },
128                        ask: { prompt, reply in self.asked.append(prompt); reply(self.answers[prompt.key]) },
129                        open: { path, _ in self.opened.append(path); self.session.open(path) }, insertLink: { self.links.append(($0, $1)) }, refresh: {})
130        }
131        @discardableResult
132        func write(_ name: String, _ text: String) throws -> String {
133            let url = folder.appendingPathComponent(name)
134            try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
135            try text.write(to: url, atomically: true, encoding: .utf8)
136            return url.path
137        }
138        func names() -> [String] { ((try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []).filter { !$0.hasPrefix(".") }.sorted() }
139    }
140
141    /// `denote-rename-file`: the questions start with the current values; the file and its
142    /// front matter change.
143    @MainActor
144    @Test func renamesByPrompting() throws {
145        let h = try Harness()
146        let path = try h.write("20261011T120000--old__x.org", "#+title:      Old\n#+date:       [2026-10-11 Sun 12:00]\n#+filetags:   :x:\n#+identifier: 20261011T120000\n\nBody\n")
147        h.session.open(path)
148        h.answers = ["title": "New Name", "keywords": "b, a"]
149        h.actions.run("app.node.rename")
150        #expect(h.asked.map(\.initial) == ["Old", "x"])
151        let new = h.folder.appendingPathComponent("20261011T120000--new-name__a_b.org").path
152        #expect(h.opened == [new], "\(h.shown)")
153        #expect(try String(contentsOfFile: new, encoding: .utf8) == "#+title:      New Name\n#+date:       [2026-10-11 Sun 12:00]\n#+filetags:   :a:b:\n#+identifier: 20261011T120000\n\nBody\n")
154    }
155
156    /// Markdown and text notes: made in `denote-file-type`, renamed with their front matter in
157    /// their own format, linked to by Insert Node Link, which only Denote may do outside org.
158    @MainActor
159    @Test func textTypeNotes() throws {
160        let h = try Harness()
161        let defaults = UserDefaults.standard
162        defaults.set("denote", forKey: "notesPackage")
163        defaults.set("markdown-toml", forKey: "denoteFileType")
164        defer { defaults.removeObject(forKey: "notesPackage"); defaults.removeObject(forKey: "denoteFileType") }
165        h.answers = ["node": "Field Notes", "keywords": "work"]
166        h.actions.run("app.node.find")
167        let note = try #require(h.opened.first)
168        #expect(note.hasSuffix("--field-notes__work.md"), "\(h.shown)")
169        #expect(try String(contentsOfFile: note, encoding: .utf8).hasPrefix("+++\ntitle      = \"Field Notes\"\ndate       = "))
170
171        let path = try h.write("20261011T120000--old__x.txt", "title:      Old\ndate:       2026-10-11\ntags:       x\nidentifier: 20261011T120000\n---------------------------\n\nBody\n")
172        h.session.open(path)
173        h.opened = []
174        h.answers = ["title": "New Name", "keywords": "b, a"]
175        h.actions.run("app.node.rename")
176        #expect(h.asked.suffix(2).map(\.initial) == ["Old", "x"])
177        let renamed = h.folder.appendingPathComponent("20261011T120000--new-name__a_b.txt").path
178        #expect(h.opened == [renamed], "\(h.shown)")
179        #expect(try String(contentsOfFile: renamed, encoding: .utf8)
180            == "title:      New Name\ndate:       2026-10-11\ntags:       a  b\nidentifier: 20261011T120000\n---------------------------\n\nBody\n")
181
182        let md = try h.write("20261011T130000--edited__x.md", "---\ntitle:      \"Edited Title\"\ntags:       [\"y\"]\nidentifier: \"20261011T130000\"\n---\n")
183        h.session.open(md)
184        h.opened = []
185        h.actions.run("app.node.rename-from-front-matter")
186        #expect(h.opened == [h.folder.appendingPathComponent("20261011T130000--edited-title__y.md").path], "\(h.shown)")
187
188        h.answers = ["node": "Linked Note", "keywords": ""]
189        h.actions.run("app.node.insert")
190        #expect(h.links.last?.1 == "Linked Note" && h.links.last?.0.hasPrefix("denote:") == true)
191        defaults.removeObject(forKey: "notesPackage")
192        let count = h.links.count
193        h.actions.run("app.node.insert")
194        #expect(h.links.count == count && h.shown.last == "Not an org file")
195    }
196
197    @MainActor
198    @Test func renamesFolderFromFrontMatter() throws {
199        let h = try Harness()
200        try h.write("20261011T120000--old__x.org", "#+title:      One\n#+filetags:   :y:\n")
201        try h.write("20261011T130000--two.org", "#+title:      Two\n")
202        try h.write("plain.org", "#+title: Plain\n")
203        h.answers = ["folder": "."]
204        h.actions.run("app.node.rename-folder-from-front-matter")
205        #expect(h.names() == ["20261011T120000--one__y.org", "20261011T130000--two.org", "plain.org"])
206        #expect(h.shown == ["Renamed 1 note"])
207    }
208
209    @MainActor
210    @Test func silos() throws {
211        let h = try Harness()
212        let silo = h.folder.appendingPathComponent("silo").path
213        try FileManager.default.createDirectory(atPath: silo, withIntermediateDirectories: true)
214        let defaults = UserDefaults.standard
215        defaults.set(h.folder.path + ":" + silo, forKey: "denoteSiloDirectories")
216        defer { defaults.removeObject(forKey: "denoteSiloDirectories") }
217        h.answers = ["silo": DenoteNote.abbreviated(silo), "title": "In Silo", "keywords": "k"]
218        h.actions.run("app.node.silo-create")
219        #expect(h.asked.first?.choices == [DenoteNote.abbreviated(h.folder.path), DenoteNote.abbreviated(silo)])
220        #expect(h.opened.count == 1 && h.opened[0].hasPrefix(silo + "/") && h.opened[0].hasSuffix("--in-silo__k.org"))
221    }
222
223    @MainActor
224    @Test func sequenceCommands() throws {
225        let h = try Harness()
226        let root = try h.write("20261001T090000==1--root.org", "#+title:      Root\n")
227        let child = try h.write("20261002T090000==1=1--child__k.org", "#+title:      Child\n#+filetags:   :k:\n#+identifier: 20261002T090000\n#+signature:  1=1\n\nC\n")
228        try h.write("20261003T090000==1=1=1--grandchild.org", "#+title:      Grandchild\n")
229        let third = try h.write("20261004T090000==1=3--third.org", "#+title:      Third\n")
230        try h.write("20261005T090000==2--two.org", "#+title:      Two\n")
231        // A new child of the open note.
232        h.session.open(root)
233        h.answers = ["title": "Kid", "keywords": ""]
234        h.actions.run("app.node.sequence-new-child-of-current")
235        #expect(h.opened.last.map { ($0 as NSString).lastPathComponent }?.hasSuffix("==1=4--kid.org") == true, "\(h.shown)")
236        // The next sibling skips the missing 1=2.
237        h.session.open(child)
238        h.actions.run("app.node.sequence-next-sibling")
239        #expect(h.opened.last == third)
240        // Find: the parent opens at once.
241        h.session.open(child)
242        h.answers = ["relation": "parent"]
243        h.actions.run("app.node.sequence-find")
244        #expect(h.opened.last == root)
245        // Reparenting with descendants under 2.
246        h.session.open(child)
247        h.answers = ["sequence": "20261005T090000==2--two.org"]
248        h.actions.run("app.node.sequence-reparent-recursive")
249        #expect(h.names().contains("20261002T090000==2=1--child__k.org") && h.names().contains("20261003T090000==2=1=1--grandchild.org"), "\(h.names()) \(h.shown)")
250        #expect(try String(contentsOfFile: h.folder.appendingPathComponent("20261002T090000==2=1--child__k.org").path, encoding: .utf8).contains("#+signature:  2=1\n"))
251        // A link to a sequence note says its sequence and title.
252        h.answers = ["sequence": "20261004T090000==1=3--third.org"]
253        h.actions.run("app.node.sequence-link")
254        #expect(h.links.last?.0 == "denote:20261004T090000" && h.links.last?.1 == "1=3  Third")
255    }
256
257    /// `denote-org-capture`: the note's questions first, then the entry filed in it.
258    @MainActor
259    @Test func denoteCapture() throws {
260        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-capture-\(UUID().uuidString)").resolvingSymlinksInPath()
261        defer { try? FileManager.default.removeItem(at: folder) }
262        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
263        let defaults = TestDefaults("orgstar-capture")
264        defaults.set("title signature keywords", forKey: "denotePrompts")
265        let capture = DenoteCapture(roots: [folder.path], paths: ["/x/20260101T000000--a__old.org"], defaults: defaults)
266        #expect(capture.questions.map(\.prompt) == ["New file TITLE", "New file SIGNATURE", "New file KEYWORDS"])
267        #expect(capture.questions[2].choices == ["old"])
268        let path = try capture.create(["Captured", "1a", "b a"], now: Self.day)
269        #expect((path as NSString).lastPathComponent == "20261011T120000==1a--captured__a_b.org")
270        let file = folder.appendingPathComponent("capture.toml")
271        try "[[template]]\nkey = \"n\"\nname = \"Note\"\ndenote = true\ntemplate = \"* %?\"\n".write(to: file, atomically: true, encoding: .utf8)
272        let loaded = CaptureTemplates.load(userFile: file)
273        #expect(loaded.problems.isEmpty, "\(loaded.problems)")
274        let template = try #require(loaded.templates.first)
275        #expect(template.options.denote)
276    }
277
278    /// `denote-prompts` sets the questions after the title and their order.
279    @MainActor
280    @Test func denotePromptsInOrder() throws {
281        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").resolvingSymlinksInPath()
282        defer { try? FileManager.default.removeItem(at: folder) }
283        try FileManager.default.createDirectory(at: folder.appendingPathComponent("work"), withIntermediateDirectories: true)
284        var asked: [String] = []
285        let answers = ["signature": "a1", "subdirectory": "work", "date": "2026-10-11 09:30", "template": "memo", "keywords": "beta, alpha"]
286        var created: String?
287        let actions = RoamActions(session: DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r"))),
288                                  roots: { [folder.path] }, nodes: { [] }, show: { _ in }, ask: { prompt, reply in asked.append(prompt.key); reply(answers[prompt.key]) },
289                                  open: { _, _ in }, insertLink: { _, _ in }, refresh: {})
290        actions.createDenote("Field Notes", roots: [folder.path], prompts: ["title", "signature", "subdirectory", "date", "file-type", "template", "keywords"],
291                             templates: [("report", "* R\n"), ("memo", "* M\n")], keywords: []) { choice in
292            if case .created(let path, _, _, _) = choice { created = path }
293        }
294        #expect(asked == ["signature", "subdirectory", "date", "template", "keywords"])
295        let path = try #require(created)
296        #expect(path == folder.appendingPathComponent("work/20261011T093000==a1--field-notes__alpha_beta.org").path)
297        #expect(try String(contentsOfFile: path, encoding: .utf8).hasSuffix("#+signature:  a1\n\n* M\n"))
298    }
299
300    @MainActor
301    @Test func renamesFromFrontMatter() throws {
302        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").resolvingSymlinksInPath()
303        defer { try? FileManager.default.removeItem(at: folder) }
304        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
305        let old = folder.appendingPathComponent("20261011T120000--old__x.org").path
306        try "#+title:      Old\n#+filetags:   :x:\n".write(toFile: old, atomically: true, encoding: .utf8)
307        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
308        session.open(old)
309        var opened: String?
310        var shown: [String] = []
311        let actions = RoamActions(session: session, roots: { [folder.path] }, nodes: { [] }, show: { shown.append($0) }, ask: { $1(nil) },
312                                  open: { path, _ in opened = path }, insertLink: { _, _ in }, refresh: {})
313        if case .failed = session.perform(ReplaceText(old: "#+title:      Old\n#+filetags:   :x:\n", new: "#+title:      New Name\n#+filetags:   :x:y:\n"), path: old, at: 0, expect: nil) {
314            Issue.record("edit failed"); return
315        }
316        actions.renameFromFrontMatter()
317        let new = folder.appendingPathComponent("20261011T120000--new-name__x_y.org").path
318        #expect(opened == new && !FileManager.default.fileExists(atPath: old), "\(shown)")
319        #expect(try String(contentsOfFile: new, encoding: .utf8) == "#+title:      New Name\n#+filetags:   :x:y:\n#+identifier: 20261011T120000\n")
320    }
321
322    @MainActor
323    @Test func captureFilesTheEntryAtTheEnd() throws {
324        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-daily-\(UUID().uuidString)").resolvingSymlinksInPath()
325        defer { try? FileManager.default.removeItem(at: folder) }
326        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
327        var opened: (String, Int)?
328        var actions = RoamActions(session: session, roots: { [folder.path] }, nodes: { [] }, show: { Issue.record("\($0)") }, ask: { $1(nil) },
329                                  open: { opened = ($0, $1) }, insertLink: { _, _ in }, refresh: {})
330        actions.templates = { (RoamTemplate.defaults($0), []) }
331        actions.capture(Self.day)
332        let path = folder.appendingPathComponent("daily/2026-10-11.org").path
333        let text = try String(contentsOfFile: path, encoding: .utf8)
334        #expect(text.hasPrefix(":PROPERTIES:\n:ID:       "))
335        #expect(text.hasSuffix(":END:\n#+title: 2026-10-11\n* \n"))
336        // Without a capture window, the entry is filed at once and opens where it starts.
337        #expect(opened?.0 == path && opened?.1 == (text as NSString).length - 3)
338    }
339
340    /// An index that can't be read is reported, not offered as an empty list of nodes.
341    @MainActor
342    @Test func nodeFindReportsAnIndexError() throws {
343        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roam-\(UUID().uuidString)").resolvingSymlinksInPath()
344        defer { try? FileManager.default.removeItem(at: folder) }
345        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
346        var shown: [String] = []
347        var asked: [String] = []
348        let actions = RoamActions(session: session, roots: { [folder.path] },
349                                  nodes: { throw WorkspaceModel.FileError(message: "Can't read the index: closed") },
350                                  show: { shown.append($0) }, ask: { prompt, _ in asked.append(prompt.key) },
351                                  open: { _, _ in }, insertLink: { _, _ in }, refresh: {})
352        actions.run("app.node.find")
353        #expect(shown == ["Can't read the index: closed"] && asked.isEmpty)
354    }
355}
356
357struct NodeIndexTests {
358    @Test func denoteNotesAreNodes() throws {
359        let store = try IndexStore()
360        let settings = IndexSettings()
361        try store.write(FileRecord(path: "/n/20261011T120000--a__x.org", root: "/n", kind: .org, bytes: Array("#+title: A note\n".utf8), mtime: 1, settings: settings))
362        try store.write(FileRecord(path: "/n/20261012T120000--untitled.org", root: "/n", kind: .org, bytes: [], mtime: 1, settings: settings))
363        try store.write(FileRecord(path: "/n/plain.org", root: "/n", kind: .org, bytes: Array("#+title: Plain\n".utf8), mtime: 1, settings: settings))
364        let nodes = try store.denoteNodes()
365        #expect(nodes.map(\.id) == ["20261011T120000", "20261012T120000"])
366        #expect(nodes.map(\.title) == ["A note", "20261012T120000--untitled"])
367    }
368
369    /// Markdown and text notes are nodes too, titled by their front matter; their Denote links
370    /// are backlinks.
371    @Test func denoteTextNotesAreNodesAndLink() throws {
372        let store = try IndexStore()
373        let settings = IndexSettings()
374        try store.write(FileRecord(path: "/n/20261011T120000--a__x.org", root: "/n", kind: .org, bytes: Array("#+title: A note\n".utf8), mtime: 1, settings: settings))
375        try store.write(FileRecord(path: "/n/20261013T120000--m.md", root: "/n", kind: .text,
376                                   bytes: Array("---\ntitle: \"Markdown\"\n---\nSee [A](denote:20261011T120000).\n# Part\nAnd [[denote:20261014T120000][T]].\n".utf8), mtime: 1, settings: settings))
377        try store.write(FileRecord(path: "/n/20261014T120000--t.txt", root: "/n", kind: .text,
378                                   bytes: Array("title:      Text note\nidentifier: 20261014T120000\n---------------------------\n\n[[denote:20261011T120000]]\n".utf8), mtime: 1, settings: settings))
379        try store.write(FileRecord(path: "/n/20261015T120000--other.markdown", root: "/n", kind: .text, bytes: Array("# Other\n".utf8), mtime: 1, settings: settings))
380        let nodes = try store.denoteNodes()
381        #expect(nodes.map(\.id) == ["20261011T120000", "20261013T120000", "20261014T120000"])
382        #expect(nodes.map(\.title) == ["A note", "Markdown", "Text note"])
383        let links = try store.links()
384        #expect(links.map(\.target).sorted() == ["denote:20261011T120000", "denote:20261011T120000", "denote:20261014T120000"])
385        #expect(links.first { $0.target == "denote:20261014T120000" }?.source.title == "Part")
386        let target = Backlinks.Target(path: "/n/20261011T120000--a__x.org")
387        #expect(links.filter { Backlinks.links($0.target, from: $0.source.path, to: target) }.map(\.source.path).sorted()
388            == ["/n/20261013T120000--m.md", "/n/20261014T120000--t.txt"])
389        #expect(Backlinks.context(in: "See [A](denote:20261011T120000) and [[denote:x][X]].", link: "denote:20261011T120000")?.text == "See A and X.")
390    }
391
392    @Test func filesAndHeadingsWithIDsAreNodes() throws {
393        let store = try IndexStore()
394        let settings = IndexSettings()
395        let text = ":PROPERTIES:\n:ID:       file-1\n:END:\n#+title: Daily\n* Task\n:PROPERTIES:\n:ID: h-1\n:END:\n* Plain\n"
396        try store.write(FileRecord(path: "/n/2026-10-11.org", root: "/n", kind: .org, bytes: Array(text.utf8), mtime: 1, settings: settings))
397        try store.write(FileRecord(path: "/n/untitled.org", root: "/n", kind: .org, bytes: Array(":PROPERTIES:\n:ID: f2\n:END:\n".utf8), mtime: 1, settings: settings))
398        let nodes = try store.nodes()
399        #expect(nodes.map(\.id) == ["file-1", "f2", "h-1"])
400        #expect(nodes.map(\.title) == ["Daily", "untitled", "Task"])
401        #expect(try store.headings(withID: "file-1").map(\.ordinal) == [HeadingLocation.fileOrdinal])
402        #expect(try store.headings(withID: "h-1").map(\.title) == ["Task"])
403    }
404}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form