Tests/OrgCoreTests/AgendaTests.swift
378 lines · 16807 bytes
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// Runs `org-agenda-list` over files in `emacs -Q --batch` with the clock frozen.
6enum AgendaOracle {
7 struct Line: Codable {
8 var line: String
9 var type: String?
10 var category: String?
11 var tod: Int?
12 var extra: String?
13 var urgency: Int?
14 var file: String?
15 var pos: Int?
16 }
17
18 struct Day: Codable {
19 var header: String
20 var items: [Line]
21 }
22
23 static let keywords = "TODO PROJ LOOP STRT WAIT HOLD IDEA | DONE KILL"
24
25 static func script(files: [String], form: String, seconds: Int) -> String {
26 let fileList = files.map { "\"\($0)\"" }.joined(separator: " ")
27 let words = keywords.split(separator: " ").map { "\"\($0)\"" }.joined(separator: " ")
28 return #"""
29 ;;; -*- lexical-binding: t -*-
30 (require 'org)
31 (require 'org-agenda)
32 (require 'json)
33 (setq org-todo-keywords '((sequence \#(words)))
34 org-agenda-files '(\#(fileList)))
35 (add-to-list 'auto-mode-alist '("\\.org_archive\\'" . org-mode))
36 (defun orgstar-dump ()
37 (let (days header items)
38 (goto-char (point-min))
39 (while (not (eobp))
40 (let* ((p (line-beginning-position))
41 (line (buffer-substring-no-properties p (line-end-position)))
42 (hd (get-text-property p 'org-hd-marker)))
43 (cond
44 ((get-text-property p 'org-agenda-date-header)
45 (when header (push `((header . ,header) (items . ,(vconcat (nreverse items)))) days))
46 (setq header line items nil))
47 ((or header hd)
48 (push `((line . ,line)
49 (type . ,(get-text-property p 'type))
50 (category . ,(get-text-property p 'org-category))
51 (tod . ,(get-text-property p 'time-of-day))
52 (extra . ,(get-text-property p 'extra))
53 (urgency . ,(get-text-property p 'urgency))
54 (file . ,(and hd (buffer-file-name (marker-buffer hd))))
55 (pos . ,(and hd (marker-position hd))))
56 items))))
57 (forward-line 1))
58 (when (or header items) (push `((header . ,(or header "")) (items . ,(vconcat (nreverse items)))) days))
59 (vconcat (nreverse days))))
60 \#(frozenClock(seconds, """
61 (progn
62 \(form)
63 (let ((result (with-current-buffer org-agenda-buffer-name (orgstar-dump))))
64 (let ((coding-system-for-write 'utf-8-unix))
65 (with-temp-file (getenv "ORACLE_OUTPUT")
66 (insert (json-encode result))))))
67 """))
68 """#
69 }
70
71 static func run(files: [(name: String, text: String)], form: String, today: Int, hour: Int, minute: Int) throws -> [Day] {
72 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-agenda-\(UUID().uuidString)")
73 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
74 defer { try? FileManager.default.removeItem(at: folder) }
75 var paths: [String] = []
76 for file in files {
77 let url = folder.appendingPathComponent(file.name)
78 try file.text.write(to: url, atomically: true, encoding: .utf8)
79 paths.append(url.resolvingSymlinksInPath().path)
80 }
81 let seconds = (today - 719163) * 86400 + hour * 3600 + minute * 60
82 let scriptURL = folder.appendingPathComponent("agenda.el")
83 let output = folder.appendingPathComponent("output.json")
84 try script(files: paths, form: form, seconds: seconds)
85 .write(to: scriptURL, atomically: true, encoding: .utf8)
86 let log = try EmacsOracle.run(["-Q", "--batch", "-l", scriptURL.path], environment: ["ORACLE_OUTPUT": output.path, "TZ": "UTC"])
87 guard let data = try? Data(contentsOf: output) else { throw OracleError(log: log) }
88 let days = try JSONDecoder().decode([Day].self, from: data)
89 // Positions as UTF-16 offsets, files by name.
90 return days.map { day in
91 Day(header: day.header, items: day.items.map { line in
92 var line = line
93 if let file = line.file, let pos = line.pos, let index = paths.firstIndex(of: URL(fileURLWithPath: file).resolvingSymlinksInPath().path) {
94 line.file = files[index].name
95 line.pos = EmacsOracle.offset(pos, in: files[index].text)
96 }
97 return line
98 })
99 }
100 }
101
102 struct OracleError: Error { let log: String }
103
104 /// Tags realigned to one space, as their column depends on the window.
105 static func normalize(_ line: String) -> String {
106 line.replacingOccurrences(of: "[ \\t]+(:[^ \\t]+:)[ \\t]*$", with: " $1", options: .regularExpression)
107 }
108
109 static func compare(files: [(name: String, text: String)], start: Int, span: Int, today: Int, hour: Int = 9, minute: Int = 30) throws {
110 let date = Days.date(start)
111 let emacs = try run(files: files, form: "(org-agenda-list nil \"\(String(format: "%04d-%02d-%02d", date.year, date.month, date.day))\" \(span))", today: today, hour: hour, minute: minute)
112 let defaults = OrgSettings.default.withTodoKeywords(keywords)!
113 let sources = files.map { AgendaSource(path: $0.name, text: $0.text, defaults: defaults) }
114 let ours = Agenda.list(sources, start: start, days: span, today: today, now: (hour, minute), options: .terminal)
115 #expect(ours.count == emacs.count)
116 for (o, e) in zip(ours, emacs) {
117 #expect(o.header == e.header)
118 #expect(describe(o.items) == describe(e.items), "\(e.header) today \(Days.date(today))")
119 }
120 }
121
122 static func describe(_ items: [Line]) -> [String] {
123 items.map { item in
124 "\(normalize(item.line)) | \(item.type ?? "-") \(item.category ?? "") \(item.tod.map(String.init) ?? "-") [\(item.extra ?? "")] \(item.urgency ?? 0) \(item.file ?? "-")@\(item.pos.map(String.init) ?? "-")"
125 }
126 }
127
128 static func describe(_ items: [AgendaItem]) -> [String] {
129 items.map { item in
130 let type: String = switch item.kind {
131 case .timeGrid, .currentTime: "-"
132 default: item.kind.rawValue
133 }
134 return "\(normalize(item.line)) | \(type) \(item.category) \(item.timeOfDay.map(String.init) ?? "-") [\(item.extra)] \(item.urgency) \(item.path ?? "-")@\(item.headingOffset.map(String.init) ?? "-")"
135 }
136 }
137
138 /// A TODO list or tags view: `form` runs it in Emacs, `ours` builds ours from the sources.
139 static func compareList(files: [(name: String, text: String)], form: String, today: Int, _ ours: ([AgendaSource]) -> [AgendaItem]) throws {
140 let emacs = try run(files: files, form: form, today: today, hour: 9, minute: 30)
141 let defaults = OrgSettings.default.withTodoKeywords(keywords)!
142 let mine = ours(files.map { AgendaSource(path: $0.name, text: $0.text, defaults: defaults) })
143 #expect(describe(mine) == describe(emacs.first?.items ?? []), "\(form)")
144 }
145}
146
147struct AgendaTests {
148 @Test func days() {
149 #expect(Days.absolute(year: 1970, month: 1, day: 1) == 719163)
150 #expect(Days.absolute(year: 2026, month: 10, day: 5) - Days.absolute(year: 2026, month: 9, day: 30) == 5)
151 #expect(Days.weekday(Days.absolute(year: 2026, month: 10, day: 5)) == 1)
152 #expect(Days.isoWeek(Days.absolute(year: 2026, month: 10, day: 5)) == 41)
153 #expect(Days.isoWeek(Days.absolute(year: 2027, month: 1, day: 1)) == 53)
154 let d = Days.date(Days.absolute(year: 2024, month: 2, day: 29))
155 #expect(d.year == 2024 && d.month == 2 && d.day == 29)
156 #expect(Days.date(Days.absolute(year: 2026, month: 2, day: 31)) == (2026, 3, 3))
157 #expect(Days.date(Days.absolute(year: 2026, month: 13, day: 1)) == (2027, 1, 1))
158 }
159
160 static let synthetic = """
161 #+TODO: TODO NEXT | DONE
162 #+FILETAGS: :ft:
163 Before the first heading <2026-10-05 Mon>.
164 * TODO [#A] Pay rent :home:
165 SCHEDULED: <2026-10-01 Thu>
166 * Meeting 10:00 with Bob
167 <2026-10-05 Mon 14:00-15:00>
168 * DONE Old
169 DEADLINE: <2026-10-03 Sat>
170 * NEXT Report :work:
171 DEADLINE: <2026-10-12 Mon -3d>
172 * NEXT Soon
173 DEADLINE: <2026-10-09 Fri>
174 * TODO Overdue
175 DEADLINE: <2026-09-20 Sun 08:15>
176 * Trip
177 <2026-10-04 Sun>--<2026-10-07 Wed>
178 * Same day range
179 <2026-10-06 Tue 10:00>--<2026-10-06 Tue 12:30>
180 * Gym
181 <2026-09-01 Tue 07:00 +1w>
182 ** Child
183 :PROPERTIES:
184 :CATEGORY: kid
185 :END:
186 SCHEDULED: <2026-10-06 Tue>
187 *** Grandchild :x:
188 <2026-10-07 Wed 9am>
189 * TODO Water plants
190 SCHEDULED: <2026-09-28 Mon .+2d>
191 * TODO Monthly
192 SCHEDULED: <2026-08-31 Mon +1m>
193 * TODO Yearly
194 DEADLINE: <2025-10-08 Wed +1y>
195 * TODO Delayed
196 SCHEDULED: <2026-10-02 Fri -2d>
197 * Archived :ARCHIVE:
198 SCHEDULED: <2026-10-05 Mon>
199 <2026-10-05 Mon>
200 ** TODO Under archived
201 DEADLINE: <2026-10-05 Mon>
202 * COMMENT Commented
203 DEADLINE: <2026-10-05 Mon>
204 <2026-10-05 Mon>
205 * Blocks
206 #+begin_src sh
207 echo <2026-10-05 Mon>
208 #+end_src
209 # <2026-10-05 Mon>
210 =<2026-10-06 Tue>= and [[https://example.com][<2026-10-06 Tue>]]
211 * [#C] Low priority <2026-10-06 Tue>
212 * TODO Late meeting 23:30
213 SCHEDULED: <2026-10-05 Mon>
214 * Props
215 :PROPERTIES:
216 :WHEN: <2026-10-06 Tue 16:00>
217 :END:
218 * TODO Spaces :a:b:
219 <2026-10-06 Tue 11:00>
220 * Ünïcode tïtle :tag:
221 <2026-10-05 Mon 08:00>
222 * Range with times <2026-10-05 Mon 10:00-11:00>
223 * Hourly
224 <2026-10-04 Sun 22:00 +12h>
225 """
226
227 static let second = """
228 #+CATEGORY: other
229 * WAIT Second file
230 DEADLINE: <2026-10-05 Mon>
231 * Two stamps
232 <2026-10-05 Mon 13:00> and <2026-10-06 Tue>
233 """
234
235 static let third = """
236 #+FILETAGS: :proj:
237 * TODO Alpha :work:urgent:
238 :PROPERTIES:
239 :EFFORT: 2:00
240 :SIZE: 3
241 :OWNER: alice
242 :DUE: <2026-10-10 Sat>
243 :END:
244 ** NEXT Beta :boss:
245 :PROPERTIES:
246 :SIZE: 10
247 :END:
248 *** Gamma :work:
249 * DONE Delta :home:
250 CLOSED: [2026-10-01 Thu 10:00] SCHEDULED: <2026-09-30 Wed>
251 * WAIT [#A] Epsilon 10:30
252 :PROPERTIES:
253 :OWNER: Bob
254 :END:
255 <2026-10-03 Sat> [2026-10-02 Fri]
256 * HOLD Zeta :x@y:
257 * Eta with category
258 :PROPERTIES:
259 :CATEGORY: cat
260 :END:
261 ** KILL Theta
262 * IDEA [#C] Iota
263 * Archived :ARCHIVE:work:
264 ** TODO Kappa :work:
265 """
266
267 static let matches = [
268 "work", "+work-urgent", "work|home", "proj", "{^w}", "-work", "LEVEL>1", "LEVEL=2+boss", "SIZE>5", "SIZE<5",
269 "OWNER=\"alice\"", "OWNER={^b}", "OWNER<>\"alice\"", "OWNER<\"b\"", "TODO=\"WAIT\"", "PRIORITY=\"A\"",
270 "CATEGORY=\"cat\"", "DUE<\"<2026-10-15>\"", "DUE>\"<today>\"", "SCHEDULED<\"<today>\"", "TIMESTAMP=\"<2026-10-03 Sat>\"",
271 "ITEM={lph}", "work/TODO", "/!", "+work/!TODO|WAIT", "EFFORT>\"1:00\"", "ALLTAGS={proj}", "TAGS=\":work:urgent:\"",
272 "x@y", "/-TODO", "/!{^[HW]}", "work&urgent", "SIZE>=3+SIZE<=3", "LEVEL<>1",
273 ]
274
275 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
276 func listsMatchEmacs() throws {
277 let files = [("a.org", Self.synthetic), ("b.org", Self.second), ("c.org", Self.third)]
278 let today = Days.absolute(year: 2026, month: 10, day: 5)
279 var utc = Calendar(identifier: .gregorian)
280 utc.timeZone = TimeZone(identifier: "UTC")!
281 let now = Date(timeIntervalSince1970: Double((today - 719163) * 86400 + 9 * 3600 + 30 * 60))
282 func lisp(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
283 try AgendaOracle.compareList(files: files, form: "(org-todo-list nil)", today: today) { Agenda.todoList($0) }
284 for keywords in ["WAIT|HOLD", "DONE", "KILL|TODO"] {
285 try AgendaOracle.compareList(files: files, form: "(org-todo-list \(lisp(keywords)))", today: today) { Agenda.todoList($0, keywords: keywords) }
286 }
287 for match in Self.matches {
288 for todoOnly in [false, true] {
289 try AgendaOracle.compareList(files: files, form: "(org-tags-view \(todoOnly ? "t" : "nil") \(lisp(match)))", today: today) {
290 Agenda.tagsMatch($0, match: match, todoOnly: todoOnly, now: now, calendar: utc)
291 }
292 }
293 }
294 }
295
296 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
297 func matchesEmacs() throws {
298 let files = [("a.org", Self.synthetic), ("b.org", Self.second)]
299 for today in [(2026, 10, 5), (2026, 10, 1), (2026, 10, 8), (2026, 9, 29)] {
300 let day = Days.absolute(year: today.0, month: today.1, day: today.2)
301 try AgendaOracle.compare(files: files, start: day - 3, span: 10, today: day)
302 }
303 let day = Days.absolute(year: 2026, month: 10, day: 6)
304 try AgendaOracle.compare(files: files, start: day, span: 1, today: day)
305 try AgendaOracle.compare(files: files, start: day + 1, span: 1, today: day)
306 }
307
308 /// `ORGSTAR_ORACLE_CORPUS=<folder>`: the top-level files of the folder, ten days around
309 /// two dates.
310 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
311 func matchesEmacsOnACorpus() throws {
312 let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"]!)
313 let files = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
314 .filter { $0.pathExtension == "org" }.sorted { $0.path < $1.path }
315 .compactMap { url in (try? String(contentsOf: url, encoding: .utf8)).map { (url.lastPathComponent, $0) } }
316 for today in [Days.absolute(Date(), calendar: .current), Days.absolute(year: 2025, month: 3, day: 14)] {
317 try AgendaOracle.compare(files: files, start: today - 3, span: 10, today: today)
318 }
319 let today = Days.absolute(Date(), calendar: .current)
320 try AgendaOracle.compareList(files: files, form: "(org-todo-list nil)", today: today) { Agenda.todoList($0) }
321 for match in ["finance|home", "LEVEL=2", "/!", "PRIORITY=\"A\""] {
322 let lisp = "\"" + match.replacingOccurrences(of: "\"", with: "\\\"") + "\""
323 try AgendaOracle.compareList(files: files, form: "(org-tags-view nil \(lisp))", today: today) { Agenda.tagsMatch($0, match: match) }
324 }
325 }
326}
327
328struct ReminderTests {
329 static var utc: Calendar {
330 var calendar = Calendar(identifier: .gregorian)
331 calendar.timeZone = TimeZone(identifier: "UTC")!
332 return calendar
333 }
334
335 static func date(_ day: Int, _ hour: Int, _ minute: Int) -> Date {
336 utc.date(from: DateComponents(year: 2026, month: 10, day: day, hour: hour, minute: minute))!
337 }
338
339 @Test func timedEntriesWithTheirWarnings() {
340 let text = """
341 * TODO Call
342 SCHEDULED: <2026-10-05 Mon 14:00>
343 * Meeting
344 :PROPERTIES:
345 :APPT_WARNTIME: 30
346 :END:
347 <2026-10-06 Tue 10:00-11:00>
348 * DONE Finished
349 SCHEDULED: <2026-10-05 Mon 15:00>
350 * Untimed
351 SCHEDULED: <2026-10-05 Mon>
352 * Earlier
353 <2026-10-05 Mon 08:00>
354 * Soon
355 <2026-10-05 Mon 09:35>
356 * TODO Report due
357 DEADLINE: <2026-10-07 Wed 17:00>
358 """
359 let source = AgendaSource(path: "/n/a.org", text: text)
360 let now = Self.date(5, 9, 30)
361 let reminders = Reminders.upcoming([source], now: now, calendar: Self.utc)
362 #expect(reminders.map(\.title) == ["Soon", "TODO Call", "Meeting", "TODO Report due"])
363 #expect(reminders[0].fireDate == now.addingTimeInterval(1))
364 #expect(reminders[1].fireDate == Self.date(5, 13, 48))
365 #expect(reminders[1].body == "14:00 · Scheduled: · a")
366 #expect(reminders[2].fireDate == Self.date(6, 9, 30))
367 #expect(reminders[3].eventDate == Self.date(7, 17, 0))
368 #expect(Reminders.upcoming([source], now: now, calendar: Self.utc, limit: 2).count == 2)
369 #expect(Reminders.upcoming([source], now: now, calendar: Self.utc, days: 1).map(\.title) == ["Soon", "TODO Call"])
370 }
371
372 @Test func repeatsFillTheWeek() {
373 let source = AgendaSource(path: "/n/a.org", text: "* Standup\n<2026-10-01 Thu 09:00 +1d>\n")
374 let reminders = Reminders.upcoming([source], now: Self.date(5, 9, 30), calendar: Self.utc)
375 #expect(reminders.count == 6)
376 #expect(Set(reminders.map(\.id)).count == 6)
377 }
378}