Tests/OrgCoreTests/AgendaTests.swift

87e24faa398b297d22cbc8cb585e8bb0a666c4ec
orgstar/Tests/OrgCoreTests/AgendaTests.swift history · blame · raw

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