Tests/OrgCoreTests/AgendaTests.swift
241 lines · 10817 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], start: String, span: Int, 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 (header
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 header (push `((header . ,header) (items . ,(vconcat (nreverse items)))) days))
59 (vconcat (nreverse days))))
60 \#(frozenClock(seconds, """
61 (progn
62 (org-agenda-list nil "\(start)" \(span))
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)], start: Int, span: Int, 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 date = Days.date(start)
82 let seconds = (today - 719163) * 86400 + hour * 3600 + minute * 60
83 let scriptURL = folder.appendingPathComponent("agenda.el")
84 let output = folder.appendingPathComponent("output.json")
85 try script(files: paths, start: String(format: "%04d-%02d-%02d", date.year, date.month, date.day), span: span, seconds: seconds)
86 .write(to: scriptURL, atomically: true, encoding: .utf8)
87 let log = try EmacsOracle.run(["-Q", "--batch", "-l", scriptURL.path], environment: ["ORACLE_OUTPUT": output.path, "TZ": "UTC"])
88 guard let data = try? Data(contentsOf: output) else { throw OracleError(log: log) }
89 let days = try JSONDecoder().decode([Day].self, from: data)
90 // Positions as UTF-16 offsets, files by name.
91 return days.map { day in
92 Day(header: day.header, items: day.items.map { line in
93 var line = line
94 if let file = line.file, let pos = line.pos, let index = paths.firstIndex(of: URL(fileURLWithPath: file).resolvingSymlinksInPath().path) {
95 line.file = files[index].name
96 line.pos = EmacsOracle.offset(pos, in: files[index].text)
97 }
98 return line
99 })
100 }
101 }
102
103 struct OracleError: Error { let log: String }
104
105 /// Tags realigned to one space, as their column depends on the window.
106 static func normalize(_ line: String) -> String {
107 line.replacingOccurrences(of: "[ \\t]+(:[^ \\t]+:)[ \\t]*$", with: " $1", options: .regularExpression)
108 }
109
110 static func compare(files: [(name: String, text: String)], start: Int, span: Int, today: Int, hour: Int = 9, minute: Int = 30) throws {
111 let emacs = try run(files: files, start: start, span: 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 let theirs = e.items.map { item in
119 "\(normalize(item.line)) | \(item.type ?? "-") \(item.category ?? "") \(item.tod.map(String.init) ?? "-") [\(item.extra ?? "")] \(item.urgency ?? 0) \(item.file ?? "-")@\(item.pos.map(String.init) ?? "-")"
120 }
121 let mine = o.items.map { item in
122 let type: String = switch item.kind {
123 case .timeGrid, .currentTime: "-"
124 default: item.kind.rawValue
125 }
126 return "\(normalize(item.line)) | \(type) \(item.category) \(item.timeOfDay.map(String.init) ?? "-") [\(item.extra)] \(item.urgency) \(item.path ?? "-")@\(item.headingOffset.map(String.init) ?? "-")"
127 }
128 #expect(mine == theirs, "\(e.header) today \(Days.date(today))")
129 }
130 }
131}
132
133struct AgendaTests {
134 @Test func days() {
135 #expect(Days.absolute(year: 1970, month: 1, day: 1) == 719163)
136 #expect(Days.absolute(year: 2026, month: 10, day: 5) - Days.absolute(year: 2026, month: 9, day: 30) == 5)
137 #expect(Days.weekday(Days.absolute(year: 2026, month: 10, day: 5)) == 1)
138 #expect(Days.isoWeek(Days.absolute(year: 2026, month: 10, day: 5)) == 41)
139 #expect(Days.isoWeek(Days.absolute(year: 2027, month: 1, day: 1)) == 53)
140 let d = Days.date(Days.absolute(year: 2024, month: 2, day: 29))
141 #expect(d.year == 2024 && d.month == 2 && d.day == 29)
142 #expect(Days.date(Days.absolute(year: 2026, month: 2, day: 31)) == (2026, 3, 3))
143 #expect(Days.date(Days.absolute(year: 2026, month: 13, day: 1)) == (2027, 1, 1))
144 }
145
146 static let synthetic = """
147 #+TODO: TODO NEXT | DONE
148 #+FILETAGS: :ft:
149 Before the first heading <2026-10-05 Mon>.
150 * TODO [#A] Pay rent :home:
151 SCHEDULED: <2026-10-01 Thu>
152 * Meeting 10:00 with Bob
153 <2026-10-05 Mon 14:00-15:00>
154 * DONE Old
155 DEADLINE: <2026-10-03 Sat>
156 * NEXT Report :work:
157 DEADLINE: <2026-10-12 Mon -3d>
158 * NEXT Soon
159 DEADLINE: <2026-10-09 Fri>
160 * TODO Overdue
161 DEADLINE: <2026-09-20 Sun 08:15>
162 * Trip
163 <2026-10-04 Sun>--<2026-10-07 Wed>
164 * Same day range
165 <2026-10-06 Tue 10:00>--<2026-10-06 Tue 12:30>
166 * Gym
167 <2026-09-01 Tue 07:00 +1w>
168 ** Child
169 :PROPERTIES:
170 :CATEGORY: kid
171 :END:
172 SCHEDULED: <2026-10-06 Tue>
173 *** Grandchild :x:
174 <2026-10-07 Wed 9am>
175 * TODO Water plants
176 SCHEDULED: <2026-09-28 Mon .+2d>
177 * TODO Monthly
178 SCHEDULED: <2026-08-31 Mon +1m>
179 * TODO Yearly
180 DEADLINE: <2025-10-08 Wed +1y>
181 * TODO Delayed
182 SCHEDULED: <2026-10-02 Fri -2d>
183 * Archived :ARCHIVE:
184 <2026-10-05 Mon>
185 * COMMENT Commented
186 <2026-10-05 Mon>
187 * Blocks
188 #+begin_src sh
189 echo <2026-10-05 Mon>
190 #+end_src
191 # <2026-10-05 Mon>
192 =<2026-10-06 Tue>= and [[https://example.com][<2026-10-06 Tue>]]
193 * [#C] Low priority <2026-10-06 Tue>
194 * TODO Late meeting 23:30
195 SCHEDULED: <2026-10-05 Mon>
196 * Props
197 :PROPERTIES:
198 :WHEN: <2026-10-06 Tue 16:00>
199 :END:
200 * TODO Spaces :a:b:
201 <2026-10-06 Tue 11:00>
202 * Ünïcode tïtle :tag:
203 <2026-10-05 Mon 08:00>
204 * Range with times <2026-10-05 Mon 10:00-11:00>
205 * Hourly
206 <2026-10-04 Sun 22:00 +12h>
207 """
208
209 static let second = """
210 #+CATEGORY: other
211 * WAIT Second file
212 DEADLINE: <2026-10-05 Mon>
213 * Two stamps
214 <2026-10-05 Mon 13:00> and <2026-10-06 Tue>
215 """
216
217 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
218 func matchesEmacs() throws {
219 let files = [("a.org", Self.synthetic), ("b.org", Self.second)]
220 for today in [(2026, 10, 5), (2026, 10, 1), (2026, 10, 8), (2026, 9, 29)] {
221 let day = Days.absolute(year: today.0, month: today.1, day: today.2)
222 try AgendaOracle.compare(files: files, start: day - 3, span: 10, today: day)
223 }
224 let day = Days.absolute(year: 2026, month: 10, day: 6)
225 try AgendaOracle.compare(files: files, start: day, span: 1, today: day)
226 try AgendaOracle.compare(files: files, start: day + 1, span: 1, today: day)
227 }
228
229 /// `ORGSTAR_ORACLE_CORPUS=<folder>`: the top-level files of the folder, ten days around
230 /// two dates.
231 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
232 func matchesEmacsOnACorpus() throws {
233 let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"]!)
234 let files = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
235 .filter { $0.pathExtension == "org" }.sorted { $0.path < $1.path }
236 .compactMap { url in (try? String(contentsOf: url, encoding: .utf8)).map { (url.lastPathComponent, $0) } }
237 for today in [Days.absolute(Date(), calendar: .current), Days.absolute(year: 2025, month: 3, day: 14)] {
238 try AgendaOracle.compare(files: files, start: today - 3, span: 10, today: today)
239 }
240 }
241}