import Foundation import Testing @testable import OrgCore struct ClockTests { static let texts = [ "* TODO Task\n", "* TODO Task\nBody text.\n", "* Task\nSCHEDULED: <2026-10-05 Mon>\n:PROPERTIES:\n:ID: x\n:END:\nBody\n", "* Task\n:LOGBOOK:\nCLOCK: [2026-10-04 Sun 09:00]--[2026-10-04 Sun 10:00] => 1:00\n:END:\nNotes\n", "* Task\nCLOCK: [2026-10-04 Sun 09:00]--[2026-10-04 Sun 10:00] => 1:00\nNotes\n", "* Task\n** Child\nChild body\n* Next\n", "* Task", "Preamble\n* Task\n- item\n", "* Task\n:LOGBOOK:\n- State \"DONE\" from \"TODO\" [2026-10-01 Thu 10:00]\n:END:\n", ] static var utc: Calendar { var c = Calendar(identifier: .gregorian) c.timeZone = TimeZone(identifier: "UTC")! return c } func run(_ command: any OrgCommand, _ text: String, caret: Int, at seconds: Int, options: EditingOptions = .org) -> (text: String, caret: Int, failure: String?) { let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret.. $1.range.lowerBound }) { new = edit.apply(to: new) } return (new, result.selection?.first?.lowerBound ?? caret, nil) case .failed(let message): return (text, caret, message) default: return (text, caret, "other") } } @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) func matchesEmacs() throws { try compare(Self.texts) } /// `org-clock-into-drawer` values, `org-log-into-drawer`, and the CLOCK_INTO_DRAWER and /// LOG_INTO_DRAWER properties. @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) func intoDrawerMatchesEmacs() throws { let texts = Self.texts + [ "* Task\nCLOCK: [2026-10-03 Sat 09:00]--[2026-10-03 Sat 10:00] => 1:00\nCLOCK: [2026-10-04 Sun 09:00]--[2026-10-04 Sun 10:00] => 1:00\n", "* Task\n:PROPERTIES:\n:CLOCK_INTO_DRAWER: nil\n:END:\nBody\n", "* Parent\n:PROPERTIES:\n:CLOCK_INTO_DRAWER: TIMES\n:END:\n** Task\nBody\n", "* Task\n:PROPERTIES:\n:CLOCK_INTO_DRAWER: 2\n:END:\nCLOCK: [2026-10-04 Sun 09:00]--[2026-10-04 Sun 10:00] => 1:00\n", "* Task\n:PROPERTIES:\n:CLOCK_INTO_DRAWER: t\n:LOG_INTO_DRAWER: NOTES\n:END:\n", ] for (lisp, value, log) in [("nil", "nil", nil), ("2", "2", nil), ("3", "3", nil), ("\"CLOCKS\"", "CLOCKS", nil), ("t", nil, "NOTES"), ("2", "2", "NOTES")] as [(String, String?, String?)] { var options = EditingOptions.org options.clockIntoDrawer = value options.logIntoDrawer = log try compare(texts, lisp: lisp, log: log.map { "\"\($0)\"" } ?? "nil", options: options) } } /// `org-clock-rounding-minutes`, `org-clock-out-remove-zero-time-clocks` and /// `org-clock-in-switch-to-state`. @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) func optionsMatchEmacs() throws { let texts = Self.texts + ["#+TODO: TODO NEXT | DONE\n* TODO Task\n", "#+TODO: TODO NEXT | DONE\n* NEXT Task\nBody\n"] var rounding = EditingOptions.org rounding.clockRoundingMinutes = 5 try compare(texts, extra: "org-clock-rounding-minutes 5", options: rounding) try compare(texts, extra: "org-clock-rounding-minutes 15", options: { var o = EditingOptions.org; o.clockRoundingMinutes = 15; return o }(), length: 7 * 60) var zero = EditingOptions.org zero.clockOutRemoveZeroTimeClocks = true try compare(texts, extra: "org-clock-out-remove-zero-time-clocks t", options: zero, length: 20) var state = EditingOptions.org state.clockInSwitchToState = "NEXT" try compare(texts, extra: "org-clock-in-switch-to-state \"NEXT\"", options: state) } func compare(_ texts: [String], lisp: String = "t", log: String = "nil", extra: String = "", options: EditingOptions = .org, length: Int = 3 * 3600 + 17 * 60 + 42) throws { let t1 = 1_789_000_000 // Thu 2026-09-10 00:26 let t2 = t1 + length var cases: [EmacsOracle.Case] = [] var ours: [(String, String)] = [] for text in texts { let caret = (text as NSString).range(of: "Task").location for mode in ["out", "cancel"] { // Clock in at t1, then out (or cancel) at t2. let first = run(ClockIn(), text, caret: caret, at: t1, options: options) // Clocking in failed: the text stays, as Emacs's does when it signals. if let start = ClockIn.runningStart(in: first.text, near: caret) { let second = run(ClockOut(start: start, cancel: mode == "cancel"), first.text, caret: first.caret, at: t2, options: options) ours.append((second.text, first.text)) } else { ours.append((first.text, first.failure ?? "")) } let out = mode == "cancel" ? "(org-clock-cancel)" : "(org-clock-out)" cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """ (progn (require 'org-clock) (setq org-clock-persist nil org-clock-idle-time nil org-clock-auto-clock-resolution nil org-clock-into-drawer \(lisp) org-log-into-drawer \(log) \(extra)) \(frozenClock(t1, "(org-clock-in)")) (setq orgstar-after-in (buffer-substring-no-properties (point-min) (point-max))) \(frozenClock(t2, out))) """)) } } let emacs = try EmacsOracle.run(cases) for (i, (mine, theirs)) in zip(ours, emacs).enumerated() { #expect(mine.0 == theirs.text, "case \(i) \(lisp) \(cases[i].form.contains("cancel") ? "cancel" : "out")\n\(cases[i].text.debugDescription)\nafter in (ours): \(mine.1.debugDescription)\nours: \(mine.0.debugDescription)\nemacs: \(theirs.text.debugDescription) \(theirs.error)") } } } struct ClockReportTests { static let config = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config/doom/config.el") static let sample = """ * TODO [#A] Audit work :work: :LOGBOOK: CLOCK: [2026-02-20 Fri 10:00]--[2026-02-20 Fri 16:00] => 6:00 CLOCK: [2026-02-17 Tue 16:22]--[2026-02-17 Tue 16:45] => 0:23 CLOCK: [2026-02-17 Tue 08:15]--[2026-02-17 Tue 08:50] => 0:35 :END: * Meetings :LOGBOOK: CLOCK: [2026-02-24 Tue 09:30]--[2026-02-24 Tue 10:00] => 0:30 CLOCK: [2026-03-02 Mon 09:00] CLOCK: [2026-02-17 Tue 09:28]--[2026-02-17 Tue 09:55] => 0:27 :END: """ @Test func totalsPerHeading() { let entries = ClockReport.entries(Self.sample) let all = ClockReport.byHeading(entries) #expect(all.map(\.heading) == ["Audit work", "Meetings"] && all.map(\.minutes) == [418, 57]) #expect(all[1].start == (Self.sample as NSString).range(of: "* Meetings").location) #expect(ClockReport.byHeading(entries, from: "2026-02-18", to: "2026-02-24").map(\.minutes) == [360, 30]) } /// Your own `tr/generate-report`, loaded from config.el in batch Emacs. static func emacsReport(_ text: String, start: String?, end: String?) throws -> String { let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-tr-\(UUID().uuidString)") try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: folder) } let input = folder.appendingPathComponent("time.org") let output = folder.appendingPathComponent("report.org") try text.write(to: input, atomically: true, encoding: .utf8) func lisp(_ s: String?) -> String { s.map { "\"\($0)\"" } ?? "nil" } let script = folder.appendingPathComponent("tr.el") try """ (require 'org) (require 'cl-lib) (require 'subr-x) (with-temp-buffer (insert-file-contents "\(config.path)") (goto-char (point-min)) (condition-case nil (while t (let ((form (read (current-buffer)))) (when (and (eq (car-safe form) 'defun) (string-prefix-p "tr/" (symbol-name (cadr form)))) (eval form t)))) (end-of-file nil))) (tr/generate-report "\(input.path)" "\(output.path)" \(lisp(start)) \(lisp(end))) """.write(to: script, atomically: true, encoding: .utf8) _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"]) return try String(contentsOf: output, encoding: .utf8) } @Test(.enabled(if: FileManager.default.fileExists(atPath: ClockReportTests.config.path) && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) func matchesYourReport() throws { var texts = [Self.sample] let work = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("git/cmc/work-notes/time.org") if let real = try? String(contentsOf: work, encoding: .utf8) { texts.append(real) } for text in texts { for (start, end) in [(nil, nil), ("2026-02-18", nil), (nil, "2026-02-20"), ("2026-02-17", "2026-02-17")] as [(String?, String?)] { let ours = ClockReport.timeReport(ClockReport.entries(text), start: start, end: end) let theirs = try Self.emacsReport(text, start: start, end: end) #expect(ours == theirs, "\(start ?? "-")..\(end ?? "-")\nours:\n\(ours)\ntheirs:\n\(theirs)") } } } } struct ClockDrawerStartupTests { @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) func startupLogdrawerMatchesEmacs() throws { let text = "#+STARTUP: nologdrawer\n* Task\nBody\n" let caret = (text as NSString).range(of: "Task").location let t1 = 1_789_000_000 var options = EditingOptions.org options.logIntoDrawer = "NOTES" let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret.. $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) } let emacs = try EmacsOracle.run([EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """ (progn (require 'org-clock) (setq org-clock-persist nil org-clock-idle-time nil org-clock-auto-clock-resolution nil org-clock-into-drawer t) (setq-default org-log-into-drawer "NOTES") (org-mode) \(frozenClock(t1, "(org-clock-in)"))) """)]) #expect(ours == emacs[0].text, "ours: \(ours.debugDescription)\nemacs: \(emacs[0].text.debugDescription) \(emacs[0].error)") } }