Tests/OrgAppTests/DailiesTests.swift
89 lines · 5382 bytes
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 @MainActor
60 @Test func captureFilesTheEntryAtTheEnd() throws {
61 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-daily-\(UUID().uuidString)").resolvingSymlinksInPath()
62 defer { try? FileManager.default.removeItem(at: folder) }
63 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
64 var opened: (String, Int)?
65 let actions = RoamActions(session: session, roots: { [folder.path] }, nodes: { [] }, show: { Issue.record("\($0)") }, ask: { $1(nil) },
66 open: { opened = ($0, $1) }, insertLink: { _, _ in }, refresh: {})
67 actions.capture(Self.day)
68 let path = folder.appendingPathComponent("daily/2026-10-11.org").path
69 let text = try String(contentsOfFile: path, encoding: .utf8)
70 #expect(text.hasPrefix(":PROPERTIES:\n:ID: "))
71 #expect(text.hasSuffix(":END:\n#+title: 2026-10-11\n* \n"))
72 #expect(opened?.0 == path && opened?.1 == (text as NSString).length - 1)
73 }
74}
75
76struct NodeIndexTests {
77 @Test func filesAndHeadingsWithIDsAreNodes() throws {
78 let store = try IndexStore()
79 let settings = IndexSettings()
80 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"
81 try store.write(FileRecord(path: "/n/2026-10-11.org", root: "/n", kind: .org, bytes: Array(text.utf8), mtime: 1, settings: settings))
82 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))
83 let nodes = try store.nodes()
84 #expect(nodes.map(\.id) == ["file-1", "f2", "h-1"])
85 #expect(nodes.map(\.title) == ["Daily", "untitled", "Task"])
86 #expect(try store.headings(withID: "file-1").map(\.ordinal) == [HeadingLocation.fileOrdinal])
87 #expect(try store.headings(withID: "h-1").map(\.title) == ["Task"])
88 }
89}