Tests/OrgCoreTests/UserCommandTests.swift

de2aded7684eed392547e008fce57921e637d7bf
orgstar/Tests/OrgCoreTests/UserCommandTests.swift

374 lines · 18169 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct UserCommandManifestTests {
  6    func parse(_ toml: String, files: Set<String> = ["review.js", "lib/dates.mjs"]) throws -> ([UserCommand], [String]) {
  7        var problems: [String] = []
  8        let commands = try UserCommands.parse(toml, problems: &problems) { files.contains($0) }
  9        return (commands, problems)
 10    }
 11
 12    @Test func readsCommands() throws {
 13        let (commands, problems) = try parse("""
 14            api = 1
 15
 16            [[command]]
 17            name = "weekly-review"
 18            title = "Start Weekly Review"
 19            file = "review.js"
 20            function = "weeklyReview"
 21            when = "heading"
 22            timeout = 5
 23
 24            [[command]]
 25            name = "dates"
 26            file = "lib/dates.mjs"
 27            function = "$fix_dates"
 28            """)
 29        #expect(problems == [])
 30        #expect(commands == [
 31            UserCommand(name: "weekly-review", title: "Start Weekly Review", file: "review.js", function: "weeklyReview", when: "heading", timeout: 5),
 32            UserCommand(name: "dates", title: "dates", file: "lib/dates.mjs", function: "$fix_dates", timeout: 2),
 33        ])
 34        #expect(commands[0].id == "user.weekly-review")
 35    }
 36
 37    @Test func reportsProblemsByCommandAndKey() throws {
 38        let (commands, problems) = try parse("""
 39            api = 1
 40            extra = true
 41
 42            [[command]]
 43            name = "ok"
 44            file = "review.js"
 45            function = "ok"
 46            colour = "red"
 47
 48            [[command]]
 49            name = "missing"
 50            file = "gone.js"
 51            function = "f"
 52
 53            [[command]]
 54            name = "outside"
 55            file = "../secret.js"
 56            function = "f"
 57
 58            [[command]]
 59            name = "bad function"
 60            file = "review.js"
 61            function = "f"
 62
 63            [[command]]
 64            name = "fn"
 65            file = "review.js"
 66            function = "1f"
 67
 68            [[command]]
 69            name = "ctx"
 70            file = "review.js"
 71            function = "f"
 72            when = "everywhere"
 73
 74            [[command]]
 75            name = "slow"
 76            file = "review.js"
 77            function = "f"
 78            timeout = 60
 79
 80            [[command]]
 81            name = "ok"
 82            file = "review.js"
 83            function = "again"
 84
 85            [other]
 86            """)
 87        #expect(commands.map(\.name) == ["ok"])
 88        #expect(problems == [
 89            "unknown key extra",
 90            "command ok: unknown key colour",
 91            "command missing: no file commands/gone.js",
 92            "command outside: file must be a .js or .mjs file in commands/",
 93            "line 20: command needs a name of letters, digits, - and _",
 94            "command fn: function must be the name of an exported function",
 95            "command ctx: unknown context everywhere",
 96            "command slow: timeout must be 1 to 30 seconds",
 97            "command ok: defined twice",
 98            "line 47: unknown table [other]",
 99        ])
