Tests/OrgCoreTests/UserCommandTests.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Tests/OrgCoreTests/UserCommandTests.swift

297 lines · 14580 bytes

24 symbols in this file
  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 needsAKnownAPI() throws {
123        let command = "\n[[command]]\nname = \"a\"\nfile = \"review.js\"\nfunction = \"a\"\n"
124        #expect(try parse(command) == ([], ["missing api = 1"]))
125        #expect(try parse("api = 2\n" + command) == ([], ["api 2 needs a newer orgstar"]))
126        #expect(try parse("api = 0\n" + command) == ([], ["unknown api 0"]))
127        #expect(try parse("") == ([], []))
128        #expect(throws: TOML.ParseError.self) { _ = try parse("api = \n[[command") }
129    }
130
131    @Test func whenHidesTheCommandWhereItDoesntApply() {
132        let text = "intro\n* Heading\nbody\n"
133        let command = UserCommand(name: "h", title: "H", file: "a.js", function: "h", when: "heading")
134        func context(_ caret: Int) -> EditContext { EditContext(revision: 3, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) }
135        #expect(!command.applies(in: context(0)))
136        #expect(command.applies(in: context(8)))
137        #expect(UserCommand(name: "e", title: "E", file: "a.js", function: "e").applies(in: context(0)))
138        #expect(command.run(in: context(8)) == .external(.userCommand(UserCommandRequest(command: command, revision: 3, selection: [8..<8]))))
139    }
140
141    @Test func registry() {
142        let store = UserCommands()
143        let command = UserCommand(name: "a", title: "A", file: "a.js", function: "a")
144        store.replace([command], folder: URL(fileURLWithPath: "/c/commands"))
145        #expect(store.command("user.a") == command)
146        #expect(store.command("user.b") == nil)
147        #expect(store.command("a") == nil)
148        #expect(store.folder?.path == "/c/commands")
149    }
150}
151
152struct UserCommandAPITests {
153    static let text = """
154        #+FILETAGS: :home:
155        intro
156        * TODO [#A] Plan the week :work:
157        SCHEDULED: <2026-11-30 Mon> DEADLINE: <2026-12-04 Fri>
158        :PROPERTIES:
159        :EFFORT: 1:00
160        :END:
161        ** Sub é
162        * Done
163        """
164
165    func context(_ caret: Int, selection: [Range<Int>]? = nil) -> EditContext {
166        EditContext(revision: 7, text: Self.text, tree: OrgParser.parse(Self.text), selection: selection ?? [caret..<caret], knownTags: { ["work", "home"] })
167    }
168
169    func offset(_ needle: String) -> Int { (Self.text as NSString).range(of: needle).location }
170
171    @Test func headingAtThePoint() throws {
172        let context = context(offset("EFFORT"))
173        let heading = try #require(UserCommandAPI.answer("heading", NSNull(), context: context, file: nil) as? [String: Any])
174        #expect(heading["level"] as? Int == 1)
175        #expect(heading["keyword"] as? String == "TODO")
176        #expect(heading["done"] as? Bool == false)
177        #expect(heading["priority"] as? String == "A")
178        #expect(heading["title"] as? String == "Plan the week")
179        #expect(heading["tags"] as? [String] == ["work"])
180        #expect(heading["start"] as? Int == offset("* TODO"))
181        #expect(heading["end"] as? Int == offset("* Done"))
182        let titleStart = try #require(heading["titleStart"] as? Int), titleEnd = try #require(heading["titleEnd"] as? Int)
183        #expect((Self.text as NSString).substring(with: NSRange(titleStart..<titleEnd)) == "Plan the week")
184        #expect(heading["scheduled"] as? String == "<2026-11-30 Mon>")
185        #expect(heading["deadline"] as? String == "<2026-12-04 Fri>")
186        #expect(heading["closed"] is NSNull)
187        #expect(heading["properties"] as? [String: String] == ["EFFORT": "1:00"])
188        // Before the first heading, none; with an offset, the heading there.
189        #expect(UserCommandAPI.answer("heading", NSNull(), context: self.context(0), file: nil) is NSNull)
190        let sub = try #require(UserCommandAPI.answer("heading", offset("Sub") as NSNumber, context: context, file: nil) as? [String: Any])
191        #expect(sub["title"] as? String == "Sub é")
192        #expect(sub["level"] as? Int == 2)
193        #expect(sub["keyword"] is NSNull)
194    }
195
196    @Test func outlineSelectionTextFileAndSettings() throws {
197        let context = context(0, selection: [3..<5, 9..<9])
198        let outline = try #require(UserCommandAPI.answer("outline", NSNull(), context: context, file: nil) as? [[String: Any]])
199        #expect(outline.map { $0["title"] as? String } == ["Plan the week", "Sub é", "Done"])
200        #expect(outline.last?["end"] as? Int == (Self.text as NSString).length)
201        #expect(UserCommandAPI.answer("text", NSNull(), context: context, file: nil) as? String == Self.text)
202        #expect(UserCommandAPI.answer("selection", NSNull(), context: context, file: nil) as? [[String: Int]] == [["from": 3, "to": 5], ["from": 9, "to": 9]])
203        #expect(UserCommandAPI.answer("file", NSNull(), context: context, file: "notes/a.org") as? String == "notes/a.org")
204        #expect(UserCommandAPI.answer("file", NSNull(), context: context, file: nil) is NSNull)
205        let settings = try #require(UserCommandAPI.answer("settings", NSNull(), context: context, file: nil) as? [String: Any])
206        #expect(settings["todoKeywords"] as? [String] == ["TODO"])
207        #expect(settings["doneKeywords"] as? [String] == ["DONE"])
208        #expect(settings["fileTags"] as? [String] == ["home"])
209        #expect(settings["tags"] as? [String] == ["work", "home"])
210        #expect(settings["fillColumn"] as? Int == 70)
211        #expect(UserCommandAPI.answer("nope", NSNull(), context: context, file: nil) == nil)
212    }
213
214    func result(_ json: String) -> Result<EditResult, UserCommandAPI.Problem> {
215        UserCommandAPI.result(json, in: EditContext(revision: 4, text: "ab😀cd", tree: OrgParser.parse("ab😀cd"), selection: [0..<0]))
216    }
217
218    @Test func readsTheResult() {
219        #expect(result("null") == .success(EditResult(baseRevision: 4, edits: [])))
220        #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"}"#)
221            == .success(EditResult(baseRevision: 4, edits: [
222                TextEdit(range: 0..<1, replacement: ""), TextEdit(range: 2..<2, replacement: "+"), TextEdit(range: 5..<6, replacement: "D"),
223            ], selection: [1..<2], effects: [.message("done"), .copy("x")])))
224        #expect(result(#"{"selection": [3, {"from": 5, "to": 1}]}"#) == .success(EditResult(baseRevision: 4, edits: [], selection: [3..<3, 1..<5])))
225    }
226
227    @Test func refusesEditsThatCantApply() {
228        func problem(_ json: String) -> String? {
229            if case .failure(let problem) = result(json) { return problem.message }
230            return nil
231        }
232        #expect(problem(#"{"edits": [{"from": 0, "to": 2}, {"from": 1, "to": 4}]}"#) == "edits overlap")
233        #expect(problem(#"{"edits": [{"from": 1, "text": "a"}, {"from": 1, "text": "b"}]}"#) == "edits overlap")
234        #expect(problem(#"{"edits": [{"from": 5, "to": 9}]}"#) == "edit 1 is outside the text")
235        #expect(problem(#"{"edits": [{"from": 2, "to": 1}]}"#) == "edit 1 is outside the text")
236        #expect(problem(#"{"edits": [{"from": -1}]}"#) == "edit 1 is outside the text")
237        #expect(problem(#"{"edits": [{"from": 3}]}"#) == "edit 1 splits a character")
238        #expect(problem(#"{"edits": [{"from": 0.5}]}"#) == "edit 1 needs a from offset")
239        #expect(problem(#"{"edits": [{"from": 0, "text": 3}]}"#) == "edit 1 has a text that isn't a string")
240        #expect(problem(#"{"edits": {"from": 0}}"#) == "edits must be a list")
241        #expect(problem(#"{"edit": []}"#) == "returned an unknown key edit")
242        #expect(problem(#"{"selection": 7}"#) == "selection is outside the text")
243        #expect(problem(#"{"edits": [{"from": 0, "to": 6}], "selection": 2}"#) == "selection is outside the text")
244        #expect(problem(#"{"message": 3}"#) == "message must be a string")
245        #expect(problem(#""text""#) == "returned something other than an object")
246    }
247
248    @Test func prompts() {
249        let prompt = UserCommandAPI.prompt(["message": "Week: ", "initial": "W48", "choices": ["W48", "W49"], "requireMatch": true] as [String: Any])
250        #expect(prompt == Prompt(key: "user", message: "Week: ", initial: "W48", choices: ["W48", "W49"], requireMatch: true))
251        #expect(UserCommandAPI.prompt(["message": "Any: ", "requireMatch": true] as [String: Any]).requireMatch == false)
252        let date = UserCommandAPI.prompt(["message": "When? ", "date": true] as [String: Any])
253        #expect(date.date == Prompt.DateRead(defaultDate: nil))
254        var utc = Calendar(identifier: .gregorian)
255        utc.timeZone = TimeZone(identifier: "UTC")!
256        let now = Date(timeIntervalSince1970: 1_795_000_000)  // 2026-11-18
257        #expect(UserCommandAPI.answer("+2d", to: date, now: now, calendar: utc) == "2026-11-20")
258        #expect(UserCommandAPI.answer("2026-12-01 9:30", to: date, now: now, calendar: utc) == "2026-12-01 09:30")
259        #expect(UserCommandAPI.answer("+2d", to: prompt, now: now, calendar: utc) == "+2d")
260    }
261}
262
263struct UserCommandStateTests {
264    func context(_ text: String, caret: Int) -> EditContext {
265        EditContext(revision: 3, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
266    }
267
268    /// Commands run one after another on the text the last one left; the command's own edits
269    /// are in that text, and the result is one change from the text it started with.
270    @Test func composesIntoOneResult() throws {
271        var state = UserCommandState(context("* a\n* b\n", caret: 2), defaults: .default)
272        guard case .commit = state.run(TodoCycle(), answers: [:]) else { Issue.record("no commit"); return }
273        #expect(state.context.text == "* TODO a\n* b\n")
274        #expect(state.context.selection == [7..<7])
275        #expect(state.reply["text"] as? String == "* TODO a\n* b\n")
276        guard case .commit = state.run(NextHeading(), answers: [:]) else { Issue.record("no commit"); return }
277        let result = try state.result(#"{"edits": [{"from": 11, "text": "!"}]}"#).get()
278        #expect(result.baseRevision == 3)
279        #expect(result.edits.count == 1)
280        var text = state.start.text
281        for edit in result.edits.reversed() { text = edit.apply(to: text) }
282        #expect(text == "* TODO a\n* !b\n")
283        #expect(result.selection == [9..<9])
284    }
285
286    @Test func refusesWhatIsntBuiltIn() {
287        func refusal(_ id: String) -> String? {
288            if case .failure(let problem) = UserCommandAPI.builtIn(id) { return problem.message }
289            return nil
290        }
291        #expect(refusal("org.todo.cycle") == nil)
292        #expect(refusal("app.export.html") == "app.export.html is a command of the app, which user commands can't run")
293        #expect(refusal("user.other") == "A user command can't run another: user.other")
294        #expect(refusal("org.cycle") == "No built-in command org.cycle")
295        #expect(UserCommandAPI.safeAppCommands == ["app.save"])
296    }
297}
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