Tests/OrgAppTests/DailiesTests.swift

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

338 lines · 22732 bytes

23 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    @MainActor
157    @Test func renamesFolderFromFrontMatter() throws {
158        let h = try Harness()
159        try h.write("20261011T120000--old__x.org", "#+title:      One\n#+filetags:   :y:\n")
160        try h.write("20261011T130000--two.org", "#+title:      Two\n")
161        try h.write("plain.org", "#+title: Plain\n")
162        h.answers = ["folder": "."]
163        h.actions.run("app.node.rename-folder-from-front-matter")
164        #expect(h.names() == ["20261011T120000--one__y.org", "20261011T130000--two.org", "plain.org"])
165        #expect(h.shown == ["Renamed 1 note"])
166    }
167
168    @MainActor
169    @Test func silos() throws {
170        let h = try Harness()
171        let silo = h.folder.appendingPathComponent("silo").path
172        try FileManager.default.createDirectory(atPath: silo, withIntermediateDirectories: true)
173        let defaults = UserDefaults.standard
174        defaults.set(h.folder.path + ":" + silo, forKey: "denoteSiloDirectories")
175        defer { defaults.removeObject(forKey: "denoteSiloDirectories") }
176        h.answers = ["silo": DenoteNote.abbreviated(silo), "title": "In Silo", "keywords": "k"]
177        h.actions.run("app.node.silo-create")
178        #expect(h.asked.first?.choices == [DenoteNote.abbreviated(h.folder.path), DenoteNote.abbreviated(silo)])
179        #expect(h.opened.count == 1 && h.opened[0].hasPrefix(silo + "/") && h.opened[0].hasSuffix("--in-silo__k.org"))
180    }
181
182    @MainActor
183    @Test func sequenceCommands() throws {
184        let h = try Harness()
185        let root = try h.write("20261001T090000==1--root.org", "#+title:      Root\n")
186        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")
187        try h.write("20261003T090000==1=1=1--grandchild.org", "#+title:      Grandchild\n")
188        let third = try h.write("20261004T090000==1=3--third.org", "#+title:      Third\n")
189        try h.write("20261005T090000==2--two.org", "#+title:      Two\n")
190        // A new child of the open note.
191        h.session.open(root)
192        h.answers = ["title": "Kid", "keywords": ""]
193        h.actions.run("app.node.sequence-new-child-of-current")
194        #expect(h.opened.last.map { ($0 as NSString).lastPathComponent }?.hasSuffix("==1=4--kid.org") == true, "\(h.shown)")
195        // The next sibling skips the missing 1=2.
196        h.session.open(child)
197        h.actions.run("app.node.sequence-next-sibling")
198        #expect(h.opened.last == third)
199        // Find: the parent opens at once.
200        h.session.open(child)
201        h.answers = ["relation": "parent"]
202        h.actions.run("app.node.sequence-find")
203        #expect(h.opened.last == root)
204        // Reparenting with descendants under 2.
205        h.session.open(child)
206        h.answers = ["sequence": "20261005T090000==2--two.org"]
207        h.actions.run("app.node.sequence-reparent-recursive")
208        #expect(h.names().contains("20261002T090000==2=1--child__k.org") && h.names().contains("20261003T090000==2=1=1--grandchild.org"), "\(h.names()) \(h.shown)")
209        #expect(try String(contentsOfFile: h.folder.appendingPathComponent("20261002T090000==2=1--child__k.org").path, encoding: .utf8).contains("#+signature:  2=1\n"))
210        // A link to a sequence note says its sequence and title.
211        h.answers = ["sequence": "20261004T090000==1=3--third.org"]
212        h.actions.run("app.node.sequence-link")
213        #expect(h.links.last?.0 == "denote:20261004T090000" && h.links.last?.1 == "1=3  Third")
214    }
215
216    /// `denote-org-capture`: the note's questions first, then the entry filed in it.
217    @MainActor
218    @Test func denoteCapture() throws {
219        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-capture-\(UUID().uuidString)").resolvingSymlinksInPath()
220        defer { try? FileManager.default.removeItem(at: folder) }
221        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
222        let defaults = TestDefaults("orgstar-capture")
223        defaults.set("title signature keywords", forKey: "denotePrompts")
224        let capture = DenoteCapture(roots: [folder.path], paths: ["/x/20260101T000000--a__old.org"], defaults: defaults)
225        #expect(capture.questions.map(\.prompt) == ["New file TITLE", "New file SIGNATURE", "New file KEYWORDS"])
226        #expect(capture.questions[2].choices == ["old"])
227        let path = try capture.create(["Captured", "1a", "b a"], now: Self.day)
228        #expect((path as NSString).lastPathComponent == "20261011T120000==1a--captured__a_b.org")
229        let file = folder.appendingPathComponent("capture.toml")
230        try "[[template]]\nkey = \"n\"\nname = \"Note\"\ndenote = true\ntemplate = \"* %?\"\n".write(to: file, atomically: true, encoding: .utf8)
231        let loaded = CaptureTemplates.load(userFile: file)
232        #expect(loaded.problems.isEmpty, "\(loaded.problems)")
233        let template = try #require(loaded.templates.first)
234        #expect(template.options.denote)
235    }
236
237    /// `denote-prompts` sets the questions after the title and their order.
238    @MainActor
239    @Test func denotePromptsInOrder() throws {
240        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").resolvingSymlinksInPath()
241        defer { try? FileManager.default.removeItem(at: folder) }
242        try FileManager.default.createDirectory(at: folder.appendingPathComponent("work"), withIntermediateDirectories: true)
243        var asked: [String] = []
244        let answers = ["signature": "a1", "subdirectory": "work", "date": "2026-10-11 09:30", "template": "memo", "keywords": "beta, alpha"]
245        var created: String?
246        let actions = RoamActions(session: DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r"))),
247                                  roots: { [folder.path] }, nodes: { [] }, show: { _ in }, ask: { prompt, reply in asked.append(prompt.key); reply(answers[prompt.key]) },
248                                  open: { _, _ in }, insertLink: { _, _ in }, refresh: {})
249        actions.createDenote("Field Notes", roots: [folder.path], prompts: ["title", "signature", "subdirectory", "date", "file-type", "template", "keywords"],
250                             templates: [("report", "* R\n"), ("memo", "* M\n")], keywords: []) { choice in
251            if case .created(let path, _, _) = choice { created = path }
252        }
253        #expect(asked == ["signature", "subdirectory", "date", "template", "keywords"])
254        let path = try #require(created)
255        #expect(path == folder.appendingPathComponent("work/20261011T093000==a1--field-notes__alpha_beta.org").path)
256        #expect(try String(contentsOfFile: path, encoding: .utf8).hasSuffix("#+signature:  a1\n\n* M\n"))
257    }
258
259    @MainActor
260    @Test func renamesFromFrontMatter() throws {
261        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").resolvingSymlinksInPath()
262        defer { try? FileManager.default.removeItem(at: folder) }
263        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
264        let old = folder.appendingPathComponent("20261011T120000--old__x.org").path
265        try "#+title:      Old\n#+filetags:   :x:\n".write(toFile: old, atomically: true, encoding: .utf8)
266        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
267        session.open(old)
268        var opened: String?
269        var shown: [String] = []
270        let actions = RoamActions(session: session, roots: { [folder.path] }, nodes: { [] }, show: { shown.append($0) }, ask: { $1(nil) },
271                                  open: { path, _ in opened = path }, insertLink: { _, _ in }, refresh: {})
272        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) {
273            Issue.record("edit failed"); return
274        }
275        actions.renameFromFrontMatter()
276        let new = folder.appendingPathComponent("20261011T120000--new-name__x_y.org").path
277        #expect(opened == new && !FileManager.default.fileExists(atPath: old), "\(shown)")
278        #expect(try String(contentsOfFile: new, encoding: .utf8) == "#+title:      New Name\n#+filetags:   :x:y:\n")
279    }
280
281    @MainActor
282    @Test func captureFilesTheEntryAtTheEnd() throws {
283        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-daily-\(UUID().uuidString)").resolvingSymlinksInPath()
284        defer { try? FileManager.default.removeItem(at: folder) }
285        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
286        var opened: (String, Int)?
287        let actions = RoamActions(session: session, roots: { [folder.path] }, nodes: { [] }, show: { Issue.record("\($0)") }, ask: { $1(nil) },
288                                  open: { opened = ($0, $1) }, insertLink: { _, _ in }, refresh: {})
289        actions.capture(Self.day)
290        let path = folder.appendingPathComponent("daily/2026-10-11.org").path
291        let text = try String(contentsOfFile: path, encoding: .utf8)
292        #expect(text.hasPrefix(":PROPERTIES:\n:ID:       "))
293        #expect(text.hasSuffix(":END:\n#+title: 2026-10-11\n* \n"))
294        #expect(opened?.0 == path && opened?.1 == (text as NSString).length - 1)
295    }
296
297    /// An index that can't be read is reported, not offered as an empty list of nodes.
298    @MainActor
299    @Test func nodeFindReportsAnIndexError() throws {
300        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roam-\(UUID().uuidString)").resolvingSymlinksInPath()
301        defer { try? FileManager.default.removeItem(at: folder) }
302        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
303        var shown: [String] = []
304        var asked: [String] = []
305        let actions = RoamActions(session: session, roots: { [folder.path] },
306                                  nodes: { throw WorkspaceModel.FileError(message: "Can't read the index: closed") },
307                                  show: { shown.append($0) }, ask: { prompt, _ in asked.append(prompt.key) },
308                                  open: { _, _ in }, insertLink: { _, _ in }, refresh: {})
309        actions.run("app.node.find")
310        #expect(shown == ["Can't read the index: closed"] && asked.isEmpty)
311    }
312}
313
314struct NodeIndexTests {
315    @Test func denoteNotesAreNodes() throws {
316        let store = try IndexStore()
317        let settings = IndexSettings()
318        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))
319        try store.write(FileRecord(path: "/n/20261012T120000--untitled.org", root: "/n", kind: .org, bytes: [], mtime: 1, settings: settings))
320        try store.write(FileRecord(path: "/n/plain.org", root: "/n", kind: .org, bytes: Array("#+title: Plain\n".utf8), mtime: 1, settings: settings))
321        let nodes = try store.denoteNodes()
322        #expect(nodes.map(\.id) == ["20261011T120000", "20261012T120000"])
323        #expect(nodes.map(\.title) == ["A note", "20261012T120000--untitled"])
324    }
325
326    @Test func filesAndHeadingsWithIDsAreNodes() throws {
327        let store = try IndexStore()
328        let settings = IndexSettings()
329        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"
330        try store.write(FileRecord(path: "/n/2026-10-11.org", root: "/n", kind: .org, bytes: Array(text.utf8), mtime: 1, settings: settings))
331        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))
332        let nodes = try store.nodes()
333        #expect(nodes.map(\.id) == ["file-1", "f2", "h-1"])
334        #expect(nodes.map(\.title) == ["Daily", "untitled", "Task"])
335        #expect(try store.headings(withID: "file-1").map(\.ordinal) == [HeadingLocation.fileOrdinal])
336        #expect(try store.headings(withID: "h-1").map(\.title) == ["Task"])
337    }
338}