Tests/OrgAppTests/UserCommandRunTests.swift
278 lines · 13327 bytes
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// User commands run through the real command host against a session's buffer.
8@MainActor
9@Suite(.serialized)
10struct UserCommandRunTests {
11 static let manifest = """
12 api = 1
13
14 [[command]]
15 name = "upcase-title"
16 title = "Upcase Heading Title"
17 file = "headings.js"
18 function = "upcaseTitle"
19 when = "heading"
20
21 [[command]]
22 name = "weekly-review"
23 title = "Add Weekly Review"
24 file = "review.js"
25 function = "weeklyReview"
26
27 [[command]]
28 name = "overlap"
29 file = "bad.js"
30 function = "overlap"
31
32 [[command]]
33 name = "loop"
34 file = "bad.js"
35 function = "loop"
36 timeout = 1
37
38 [[command]]
39 name = "refuse"
40 file = "bad.js"
41 function = "refuse"
42
43 [[command]]
44 name = "copy"
45 file = "bad.js"
46 function = "copy"
47 """
48 static let headings = """
49 import { upper } from "./lib/text.js";
50
51 export async function upcaseTitle(org) {
52 const heading = await org.heading();
53 if (!heading) return org.fail("Not in an entry");
54 const text = await org.text();
55 const title = text.slice(heading.titleStart, heading.titleEnd);
56 return {
57 edits: [{ from: heading.titleStart, to: heading.titleEnd, text: upper(title) }],
58 message: `Upcased ${title}`,
59 };
60 }
61 """
62 static let review = """
63 export async function weeklyReview(org) {
64 const heading = await org.heading();
65 if (!heading) return org.fail("Not on a heading");
66 const week = await org.prompt({ message: "Week: ", initial: "W48" });
67 return {
68 edits: [{ from: heading.end, to: heading.end, text: `${"*".repeat(heading.level + 1)} Review ${week}\\n` }],
69 selection: heading.end + heading.level + 2,
70 };
71 }
72 """
73 static let bad = """
74 export function overlap() { return { edits: [{ from: 0, to: 4 }, { from: 2, to: 6 }] }; }
75 export function loop() { for (;;) {} }
76 export async function refuse(org) { await org.fail("Not today"); }
77 export async function copy(org) { org.message("Copying"); return { copy: (await org.file()) ?? "none" }; }
78 """
79 static let file = "* Plan the week :work:\nbody\n* Next\n"
80
81 let config: Folder
82 let notes: Folder
83 let path: String
84 let session: DocumentSession
85 let buffer: StateBuffer
86
87 init() throws {
88 config = try Folder()
89 notes = try Folder()
90 try config.write("commands.toml", Self.manifest)
91 try config.write("commands/headings.js", Self.headings)
92 try config.write("commands/lib/text.js", "export const upper = s => s.toUpperCase();\n")
93 try config.write("commands/review.js", Self.review)
94 try config.write("commands/bad.js", Self.bad)
95 path = try notes.write("a.org", Self.file).path
96 session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
97 session.saveMode = .explicit
98 session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
99 session.userCommands = UserCommands()
100 #expect(UserCommandFile.load(into: session.userCommands, folder: config.url) == [])
101 session.open(path)
102 buffer = StateBuffer(try #require(session.document))
103 session.attach(buffer)
104 }
105
106 func run(_ name: String, at caret: Int = 4, ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void = { _, reply in reply(nil) },
107 report: @escaping @MainActor (String) -> Void = { _ in }) async throws -> String? {
108 let command = try #require(session.userCommands.command("user." + name))
109 let document = buffer.document
110 let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [caret..<caret])
111 guard case .external(.userCommand(let request)) = command.run(in: context) else { throw CancellationError() }
112 return await session.runUserCommand(request, context: context, file: "a.org", ask: ask, report: report)
113 }
114
115 @Test func upcasesTheHeadingTitle() async throws {
116 #expect(try await run("upcase-title") == nil)
117 #expect(buffer.document.text == "* PLAN THE WEEK :work:\nbody\n* Next\n")
118 // Before the first heading, `org.fail`'s text.
119 _ = buffer.perform(ReplaceText(old: buffer.document.text, new: "intro\n" + Self.file), now: Date(), answers: [:])
120 #expect(try await run("upcase-title", at: 0) == "Not in an entry")
121 }
122
123 @Test func asksThroughThePrompt() async throws {
124 var asked: Prompt?
125 let message = try await run("weekly-review", ask: { prompt, reply in
126 asked = prompt
127 reply("W49")
128 })
129 #expect(message == nil)
130 #expect(asked == Prompt(key: "user", message: "Week: ", initial: "W48", requireMatch: false))
131 #expect(buffer.document.text == "* Plan the week :work:\nbody\n** Review W49\n* Next\n")
132 #expect(buffer.selection == [31..<31])
133 // A canceled prompt ends the command with nothing changed.
134 #expect(try await run("weekly-review") == "Quit")
135 #expect(buffer.document.text == "* Plan the week :work:\nbody\n** Review W49\n* Next\n")
136 }
137
138 @Test func anEditWhileItRanRefusesItsResult() async throws {
139 let message = try await run("weekly-review", ask: { [buffer] _, reply in
140 _ = buffer.perform(ReplaceText(old: buffer.document.text, new: buffer.document.text + "typed\n"), now: Date(), answers: [:])
141 reply("W49")
142 })
143 #expect(message == "The file changed; try again.")
144 #expect(buffer.document.text == Self.file + "typed\n")
145 }
146
147 @Test func refusesWhatCantApply() async throws {
148 #expect(try await run("overlap") == "overlap: edits overlap")
149 #expect(try await run("refuse") == "Not today")
150 let start = ContinuousClock.now
151 #expect(try await run("loop") == "loop didn't finish within 1 s and was stopped.")
152 #expect(ContinuousClock.now - start < .seconds(10))
153 #expect(buffer.document.text == Self.file)
154 var reported: [String] = []
155 #expect(try await run("copy", report: { reported.append($0) }) == nil)
156 #expect(reported == ["Copying"])
157 }
158
159 @Test func cancelStopsTheCommand() async throws {
160 let document = buffer.document
161 let command = try #require(session.userCommands.command("user.loop"))
162 let request = UserCommandRequest(command: command, revision: document.revision, selection: [0..<0])
163 let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [0..<0])
164 var reported: [String] = []
165 session.startUserCommand(request, context: context, file: nil, ask: { _, reply in reply(nil) }) { reported.append($0) }
166 #expect(session.isRunningUserCommand)
167 try await Task.sleep(for: .milliseconds(200))
168 session.cancelUserCommand()
169 for _ in 0..<100 where reported.isEmpty { try await Task.sleep(for: .milliseconds(20)) }
170 #expect(reported == ["loop canceled."])
171 #expect(!session.isRunningUserCommand)
172 }
173
174 @Test func refusedInBuffersWithDecryptedText() async throws {
175 let gpg = notes.url.appendingPathComponent("d.org.gpg")
176 try OpenPGP.encryptedMessage(Data("* Secret\n".utf8), passphrase: "pw").write(to: gpg)
177 session.open(gpg.path)
178 #expect(session.unlock("pw", for: gpg.path) == nil)
179 #expect(session.refusesUserCommand(gpg.path) == "d.org.gpg has decrypted entries, so user commands don't run in it.")
180 let document = try #require(session.document)
181 let command = try #require(session.userCommands.command("user.upcase-title"))
182 let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [3..<3])
183 let request = UserCommandRequest(command: command, revision: document.revision, selection: [3..<3])
184 #expect(await session.runUserCommand(request, context: context, file: nil, ask: { _, _ in }, report: { _ in })
185 == "d.org.gpg has decrypted entries, so user commands don't run in it.")
186 #expect(session.document?.text == "* Secret\n")
187 #expect(session.refusesUserCommand(path) == nil)
188 }
189}
190
191@MainActor
192struct UserCommandFileTests {
193 @Test func reportsProblemsByFile() throws {
194 let config = try Folder()
195 let store = UserCommands()
196 #expect(UserCommandFile.load(into: store, folder: config.url) == [])
197 try config.write("commands.toml", "api = 1\n[[command]]\nname = \"a\"\nfile = \"a.js\"\nfunction = \"a\"\n")
198 #expect(UserCommandFile.load(into: store, folder: config.url) == ["commands.toml: command a: no file commands/a.js"])
199 #expect(store.all.isEmpty && store.folder == nil)
200 try config.write("commands/a.js", "export function a() {}\n")
201 #expect(UserCommandFile.load(into: store, folder: config.url) == [])
202 #expect(store.all.map(\.id) == ["user.a"])
203 #expect(store.folder?.lastPathComponent == "commands")
204 try config.write("commands.toml", "api = 1\n[[command]\n")
205 #expect(UserCommandFile.load(into: store, folder: config.url) == ["commands.toml: line 2: unclosed table header"])
206 #expect(store.all.isEmpty)
207 }
208
209 @Test func importsResolveInsideTheFolder() {
210 let text = """
211 import { a } from "./a.js";
212 import * as b from '../b.js';
213 export { c } from "./lib/c.mjs";
214 import "./side.js";
215 const d = await import("./d.js");
216 import e from "https://example.com/e.js";
217 """
218 #expect(UserCommandFile.imports(text, from: "sub/main.js").sorted() == ["b.js", "sub/a.js", "sub/d.js", "sub/lib/c.mjs", "sub/side.js"])
219 #expect(UserCommandFile.imports("import x from '../../x.js';", from: "main.js") == [])
220 }
221
222 @Test func relativePath() {
223 #expect(UserCommandFile.relativePath("/n/notes/a/b.org", roots: ["/n", "/n/notes"]) == "a/b.org")
224 #expect(UserCommandFile.relativePath("/elsewhere/c.org", roots: ["/n"]) == "c.org")
225 }
226
227 /// Always keeps trust for the file and its imports as they are; a change to either, as one
228 /// arriving by sync, asks again.
229 @Test func aChangedScriptAsksForTrustAgain() throws {
230 let config = try Folder()
231 try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return x; }\n")
232 try config.write("commands/lib.js", "export const x = null;\n")
233 let modules = config.url.appendingPathComponent("commands")
234 let trust = TrustStore(file: config.url.appendingPathComponent("trusted.json"))
235 let command = UserCommand(name: "go", title: "Go", file: "main.js", function: "go")
236 var asked: [String] = []
237 var runs = 0
238 var refusals: [String] = []
239 func check(_ answer: String?) {
240 UserCommandTrust.check(command, modules: modules, trust: trust, ask: { prompt, reply in
241 asked.append(prompt.message)
242 reply(answer)
243 }, run: { runs += 1 }, refuse: { refusals.append($0) })
244 }
245 check(UserCommandTrust.dontRun)
246 #expect(runs == 0 && refusals == ["Not run"])
247 #expect(asked == ["Run commands from commands/main.js?"])
248 check(UserCommandTrust.runOnce)
249 check(UserCommandTrust.runOnce)
250 #expect(runs == 2 && asked.count == 3)
251 check(UserCommandTrust.always)
252 check(nil)
253 #expect(runs == 4 && asked.count == 4)
254 try config.write("commands/lib.js", "export const x = 1;\n")
255 check(UserCommandTrust.always)
256 #expect(runs == 5 && asked.count == 5)
257 try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return 2; }\n")
258 check(nil)
259 #expect(runs == 5 && asked.count == 6 && refusals == ["Not run", "Not run"])
260 // Back to a version trusted before, it runs without asking.
261 try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return x; }\n")
262 check(nil)
263 #expect(runs == 6)
264 #expect(UserCommandFile.trustedText("gone.js", modules: modules) == nil)
265 }
266
267 @Test func emacsImportNotesBindingsToTheUsersFunctions() throws {
268 let folder = try Folder()
269 try folder.write("init.el", """
270 (defun my/weekly-review () (interactive) (org-insert-heading))
271 (global-set-key (kbd "C-c w") #'my/weekly-review)
272 (global-set-key (kbd "C-c q") #'some-package-command)
273 """)
274 let result = EmacsImport.scan(EmacsImport.files(in: folder.url))
275 #expect(result.unsupported.contains { $0.name == "C-c w → my/weekly-review" && $0.reason == "your own function; write it as a user command in commands.toml" })
276 #expect(result.unsupported.contains { $0.name == "C-c q → some-package-command" && $0.reason == "orgstar has no such command" })
277 }
278}