100    }
101
102    @Test func readsWorkspaceAccess() throws {
103        let (commands, problems) = try parse("""
104            api = 1
105
106            [[command]]
107            name = "find"
108            file = "review.js"
109            function = "find"
110            workspace = true
111
112            [[command]]
113            name = "bad"
114            file = "review.js"
115            function = "bad"
116            workspace = "yes"
117            """)
118        #expect(commands == [UserCommand(name: "find", title: "find", file: "review.js", function: "find", workspace: true)])
119        #expect(problems == ["command bad: workspace must be true or false"])
120    }
121
122    @Test func readsHooksAndTheirProblems() throws {
123        var problems: [String] = []
124        let manifest = try UserCommands.manifest("""
125            api = 1
126
127            [[hook]]
128            event = "after-todo-state-change"
129            file = "review.js"
130            function = "logState"
131
132            [[hook]]
133            event = "capture-before-finalize"
134            file = "lib/dates.mjs"
135            function = "check"
136            timeout = 5
137            workspace = true
138
139            [[hook]]
140            event = "post-command"
141            file = "review.js"
142            function = "f"
143
144            [[hook]]
145            file = "review.js"
146            function = "f"
147
148            [[hook]]
149            event = "after-todo-state-change"
150            file = "gone.js"
151            function = "f"
152            name = "x"
153
154            [[hook]]
155            event = "capture-before-finalize"
156            file = "review.js"
157            function = "f"
158            timeout = 0
159            """, problems: &problems) { ["review.js", "lib/dates.mjs"].contains($0) }
160        #expect(manifest.commands == [])
161        #expect(manifest.hooks == [
162            UserHook(event: .afterTodoStateChange, file: "review.js", function: "logState"),
163            UserHook(event: .captureBeforeFinalize, file: "lib/dates.mjs", function: "check", timeout: 5, workspace: true),
164        ])
165        #expect(problems == [
166            "hook at line 15: unknown event post-command; the events are after-todo-state-change and capture-before-finalize",
167            "hook at line 20: missing event",
168            "hook at line 24: unknown key name",
169            "hook at line 24: no file commands/gone.js",
170            "hook at line 30: timeout must be 1 to 30 seconds",
171        ])
172        #expect(manifest.hooks[0].title == "logState in commands/review.js")
173        let store = UserCommands()
174        store.replace([], hooks: manifest.hooks, folder: nil)
175        #expect(store.hooks(.captureBeforeFinalize) == [manifest.hooks[1]])
176        // Hooks need the api line as commands do.
177        problems = []
178        _ = try UserCommands.manifest("[[hook]]\nevent = \"after-todo-state-change\"\nfile = \"review.js\"\nfunction = \"f\"\n", problems: &problems) { _ in true }
179        #expect(problems == ["missing api = 1"])
180    }
181
182    /// Every route `org-todo` takes reports the change, with the heading where it starts after
183    /// the edits; a repeating entry reports the done keyword it was given.
184    @Test func todoChangesAreEffects() {
185        func changes(_ text: String, at caret: Int, _ command: any OrgCommand) -> [TodoStateChange] {
186            let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
187            guard case .commit(let result) = command.run(in: context) else { return [] }
188            return result.effects.compactMap { if case .todoStateChanged(let change) = $0 { change } else { nil } }
189        }
190        let text = "* Parent [0/1]\n** Child\n"
191        #expect(changes(text, at: 17, TodoCycle()) == [TodoStateChange(heading: 15, from: nil, to: "TODO")])
192        #expect(changes("* TODO Task\n", at: 3, SetTodo(keyword: "DONE")) == [TodoStateChange(heading: 0, from: "TODO", to: "DONE")])
193        #expect(changes("* TODO Task\n", at: 3, SetTodo(keyword: "TODO")) == [])
194        let repeating = "* TODO Water\nSCHEDULED: <2026-11-27 Fri +1w>\n"
195        #expect(changes(repeating, at: 3, TodoShift(right: true)) == [TodoStateChange(heading: 0, from: "TODO", to: "DONE")])
196        #expect(changes("* Plan\n", at: 0, PromoteHeading()) == [])
197    }
198
199    @Test func needsAKnownAPI() throws {
200        let command = "\n[[command]]\nname = \"a\"\nfile = \"review.js\"\nfunction = \"a\"\n"
201        #expect(try parse(command) == ([], ["missing api = 1"]))
202        #expect(try parse("api = 2\n" + command) == ([], ["api 2 needs a newer orgstar"]))
203        #expect(try parse("api = 0\n" + command) == ([], ["unknown api 0"]))
204        #expect(try parse("") == ([], []))
205        #expect(throws: TOML.ParseError.self) { _ = try parse("api = \n[[command") }
206    }
207
208    @Test func whenHidesTheCommandWhereItDoesntApply() {
209        let text = "intro\n* Heading\nbody\n"
210        let command = UserCommand(name: "h", title: "H", file: "a.js", function: "h", when: "heading")
211        func context(_ caret: Int) -> EditContext { EditContext(revision: 3, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) }
212        #expect(!command.applies(in: context(0)))
213        #expect(command.applies(in: context(8)))
214        #expect(UserCommand(name: "e", title: "E", file: "a.js", function: "e").applies(in: context(0)))
215        #expect(command.run(in: context(8)) == .external(.userCommand(UserCommandRequest(command: command, revision: 3, selection: [8..<8]))))
216    }
217
218    @Test func registry() {
219        let store = UserCommands()
220        let command = UserCommand(name: "a", title: "A", file: "a.js", function: "a")
221        store.replace([command], folder: URL(fileURLWithPath: "/c/commands"))
222        #expect(store.command("user.a") == command)
223        #expect(store.command("user.b") == nil)
224        #expect(store.command("a") == nil)
225        #expect(store.folder?.path == "/c/commands")
226    }
227}
228
229struct UserCommandAPITests {
230    static let text = """
231        #+FILETAGS: :home:
232        intro
233        * TODO [#A] Plan the week :work:
234        SCHEDULED: <2026-11-30 Mon> DEADLINE: <2026-12-04 Fri>
235        :PROPERTIES:
236        :EFFORT: 1:00
237        :END:
238        ** Sub é
239        * Done
240        """
241
242    func context(_ caret: Int, selection: [Range<Int>]? = nil) -> EditContext {
243        EditContext(revision: 7, text: Self.text, tree: OrgParser.parse(Self.text), selection: selection ?? [caret..<caret], knownTags: { ["work", "home"] })
244    }
245
246    func offset(_ needle: String) -> Int { (Self.text as NSString).range(of: needle).location }
247
248    @Test func headingAtThePoint() throws {
249        let context = context(offset("EFFORT"))
250        let heading = try #require(UserCommandAPI.answer("heading", NSNull(), context: context, file: nil) as? [String: Any])
251        #expect(heading["level"] as? Int == 1)
252        #expect(heading["keyword"] as? String == "TODO")
253        #expect(heading["done"] as? Bool == false)
254        #expect(heading["priority"] as? String == "A")
255        #expect(heading["title"] as? String == "Plan the week")
256        #expect(heading["tags"] as? [String] == ["work"])
257        #expect(heading["start"] as? Int == offset("* TODO"))
258        #expect(heading["end"] as? Int == offset("* Done"))
259        let titleStart = try #require(heading["titleStart"] as? Int), titleEnd = try #require(heading["titleEnd"] as? Int)
260        #expect((Self.text as NSString).substring(with: NSRange(titleStart..<titleEnd)) == "Plan the week")
261        #expect(heading["scheduled"] as? String == "<2026-11-30 Mon>")
262        #expect(heading["deadline"] as? String == "<2026-12-04 Fri>")
263        #expect(heading["closed"] is NSNull)
264        #expect(heading["properties"] as? [String: String] == ["EFFORT": "1:00"])
265        // Before the first heading, none; with an offset, the heading there.
266        #expect(UserCommandAPI.answer("heading", NSNull(), context: self.context(0), file: nil) is NSNull)
267        let sub = try #require(UserCommandAPI.answer("heading", offset("Sub") as NSNumber, context: context, file: nil) as? [String: Any])
268        #expect(sub["title"] as? String == "Sub é")
269        #expect(sub["level"] as? Int == 2)
270        #expect(sub["keyword"] is NSNull)
271    }
272
273    @Test func outlineSelectionTextFileAndSettings() throws {
274        let context = context(0, selection: [3..<5, 9..<9])
275        let outline = try #require(UserCommandAPI.answer("outline", NSNull(), context: context, file: nil) as? [[String: Any]])
276        #expect(outline.map { $0["title"] as? String } == ["Plan the week", "Sub é", "Done"])
277        #expect(outline.last?["end"] as? Int == (Self.text as NSString).length)
278        #expect(UserCommandAPI.answer("text", NSNull(), context: context, file: nil) as? String == Self.text)
279        #expect(UserCommandAPI.answer("selection", NSNull(), context: context, file: nil) as? [[String: Int]] == [["from": 3, "to": 5], ["from": 9, "to": 9]])
280        #expect(UserCommandAPI.answer("file", NSNull(), context: context, file: "notes/a.org") as? String == "notes/a.org")
281        #expect(UserCommandAPI.answer("file", NSNull(), context: context, file: nil) is NSNull)
282        let settings = try #require(UserCommandAPI.answer("settings", NSNull(), context: context, file: nil) as? [String: Any])
283        #expect(settings["todoKeywords"] as? [String] == ["TODO"])
284        #expect(settings["doneKeywords"] as? [String] == ["DONE"])
285        #expect(settings["fileTags"] as? [String] == ["home"])
286        #expect(settings["tags"] as? [String] == ["work", "home"])
287        #expect(settings["fillColumn"] as? Int == 70)
288        #expect(UserCommandAPI.answer("nope", NSNull(), context: context, file: nil) == nil)
289    }
290
291    func result(_ json: String) -> Result<EditResult, UserCommandAPI.Problem> {
292        UserCommandAPI.result(json, in: EditContext(revision: 4, text: "ab😀cd", tree: OrgParser.parse("ab😀cd"), selection: [0..<0]))
293    }
294
295    @Test func readsTheResult() {
296        #expect(result("null") == .success(EditResult(baseRevision: 4, edits: [])))
297        #expect(result(#"{"edits": [{"from": 5, "to": 6, "text": "D"}, {"from": 0, "to": 1}, {"from": 2, "text": "+"}], "selection": {"from": 1, "to": 2}, "message": "done", "copy": "x"}"#)
298            == .success(EditResult(baseRevision: 4, edits: [
299                TextEdit(range: 0..<1, replacement: ""), TextEdit(range: 2..<2, replacement: "+"), TextEdit(range: 5..<6, replacement: "D"),
300            ], selection: [1..<2], effects: [.message("done"), .copy("x")])))
301        #expect(result(#"{"selection": [3, {"from": 5, "to": 1}]}"#) == .success(EditResult(baseRevision: 4, edits: [], selection: [3..<3, 1..<5])))
302    }
303
304    @Test func refusesEditsThatCantApply() {
305        func problem(_ json: String) -> String? {
306            if case .failure(let problem) = result(json) { return problem.message }
307            return nil
308        }
309        #expect(problem(#"{"edits": [{"from": 0, "to": 2}, {"from": 1, "to": 4}]}"#) == "edits overlap")
310        #expect(problem(#"{"edits": [{"from": 1, "text": "a"}, {"from": 1, "text": "b"}]}"#) == "edits overlap")
311        #expect(problem(#"{"edits": [{"from": 5, "to": 9}]}"#) == "edit 1 is outside the text")
312        #expect(problem(#"{"edits": [{"from": 2, "to": 1}]}"#) == "edit 1 is outside the text")
313        #expect(problem(#"{"edits": [{"from": -1}]}"#) == "edit 1 is outside the text")
314        #expect(problem(#"{"edits": [{"from": 3}]}"#) == "edit 1 splits a character")
315        #expect(problem(#"{"edits": [{"from": 0.5}]}"#) == "edit 1 needs a from offset")
316        #expect(problem(#"{"edits": [{"from": 0, "text": 3}]}"#) == "edit 1 has a text that isn't a string")
317        #expect(problem(#"{"edits": {"from": 0}}"#) == "edits must be a list")
318        #expect(problem(#"{"edit": []}"#) == "returned an unknown key edit")
319        #expect(problem(#"{"selection": 7}"#) == "selection is outside the text")
320        #expect(problem(#"{"edits": [{"from": 0, "to": 6}], "selection": 2}"#) == "selection is outside the text")
321        #expect(problem(#"{"message": 3}"#) == "message must be a string")
322        #expect(problem(#""text""#) == "returned something other than an object")
323    }
324
325    @Test func prompts() {
326        let prompt = UserCommandAPI.prompt(["message": "Week: ", "initial": "W48", "choices": ["W48", "W49"], "requireMatch": true] as [String: Any])
327        #expect(prompt == Prompt(key: "user", message: "Week: ", initial: "W48", choices: ["W48", "W49"], requireMatch: true))
328        #expect(UserCommandAPI.prompt(["message": "Any: ", "requireMatch": true] as [String: Any]).requireMatch == false)
329        let date = UserCommandAPI.prompt(["message": "When? ", "date": true] as [String: Any])
330        #expect(date.date == Prompt.DateRead(defaultDate: nil))
331        var utc = Calendar(identifier: .gregorian)
332        utc.timeZone = TimeZone(identifier: "UTC")!
333        let now = Date(timeIntervalSince1970: 1_795_000_000)  // 2026-11-18
334        #expect(UserCommandAPI.answer("+2d", to: date, now: now, calendar: utc) == "2026-11-20")
335        #expect(UserCommandAPI.answer("2026-12-01 9:30", to: date, now: now, calendar: utc) == "2026-12-01 09:30")
336        #expect(UserCommandAPI.answer("+2d", to: prompt, now: now, calendar: utc) == "+2d")
337    }
338}
339
340struct UserCommandStateTests {
341    func context(_ text: String, caret: Int) -> EditContext {
342        EditContext(revision: 3, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
343    }
344
345    /// Commands run one after another on the text the last one left; the command's own edits
346    /// are in that text, and the result is one change from the text it started with.
347    @Test func composesIntoOneResult() throws {
348        var state = UserCommandState(context("* a\n* b\n", caret: 2), defaults: .default)
349        guard case .commit = state.run(TodoCycle(), answers: [:]) else { Issue.record("no commit"); return }
350        #expect(state.context.text == "* TODO a\n* b\n")
351        #expect(state.context.selection == [7..<7])
352        #expect(state.reply["text"] as? String == "* TODO a\n* b\n")
353        guard case .commit = state.run(NextHeading(), answers: [:]) else { Issue.record("no commit"); return }
354        let result = try state.result(#"{"edits": [{"from": 11, "text": "!"}]}"#).get()
355        #expect(result.baseRevision == 3)
356        #expect(result.edits.count == 1)
357        var text = state.start.text
358        for edit in result.edits.reversed() { text = edit.apply(to: text) }
359        #expect(text == "* TODO a\n* !b\n")
360        #expect(result.selection == [9..<9])
361    }
362
363    @Test func refusesWhatIsntBuiltIn() {
364        func refusal(_ id: String) -> String? {
365            if case .failure(let problem) = UserCommandAPI.builtIn(id) { return problem.message }
366            return nil
367        }
368        #expect(refusal("org.todo.cycle") == nil)
369        #expect(refusal("app.export.html") == "app.export.html is a command of the app, which user commands can't run")
370        #expect(refusal("user.other") == "A user command can't run another: user.other")
371        #expect(refusal("org.cycle") == "No built-in command org.cycle")
372        #expect(UserCommandAPI.safeAppCommands == ["app.save"])
373    }
374}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form