Tests/OrgAppTests/AppTests.swift

618504036c53cf3c7621b45e97b4d5473e247ccc
orgstar/Tests/OrgAppTests/AppTests.swift

870 lines · 41304 bytes

  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import OrgIndex
  5import Testing
  6@testable import OrgApp
  7
  8/// A temporary folder that removes itself.
  9final class Folder {
 10    let url: URL
 11
 12    init() throws {
 13        url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)").standardizedFileURL
 14        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
 15    }
 16
 17    deinit {
 18        try? FileManager.default.removeItem(at: url)
 19    }
 20
 21    @discardableResult
 22    func write(_ path: String, _ text: String) throws -> URL {
 23        let file = url.appendingPathComponent(path)
 24        try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
 25        try Data(text.utf8).write(to: file)
 26        return file.standardizedFileURL
 27    }
 28}
 29
 30struct FileTreeTests {
 31    @Test func foldersFirstThenFiles() {
 32        let files = ["b.org", "a/z.org", "a/y.org", "c.sync-conflict-1.org", "a2.org"].map {
 33            FileEntry(path: "/r/" + $0, root: "/r", kind: $0.contains("conflict") ? .conflict : .org)
 34        }
 35        let tree = FileTreeNode.build(root: "/r", files: files)
 36        #expect(tree.children?.map(\.name) == ["a", "a2.org", "b.org", "c.sync-conflict-1.org"])
 37        #expect(tree.children?[0].children?.map(\.name) == ["y.org", "z.org"])
 38        #expect(tree.children?[1].children == nil)
 39    }
 40
 41    @Test func fuzzyMatching() {
 42        #expect(FuzzyMatch.score("wn", "work/notes.org") != nil)
 43        #expect(FuzzyMatch.score("xyz", "work/notes.org") == nil)
 44        let files = ["work/notes.org", "notes.org", "personal/wine.org"].map { FileEntry(path: "/r/" + $0, root: "/r", kind: .org) }
 45        #expect(FuzzyMatch.rank("notes", files).map(\.relativePath) == ["notes.org", "work/notes.org"])
 46        #expect(FuzzyMatch.rank("", files).count == 3)
 47    }
 48}
 49
 50@MainActor
 51struct WorkspaceModelTests {
 52    @Test func addSearchRemoveAndPersist() async throws {
 53        let notes = try Folder()
 54        let support = try Folder()
 55        try notes.write("a.org", "* Groceries\nbuy apples\n")
 56        try notes.write("sub/b.org", "* Taxes\n")
 57        try notes.write("c.sync-conflict-1.org", "* Taxes copy\n")
 58
 59        let model = try WorkspaceModel(directory: support.url)
 60        try await model.addRoot(notes.url)
 61        #expect(model.files.count == 3)
 62        #expect(model.search("apples").map(\.title) == ["Groceries"])
 63        #expect(model.quickOpen("bo").map(\.name) == ["b.org"])
 64        let root = try #require(model.rootPaths.first)
 65        #expect(model.tree(forRoot: root).children?.map(\.name) == ["sub", "a.org", "c.sync-conflict-1.org"])
 66
 67        let reopened = try WorkspaceModel(directory: support.url)
 68        #expect(reopened.roots.count == 1)
 69        #expect(reopened.files.count == 3)
 70
 71        try reopened.removeRoot(path: root)
 72        #expect(reopened.roots.isEmpty)
 73        #expect(reopened.files.isEmpty)
 74        #expect(reopened.search("apples").isEmpty)
 75    }
 76
 77    @Test func listsDownloadsInTheTree() {
 78        let files = [FileEntry(path: "/r/a.org", root: "/r", kind: .org)]
 79        let tree = FileTreeNode.build(root: "/r", files: files, downloading: ["/r/b.org", "/r/sub/c.org"])
 80        #expect(tree.children?.map(\.name) == ["sub", "a.org", "b.org"])
 81        #expect(tree.children?[2].isDownloading == true && tree.children?[2].file == nil)
 82        #expect(tree.children?[0].children?.map(\.name) == ["c.org"])
 83    }
 84
 85    @Test func findsBacklinks() async throws {
 86        let notes = try Folder()
 87        try notes.write("a.org", "* Sink\n:PROPERTIES:\n:ID: s-1\n:CUSTOM_ID: sink\n:END:\nsee [[*Taps]]\n* Taps\n")
 88        try notes.write("b.org", "* Plumbing\n[[id:s-1][the sink]] and [[file:a.org]]\n* Other\n[[file:a.org::#sink]] [[https://x.org]]\n")
 89        let model = try WorkspaceModel(directory: nil)
 90        try await model.addRoot(notes.url)
 91        let a = try #require(model.files.first { $0.path.hasSuffix("/a.org") }).path
 92        let sink = Backlinks.Target(path: a, title: "Sink", id: "s-1", customID: "sink")
 93        #expect(model.backlinks(to: sink).map(\.title) == ["Plumbing", "Other"])
 94        #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing"])
 95        #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
 96        #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other"])
 97    }
 98
 99    @Test func createRenameAndTrashFiles() async throws {
100        let notes = try Folder()
101        try notes.write("a.org", "* Alpha\n")
102        let model = try WorkspaceModel(directory: nil)
103        model.trasher = { try FileManager.default.removeItem(at: $0) }
104        try await model.addRoot(notes.url)
105        let root = try #require(model.rootPaths.first)
106
107        let created = try await model.createFile(named: "projects/plan", in: root)
108        #expect(created == root + "/projects/plan.org")
109        #expect(model.files.map(\.path).contains(created))
110        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "projects/plan.org", in: root) }
111        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "../escape", in: root) }
112
113        let renamed = try await model.rename(created, to: "roadmap.org")
114        #expect(model.files.map(\.path).contains(renamed) && !model.files.map(\.path).contains(created))
115        let folder = try await model.rename(root + "/projects", to: "work")
116        #expect(model.files.map(\.path).contains(folder + "/roadmap.org"))
117
118        try await model.trash(folder + "/roadmap.org")
119        #expect(!FileManager.default.fileExists(atPath: folder + "/roadmap.org"))
120        #expect(!model.files.map(\.path).contains(folder + "/roadmap.org"))
121        #expect(model.search("alpha").count == 1)
122    }
123
124    /// Watching starts with no folders (a first launch); a folder added afterwards is
125    /// watched.
126    @Test func foldersAddedLaterAreWatched() async throws {
127        let notes = try Folder()
128        let model = try WorkspaceModel(directory: nil)
129        model.startWatching()
130        try await model.addRoot(notes.url)
131        let file = try notes.write("new.org", "* Fresh heading\n")
132        var found = false
133        for _ in 0..<40 where !found {
134            try await Task.sleep(for: .milliseconds(100))
135            found = model.files.contains { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath() == file.resolvingSymlinksInPath() }
136        }
137        #expect(found)
138    }
139
140    @Test func changedFilesAreReindexed() async throws {
141        let notes = try Folder()
142        let file = try notes.write("a.org", "* Old\n")
143        let model = try WorkspaceModel(directory: nil)
144        try await model.addRoot(notes.url)
145        try notes.write("a.org", "* New\n")
146        await model.filesChanged([file], rescan: [])
147        #expect(model.search("new").count == 1)
148        #expect(model.changedFile?.path == file.path)
149    }
150}
151
152@MainActor
153struct DocumentSessionTests {
154    @Test func openShowAndReload() throws {
155        let notes = try Folder()
156        let file = try notes.write("a.org", "* One\n* Two\n")
157        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
158        session.open(file.path)
159        #expect(session.outline.map(\.title) == ["One", "Two"])
160
161        let location = HeadingLocation(path: file.path, ordinal: 1, title: "Two", start: 6, contentHash: "stale")
162        session.show(location)
163        #expect(session.revealRequest?.offset == 6)
164
165        try notes.write("a.org", "intro\n* One\n* Two\n")
166        session.fileChanged(file.path)
167        #expect(session.outline.map(\.start) == [6, 12])
168        session.show(location)
169        #expect(session.revealRequest?.offset == 12)
170    }
171
172    @Test func missingFileReportsAnError() {
173        let session = DocumentSession()
174        session.open("/nonexistent/a.org")
175        #expect(session.lastError != nil)
176        #expect(session.document == nil)
177    }
178}
179
180@MainActor
181struct SessionSavingTests {
182    let notes: Folder
183    let file: URL
184    let recovery: FileRecoveryStore
185    let session: DocumentSession
186
187    init() throws {
188        notes = try Folder()
189        file = try notes.write("a.org", "a\nb\nc\n")
190        recovery = FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery"))
191        session = DocumentSession(recovery: recovery)
192        session.saveMode = .explicit
193        session.open(file.path)
194    }
195
196    /// Types `text` at `offset`, as the editor would.
197    func type(_ text: String, at offset: Int) throws {
198        let buffer = StateBuffer(session.document!)
199        session.attach(buffer)
200        try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
201        session.bufferChanged()
202    }
203
204    var disk: String { (try? String(contentsOf: file, encoding: .utf8)) ?? "" }
205
206    @Test func saveWritesAndClearsDirty() throws {
207        try type("x", at: 0)
208        #expect(session.isDirty)
209        #expect(session.save())
210        #expect(!session.isDirty)
211        #expect(disk == "xa\nb\nc\n")
212    }
213
214    @Test func automaticModeSavesAfterTheDelay() async throws {
215        session.saveMode = .automatic
216        session.autosaveDelay = .milliseconds(10)
217        try type("x", at: 0)
218        #expect(disk == "a\nb\nc\n")
219        await session.autosave?.value
220        #expect(disk == "xa\nb\nc\n")
221        #expect(!session.isDirty)
222    }
223
224    @Test func explicitModeWaitsForSave() throws {
225        try type("x", at: 0)
226        #expect(session.autosave == nil)
227    }
228
229    @Test func externalChangeMergesIntoEdits() throws {
230        try type("x", at: 0)
231        try notes.write("a.org", "a\nb\nC\n")
232        session.fileChanged(file.path)
233        #expect(session.document?.text == "xa\nb\nC\n")
234        #expect(session.conflict == nil)
235        #expect(session.save())
236        #expect(disk == "xa\nb\nC\n")
237    }
238
239    @Test func conflictKeepMine() throws {
240        try type("x", at: 0)
241        try notes.write("a.org", "z\nb\nc\n")
242        session.fileChanged(file.path)
243        #expect(session.conflict != nil)
244        #expect(!session.save())
245        #expect(disk == "z\nb\nc\n")
246        session.keepMine()
247        #expect(session.conflict == nil)
248        #expect(disk == "xa\nb\nc\n")
249        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
250        #expect(kept.contains("z\nb\nc\n"))
251    }
252
253    @Test func conflictUseDiskVersion() throws {
254        try type("x", at: 0)
255        try notes.write("a.org", "z\nb\nc\n")
256        #expect(!session.save())
257        #expect(session.conflict != nil)
258        session.useDiskVersion()
259        #expect(session.conflict == nil)
260        #expect(!session.isDirty)
261        #expect(session.document?.text == "z\nb\nc\n")
262        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
263        #expect(kept.contains("xa\nb\nc\n"))
264    }
265
266    @Test func searchSeesUnsavedHeadings() async throws {
267        let workspace = try WorkspaceModel(directory: nil)
268        try await workspace.addRoot(notes.url)
269        try type("* Unsaved heading\n", at: 0)
270        let overlay = workspace.overlay(path: session.path, document: session.document)
271        #expect(workspace.search("unsaved").isEmpty)
272        #expect(workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"])
273    }
274}
275
276@MainActor
277struct KeymapLoaderTests {
278    @Test func layersTheUserFile() throws {
279        let folder = try Folder()
280        let missing = KeymapLoader.load(.emacs, userFile: folder.url.appendingPathComponent("none.toml"))
281        #expect(missing.keymap == KeymapPreset.emacs.keymap && missing.problems.isEmpty)
282
283        let file = try folder.write("keymap.toml", "[[bind]]\nkeys = \"C-c a\"\ncommand = \"app.palette\"\n[[bind]]\nkeys = \"Q-q\"\ncommand = \"x\"\n")
284        let loaded = KeymapLoader.load(.emacs, userFile: file)
285        #expect(loaded.keymap.candidates(for: KeySequence.parse("C-c a")!).first?.command == "app.palette")
286        #expect(loaded.problems == ["line 4: bad or missing keys"])
287
288        let broken = try folder.write("broken.toml", "keys = \"x")
289        #expect(KeymapLoader.load(.mac, userFile: broken).problems == ["line 1: unclosed string"])
290    }
291}
292
293@MainActor
294struct MoveSubtreeTests {
295    @Test func refileWithinAndAcrossFiles() async throws {
296        let notes = try Folder()
297        let file = try notes.write("a.org", "* one\nbody\n* two\n")
298        let other = try notes.write("b.org", "* inbox\n")
299        let workspace = try WorkspaceModel(directory: nil)
300        try await workspace.addRoot(notes.url)
301        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
302        session.saveMode = .explicit
303        session.open(file.path)
304        let targets = workspace.refileTargets(openPath: session.path, document: session.document)
305        #expect(targets.map(\.label) == ["a.org", "a.org/one", "a.org/two", "b.org", "b.org/inbox"])
306
307        #expect(session.refile(to: targets[2]) == "Refiled to a.org/two")
308        #expect(session.document?.text == "* two\n** one\nbody\n")
309
310        let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" })
311        StateBufferCaret.set(session, 6)
312        #expect(session.refile(to: inbox) == "Refiled to b.org/inbox")
313        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
314        #expect(session.document?.text == "* two\n")
315    }
316
317    @Test func archiveToTheArchiveFile() throws {
318        let notes = try Folder()
319        let file = try notes.write("a.org", "* done\n* keep\n")
320        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
321        session.saveMode = .explicit
322        session.open(file.path)
323        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
324        #expect(session.document?.text == "* keep\n")
325        let archived = try String(contentsOf: notes.url.appendingPathComponent("a.org_archive"), encoding: .utf8)
326        #expect(archived.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
327    }
328}
329
330@MainActor
331struct AgendaActionTests {
332    /// From the agenda: entries in files that aren't open move and archive on disk, and the
333    /// current buffer stays as it was.
334    @Test func refileAndArchiveFromAnEntry() async throws {
335        let notes = try Folder()
336        let file = try notes.write("a.org", "* one\nbody\n* two\n* three\n")
337        let other = try notes.write("b.org", "* inbox\n")
338        let shown = try notes.write("c.org", "* shown\n")
339        let workspace = try WorkspaceModel(directory: nil)
340        try await workspace.addRoot(notes.url)
341        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
342        session.saveMode = .explicit
343        session.open(shown.path)
344
345        let inbox = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/inbox" })
346        #expect(session.refile(to: inbox, from: (file.path, 0)) == "Refiled to b.org/inbox")
347        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
348        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n* three\n")
349
350        let text = try String(contentsOf: file, encoding: .utf8)
351        let two = try #require(workspace.refileTargets(openPath: file.path, document: DocumentState(bytes: [UInt8](text.utf8))).first { $0.label == "a.org/two" })
352        #expect(session.refile(to: two, from: (file.path, 6)) == "Refiled to a.org/two")
353        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n** three\n")
354
355        #expect(session.archive(from: (file.path, 0), now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
356        #expect(try String(contentsOf: file, encoding: .utf8) == "")
357        #expect(session.path == shown.path && session.document?.text == "* shown\n")
358    }
359
360    @Test func locatesMovedHeadings() throws {
361        let notes = try Folder()
362        let file = try notes.write("a.org", "* new\n* task\n* other\n* task\n")
363        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
364        #expect(session.locateHeading(path: file.path, line: "* task", near: 0) == 6)
365        #expect(session.locateHeading(path: file.path, line: "* task", near: 20) == 21)
366        #expect(session.locateHeading(path: file.path, line: "* other", near: 14) == 13)
367        #expect(session.locateHeading(path: file.path, line: "* gone", near: 0) == nil)
368    }
369}
370
371@MainActor
372struct MoveIntoOpenBufferTests {
373    /// A target open with unsaved edits above its heading takes the subtree in its buffer,
374    /// under the right heading, and the disk keeps the saved text.
375    @Test func refileIntoAnOpenBuffer() async throws {
376        let notes = try Folder()
377        let file = try notes.write("a.org", "* task\nbody\n")
378        let other = try notes.write("b.org", "* inbox\n* projects\n")
379        let workspace = try WorkspaceModel(directory: nil)
380        try await workspace.addRoot(notes.url)
381        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
382        session.saveMode = .explicit
383        session.open(other.path)
384        let projects = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/projects" })
385        _ = session.perform(InsertText(text: "* new\n"), path: other.path, at: 0, expect: nil)
386        session.open(file.path)
387        #expect(session.refile(to: projects) == "Refiled to b.org/projects")
388        #expect(session.document?.text == "")
389        #expect(session.openDocuments.first { $0.path == other.path }?.document.text == "* new\n* inbox\n* projects\n** task\nbody\n")
390        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n* projects\n")
391    }
392
393    @Test func archiveIntoAnOpenBuffer() throws {
394        let notes = try Folder()
395        let file = try notes.write("a.org", "* done\n* keep\n")
396        let archive = try notes.write("a.org_archive", "* old\n")
397        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
398        session.saveMode = .explicit
399        session.open(archive.path)
400        session.open(file.path)
401        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
402        #expect(session.document?.text == "* keep\n")
403        let text = try #require(session.openDocuments.first { $0.path == archive.path }?.document.text)
404        #expect(text.hasPrefix("* old\n") && text.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
405        #expect(try String(contentsOf: archive, encoding: .utf8) == "* old\n")
406    }
407}
408
409/// Inserts text at the caret, for tests.
410struct InsertText: OrgCommand {
411    let text: String
412    var id: String { "test.insert" }
413    var title: String { "Insert" }
414    func applies(in context: EditContext) -> Bool { true }
415    func run(in context: EditContext) -> CommandStep {
416        .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: context.caret..<context.caret, replacement: text)]))
417    }
418}
419
420/// Moves the caret of a session's `StateBuffer`, as clicking in the editor would.
421@MainActor
422enum StateBufferCaret {
423    static func set(_ session: DocumentSession, _ offset: Int) {
424        let buffer = StateBuffer(session.document!)
425        buffer.selection = [offset..<offset]
426        session.attach(buffer)
427    }
428}
429
430@MainActor
431struct AgendaModelTests {
432    @Test func topLevelFilesAndTheOpenBuffer() async throws {
433        let notes = try Folder()
434        try notes.write("a.org", "* TODO Pay rent\nSCHEDULED: <2026-10-05 Mon>\n")
435        try notes.write("sub/b.org", "* Hidden <2026-10-05 Mon>\n")
436        try notes.write("old.org_archive", "* Archived <2026-10-05 Mon>\n")
437        let model = try WorkspaceModel(directory: nil)
438        try await model.addRoot(notes.url)
439        let agenda = AgendaModel(workspace: model)
440        var utc = Calendar(identifier: .gregorian)
441        utc.timeZone = TimeZone(identifier: "UTC")!
442        let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
443
444        await agenda.refresh(open: [:], now: now, calendar: utc)
445        #expect(agenda.days.count == 10)
446        #expect(agenda.days[3].isToday)
447        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent"])
448
449        agenda.includeSubfolders = true
450        await agenda.refresh(open: [:], now: now, calendar: utc)
451        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent", "Hidden "])
452
453        let path = try #require(agenda.files.first { $0.hasSuffix("/a.org") })
454        await agenda.refresh(open: [path: "* DONE Pay rent\nSCHEDULED: <2026-10-05 Mon>\n"], now: now, calendar: utc)
455        #expect(agenda.days[3].items.first?.text == "DONE Pay rent")
456
457        agenda.shift(forward: true, now: now, calendar: utc)
458        await agenda.refresh(open: [:], now: now, calendar: utc)
459        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 12))
460    }
461}
462
463@MainActor
464struct AgendaCommandTests {
465    @Test func loadsViews() throws {
466        let folder = try Folder()
467        let file = try folder.write("views.toml", """
468        [[view]]
469        name = "Work"
470        type = "match"
471        match = "+work"
472        [[view]]
473        name = "Week"
474        span = 7
475        start = -1
476        [[view]]
477        name = "Waiting"
478        type = "todo"
479        keywords = "WAIT|HOLD"
480        [[view]]
481        name = "Broken"
482        type = "match"
483        """)
484        let loaded = AgendaViewLoader.load(userFile: file)
485        #expect(loaded.views.map(\.name) == ["Agenda", "TODO List", "Work", "Week", "Waiting"])
486        #expect(loaded.views[2].mode == .match("+work", todoOnly: false))
487        #expect(loaded.views[3].mode == .agenda(span: 7, startOffset: -1))
488        #expect(loaded.views[4].mode == .todo(keywords: "WAIT|HOLD"))
489        #expect(loaded.problems == ["views.toml line 13: Broken needs a match"])
490    }
491
492    @Test func todoListMode() async throws {
493        let notes = try Folder()
494        try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n")
495        let model = try WorkspaceModel(directory: nil)
496        try await model.addRoot(notes.url)
497        let agenda = AgendaModel(workspace: model)
498        agenda.mode = .todo(keywords: nil)
499        await agenda.refresh(open: [:])
500        #expect(agenda.list.map(\.text) == ["TODO One", "TODO Three"])
501        agenda.mode = .match("work", todoOnly: false)
502        await agenda.refresh(open: [:])
503        #expect(agenda.list.map(\.text) == ["TODO One"])
504    }
505
506    @Test func runsCommandsOnClosedAndOpenFiles() throws {
507        let notes = try Folder()
508        let a = try notes.write("a.org", "* TODO One\n* TODO Two\n")
509        let b = try notes.write("b.org", "* TODO Three\n")
510        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
511        session.open(a.path)
512
513        // A closed file is changed on disk.
514        let closed = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
515        guard case .commit = closed else { Issue.record("\(closed)"); return }
516        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
517
518        // The open file changes in its buffer.
519        let open = session.perform(TodoCycle(), path: a.path, at: 11, expect: (11, "* TODO Two"))
520        guard case .commit = open else { Issue.record("\(open)"); return }
521        #expect(session.document?.text == "* TODO One\n* DONE Two\n")
522
523        // A heading that moved is refused.
524        let stale = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
525        guard case .failed = stale else { Issue.record("\(stale)"); return }
526        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
527    }
528}
529
530final class FakeReminderCenter: ReminderCenter, @unchecked Sendable {
531    private let lock = NSLock()
532    private var pending: [String] = ["someone.else"]
533    var authorized = true
534    private(set) var added: [String] = []
535
536    func authorize() async -> Bool { authorized }
537    func pendingIDs() async -> [String] { lock.withLock { pending } }
538    func add(_ reminder: Reminder) async throws {
539        lock.withLock {
540            pending.append(reminder.id)
541            added.append(reminder.id)
542        }
543    }
544    func remove(_ ids: [String]) { lock.withLock { pending.removeAll { ids.contains($0) } } }
545    var ids: [String] { lock.withLock { pending } }
546}
547
548@MainActor
549struct ReminderSchedulerTests {
550    func reminder(_ id: String, _ minutes: Double) -> Reminder {
551        let date = Date(timeIntervalSince1970: 1_000_000 + minutes * 60)
552        return Reminder(id: "orgstar.\(id)", fireDate: date, eventDate: date.addingTimeInterval(720), title: id, body: "", path: "/a.org", offset: 0)
553    }
554
555    @Test func reconciles() async {
556        let center = FakeReminderCenter()
557        let scheduler = ReminderScheduler(center: center)
558        await scheduler.reconcile([reminder("a", 1), reminder("b", 2)])
559        #expect(center.ids == ["someone.else", "orgstar.a", "orgstar.b"])
560        #expect(scheduler.scheduledThrough == reminder("b", 2).eventDate)
561
562        await scheduler.reconcile([reminder("b", 2), reminder("c", 3)])
563        #expect(center.ids == ["someone.else", "orgstar.b", "orgstar.c"])
564        #expect(center.added == ["orgstar.a", "orgstar.b", "orgstar.c"])
565
566        await scheduler.clear()
567        #expect(center.ids == ["someone.else"])
568        #expect(scheduler.scheduledThrough == nil)
569
570        center.authorized = false
571        await scheduler.reconcile([reminder("d", 4)])
572        #expect(!scheduler.isAuthorized)
573        #expect(center.ids == ["someone.else"])
574    }
575}
576
577@MainActor
578struct EmacsFallbackTests {
579    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
580    func recalculatesTablesNativeCodeCannot() async throws {
581        let notes = try Folder()
582        let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=$2*2\n")
583        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
584        session.open(file.path)
585        let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
586        guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp)) = step else {
587            Issue.record("\(step)")
588            return
589        }
590        #expect(reason == "non-numeric field a")
591        #expect(!lisp)
592        let message = await session.recalculateInEmacs(table: table, point: point, form: form)
593        #expect(message == "Recalculated in Emacs")
594        #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-------|\n| x    | a | 2 a   |\n| y    | 2 | 4     |\n#+TBLFM: $3=$2*2\n")
595    }
596}
597
598@MainActor
599struct BabelSessionTests {
600    @Test func runsBlocksAndWritesResults() async throws {
601        let notes = try Folder()
602        let file = try notes.write("b.org", "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n")
603        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
604        session.open(file.path)
605        let step = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil)
606        guard case .external(.babel(let job)) = step else {
607            Issue.record("\(step)")
608            return
609        }
610        #expect(await session.runBabel(job) == "Code block evaluation complete.")
611        // A column that is half numbers is right-aligned, as org-table-align does.
612        #expect(session.document?.text == "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n\n#+RESULTS:\n| answer |\n|     42 |\n")
613    }
614}
615
616@MainActor
617struct BabelErrorTests {
618    func job(_ session: DocumentSession, _ path: String) throws -> BabelJob {
619        guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: path, at: 3, expect: nil) else {
620            throw CancellationError()
621        }
622        return job
623    }
624
625    /// Like `org-babel-eval`: the results go in, and the error output and status are shown.
626    @Test func reportsErrorsAndStillInsertsResults() async throws {
627        let notes = try Folder()
628        let file = try notes.write("e.org", "#+begin_src sh\necho out\necho oops >&2\nexit 3\n#+end_src\n")
629        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
630        session.open(file.path)
631        #expect(await session.runBabel(try job(session, file.path)) == "Exited with status 3: oops")
632        #expect(session.document?.text.hasSuffix("#+RESULTS:\n: out\n") == true)
633    }
634
635    @Test func cancelsARunningBlock() async throws {
636        let notes = try Folder()
637        let file = try notes.write("s.org", "#+begin_src sh\nsleep 20\necho late\n#+end_src\n")
638        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
639        session.open(file.path)
640        let start = ContinuousClock.now
641        var message: String?
642        session.startBabel(try job(session, file.path)) { message = $0 }
643        #expect(session.isRunningBabel)
644        try await Task.sleep(for: .milliseconds(200))
645        session.cancelBabel()
646        while message == nil, ContinuousClock.now - start < .seconds(5) { try await Task.sleep(for: .milliseconds(20)) }
647        #expect(message == "Code block canceled.")
648        #expect(!session.isRunningBabel)
649        #expect(ContinuousClock.now - start < .seconds(5))
650        #expect(session.document?.text.contains("#+RESULTS:") == false)
651    }
652}
653
654struct EmacsExportTests {
655    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
656    func exportsBesideTheFile() async throws {
657        let notes = try Folder()
658        let file = try notes.write("doc.org", "#+TITLE: On disk\n")
659        // The buffer's text is exported, not the file's.
660        let written = try await EmacsRunner.export(text: "#+TITLE: In the buffer\n\n* Heading\nBody.\n", path: file.path, function: "org-ascii-export-to-ascii")
661        #expect(URL(fileURLWithPath: written).lastPathComponent == "doc.txt")
662        let text = try String(contentsOfFile: written, encoding: .utf8)
663        #expect(text.uppercased().contains("IN THE BUFFER") && text.contains("Body."), "\(text)")
664        #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n")
665    }
666}
667
668@MainActor
669struct CaptureAppTests {
670    @Test func loadsTemplates() throws {
671        let folder = try Folder()
672        let file = try folder.write("capture.toml", """
673        [[template]]
674        key = "w"
675        name = "Work"
676        file = "work.org"
677        olp = "Projects/Work"
678        template = "* TODO %?\\n%a"
679        [[template]]
680        key = "j"
681        type = "plain"
682        file = "~/journal.org"
683        template = "%U %?"
684        prepend = true
685        """)
686        let loaded = CaptureTemplates.load(userFile: file)
687        #expect(loaded.problems.isEmpty)
688        #expect(loaded.templates.map(\.key) == ["w", "j"])
689        #expect(loaded.templates[0].target == .outline(file: "work.org", path: ["Projects", "Work"]))
690        #expect(loaded.templates[0].template == "* TODO %?\n%a")
691        #expect(loaded.templates[1].kind == .plain && loaded.templates[1].prepend)
692        try """
693        [[template]]
694        key = "d"
695        file = "journal.org"
696        datetree = true
697        olp = "Journal"
698        tree-type = "month"
699        template = "* %?"
700        empty-lines-after = 1
701        jump-to-captured = true
702        [[template]]
703        key = "i"
704        id = "abc"
705        template = "* %?"
706        clock-in = true
707        clock-resume = true
708        [[template]]
709        key = "k"
710        clock = true
711        type = "item"
712        template = "%?"
713        immediate-finish = true
714        """.write(to: file, atomically: true, encoding: .utf8)
715        let targets = CaptureTemplates.load(userFile: file)
716        #expect(targets.problems.isEmpty)
717        #expect(targets.templates.map(\.target) == [.datetree(file: "journal.org", path: ["Journal"], tree: .month), .id("abc"), .clock])
718        #expect(targets.templates[0].options == .init(emptyLinesAfter: 1, jumpToCaptured: true))
719        #expect(targets.templates[1].options == .init(clockIn: true, clockResume: true))
720        #expect(targets.templates[2].options.immediateFinish)
721        #expect(CaptureTemplates.load(userFile: folder.url.appendingPathComponent("none.toml")).templates == CaptureTemplates.defaults)
722    }
723
724    @Test func capturesIntoClosedMissingAndOpenFiles() throws {
725        let notes = try Folder()
726        let todo = try notes.write("todo.org", "* Inbox\n** TODO Old\n* Later\n")
727        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
728        let template = CaptureTemplates.defaults[0]
729        let placed = try session.capture("* TODO New\n", template: template, root: notes.url.path).get()
730        #expect(try String(contentsOf: todo, encoding: .utf8) == "* Inbox\n** TODO Old\n** TODO New\n* Later\n")
731        #expect(placed.path == todo.path && placed.offset == ("* Inbox\n** TODO Old\n" as NSString).length)
732
733        _ = try session.capture("* Note\n", template: CaptureTemplates.defaults[1], root: notes.url.path).get()
734        #expect(try String(contentsOf: notes.url.appendingPathComponent("notes.org"), encoding: .utf8) == "* Inbox\n** Note\n")
735
736        session.open(todo.path)
737        _ = try session.capture("* TODO Third\n", template: template, root: notes.url.path).get()
738        #expect(session.document?.text == "* Inbox\n** TODO Old\n** TODO New\n** TODO Third\n* Later\n")
739
740        // An ID's file is resolved by the caller.
741        let id = CaptureTemplate(key: "i", name: "", target: .id("x1"), template: "")
742        let ided = try notes.write("ided.org", "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n")
743        _ = try session.capture("* Child\n", template: id, root: nil, file: ided.path).get()
744        #expect(try String(contentsOf: ided, encoding: .utf8) == "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n** Child\n")
745    }
746}
747
748@MainActor
749struct ClockModelTests {
750    @Test func clocksInAndOutAcrossFiles() throws {
751        let notes = try Folder()
752        let work = try notes.write("work.org", "* Task\nBody\n")
753        let other = try notes.write("other.org", "* Other\n")
754        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
755        session.open(work.path)
756        session.reveal(2)
757        let stateFile = notes.url.appendingPathComponent("clock.json")
758        let clock = ClockModel(file: stateFile)
759        var utc = Calendar(identifier: .gregorian)
760        utc.timeZone = TimeZone(identifier: "UTC")!
761        let start = Date(timeIntervalSince1970: 1_789_000_000)
762        _ = clock.clockIn(session, now: start)
763        #expect(clock.running?.heading == "Task")
764        #expect(ClockModel(file: stateFile).running == clock.running)
765
766        // Out from another file: the clocked file's buffer is still open behind it and takes
767        // the change.
768        session.open(other.path)
769        let message = clock.clockOut(session, now: start.addingTimeInterval(95 * 60))
770        #expect(message == "Clock stopped after 1:35")
771        #expect(clock.running == nil)
772        #expect(session.dirtyPaths == [work.path])
773        #expect(session.saveAll())
774        let text = try String(contentsOf: work, encoding: .utf8)
775        #expect(text.hasPrefix("* Task\n:LOGBOOK:\nCLOCK: [") && text.contains("=>  1:35\n:END:\nBody\n"), "\(text)")
776    }
777}
778
779@MainActor
780struct BufferTests {
781    @Test func buffersKeepEditsWhileOthersShow() throws {
782        let notes = try Folder()
783        let a = try notes.write("a.org", "* A\n")
784        let b = try notes.write("b.org", "* B\n")
785        let c = try notes.write("c.org", "* C\n")
786        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
787        session.saveMode = .explicit
788        session.open(a.path)
789        _ = session.perform(SetTodo(keyword: "TODO"), path: a.path, at: 0, expect: nil)
790        session.open(b.path)
791        #expect(session.path == b.path)
792        #expect(session.openPaths == [a.path, b.path])
793        #expect(session.dirtyPaths == [a.path])
794        // A background buffer takes commands for its file, not the disk.
795        _ = session.perform(SetTodo(keyword: "DONE"), path: a.path, at: 0, expect: nil)
796        #expect(try String(contentsOf: a, encoding: .utf8) == "* A\n")
797        #expect(session.openDocuments.first { $0.path == a.path }?.document.text.hasPrefix("* DONE A") == true)
798
799        session.open(a.path)
800        #expect(session.document?.text.hasPrefix("* DONE A") == true)
801        session.open(c.path)
802        // Opened after the current buffer.
803        #expect(session.openPaths == [a.path, c.path, b.path])
804        session.cycle(1)
805        #expect(session.path == b.path)
806        session.cycle(1)
807        #expect(session.path == a.path)
808        session.showPrevious()
809        #expect(session.path == b.path)
810        #expect(session.recentPaths == [b.path, a.path, c.path])
811
812        session.kill(b.path)
813        #expect(session.path == a.path)
814        #expect(session.openPaths == [a.path, c.path])
815        #expect(session.saveAll())
816        #expect(try String(contentsOf: a, encoding: .utf8).hasPrefix("* DONE A"))
817        session.kill(a.path)
818        session.kill(c.path)
819        #expect(session.path == nil && session.document == nil && session.openPaths.isEmpty)
820    }
821
822    @Test func backgroundBuffersFollowTheDisk() throws {
823        let notes = try Folder()
824        let a = try notes.write("a.org", "* A\n")
825        let b = try notes.write("b.org", "* B\n")
826        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
827        session.open(a.path)
828        session.open(b.path)
829        try notes.write("a.org", "* A changed\n")
830        session.fileChanged(a.path)
831        #expect(session.openDocuments.first { $0.path == a.path }?.document.text == "* A changed\n")
832    }
833}
834
835@MainActor
836struct LinkFollowTests {
837    @Test func followsLinksOfEachKind() async throws {
838        let notes = try Folder()
839        let a = try notes.write("a.org", "* Start\nSee <<here>>.\n* Second [1/2]\n:PROPERTIES:\n:CUSTOM_ID: two\n:END:\n")
840        let b = try notes.write("sub/b.org", "* Target heading\n:PROPERTIES:\n:ID: 1234-ABCD\n:END:\nline 5\nline 6\n")
841        _ = try notes.write("pic.png", "not really")
842        let workspace = try WorkspaceModel(directory: nil)
843        try await workspace.addRoot(notes.url)
844        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
845        session.open(a.path)
846        let text = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
847        func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
848
849        #expect(follow("here") == .shown)
850        #expect(session.revealRequest?.offset == (text(a.path)! as NSString).range(of: "<<here>>").location)
851        #expect(follow("#two") == .shown)
852        #expect(follow("Second") == .shown)
853        #expect(follow("Nowhere") == .message("No match for fuzzy expression: Nowhere"))
854
855        #expect(follow("file:sub/b.org::5") == .shown)
856        #expect(session.path == b.path)
857        #expect(session.revealRequest?.offset == (text(b.path)! as NSString).range(of: "line 5").location)
858        session.open(a.path)
859        #expect(follow("file:sub/b.org::*Target heading") == .shown && session.path == b.path)
860        session.open(a.path)
861        #expect(follow("id:1234-ABCD") == .shown && session.path == b.path)
862        #expect(follow("id:none") == .message("No heading has the ID none"))
863        // Relative to the open file (now sub/b.org); files Orgstar doesn't edit go to macOS.
864        #expect(follow("file:../pic.png") == .openExternally(URL(fileURLWithPath: (notes.url.appendingPathComponent("pic.png").path as NSString).standardizingPath)))
865        #expect(follow("file:pic.png") == .message("No file " + (notes.url.appendingPathComponent("sub/pic.png").path as NSString).standardizingPath))
866        #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!))
867        #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!))
868        #expect(follow("shell:rm -rf x") == .message("Orgstar doesn't run shell links"))
869    }
870}
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