Sources/OrgCore/Commands/UserCommands.swift
266 lines · 11957 bytes
1import Foundation
2
3/// A command the user wrote: an exported function of a JavaScript module in the configuration
4/// folder's `commands/`, declared in `commands.toml`. Running it is the app's work, so `run`
5/// always asks for it as `.external(.userCommand)`.
6public struct UserCommand: OrgCommand, Equatable {
7 public let name: String
8 /// Shown as written; titles aren't translated.
9 public let title: String
10 /// The module, relative to `commands/`.
11 public let file: String
12 public let function: String
13 /// A `KeyContext` name; nil applies everywhere.
14 public let when: String?
15 /// Seconds, at most `UserCommands.maximumTimeout`.
16 public let timeout: Int
17 /// `workspace = true`: the command may also search the folders, read other files' outlines
18 /// and the agenda, and capture.
19 public let workspace: Bool
20
21 public init(name: String, title: String, file: String, function: String, when: String? = nil, timeout: Int = UserCommands.defaultTimeout,
22 workspace: Bool = false) {
23 self.name = name
24 self.title = title
25 self.file = file
26 self.function = function
27 self.when = when
28 self.timeout = timeout
29 self.workspace = workspace
30 }
31
32 public var id: String { UserCommands.commandPrefix + name }
33
34 public func applies(in context: EditContext) -> Bool {
35 when.map { KeyContext.holds($0, in: context) } ?? true
36 }
37
38 public func run(in context: EditContext) -> CommandStep {
39 .external(.userCommand(UserCommandRequest(command: self, revision: context.revision, selection: context.selection)))
40 }
41}
42
43/// A user command to run against the buffer at `revision` with `selection`.
44public struct UserCommandRequest: Sendable, Equatable {
45 public let command: UserCommand
46 public let revision: Int
47 public let selection: [Range<Int>]
48
49 public init(command: UserCommand, revision: Int, selection: [Range<Int>]) {
50 self.command = command
51 self.revision = revision
52 self.selection = selection
53 }
54}
55
56/// A function of a module in `commands/` that runs when something happens rather than from a
57/// key, declared as `[[hook]]` in `commands.toml`. There are no per-keystroke hooks.
58public struct UserHook: Sendable, Equatable {
59 public enum Event: String, Sendable, CaseIterable {
60 /// `org-after-todo-state-change-hook`: after a command changed an entry's TODO keyword.
61 case afterTodoStateChange = "after-todo-state-change"
62 /// `org-capture-before-finalize-hook`: before a capture is filed.
63 case captureBeforeFinalize = "capture-before-finalize"
64 }
65
66 public let event: Event
67 /// The module, relative to `commands/`.
68 public let file: String
69 public let function: String
70 /// Seconds, at most `UserCommands.maximumTimeout`.
71 public let timeout: Int
72 /// `workspace = true`, as for commands.
73 public let workspace: Bool
74
75 public init(event: Event, file: String, function: String, timeout: Int = UserCommands.defaultTimeout, workspace: Bool = false) {
76 self.event = event
77 self.file = file
78 self.function = function
79 self.timeout = timeout
80 self.workspace = workspace
81 }
82
83 /// How messages name it: `logDone in commands/todo.js`.
84 public var title: String { "\(function) in \(UserCommands.folderName)/\(file)" }
85}
86
87/// The commands of `commands.toml`, which the app reads from the configuration folder.
88public final class UserCommands: @unchecked Sendable {
89 public static let shared = UserCommands()
90 public static let commandPrefix = "user."
91 public static let fileName = "commands.toml"
92 /// The folder beside `commands.toml` that holds the modules.
93 public static let folderName = "commands"
94 /// The newest `api` this version runs.
95 public static let apiVersion = 1
96 public static let defaultTimeout = 2
97 public static let maximumTimeout = 30
98
99 private let lock = NSLock()
100 private var commands: [UserCommand] = []
101 private var hookList: [UserHook] = []
102 private var modules: URL?
103
104 public init() {}
105
106 /// In file order.
107 public var all: [UserCommand] { lock.withLock { commands } }
108
109 /// The `commands` folder the modules are in; nil before a file was read.
110 public var folder: URL? { lock.withLock { modules } }
111
112 /// The hooks for `event`, in file order.
113 public func hooks(_ event: UserHook.Event) -> [UserHook] {
114 lock.withLock { hookList.filter { $0.event == event } }
115 }
116
117 public func command(_ id: String) -> UserCommand? {
118 guard id.hasPrefix(Self.commandPrefix) else { return nil }
119 let name = id.dropFirst(Self.commandPrefix.count)
120 return lock.withLock { commands.first { $0.name == name } }
121 }
122
123 /// Replaces every command and hook, as from the file, with the folder their modules are in.
124 public func replace(_ all: [UserCommand], hooks: [UserHook] = [], folder: URL?) {
125 lock.withLock {
126 commands = all
127 hookList = hooks
128 modules = folder
129 }
130 }
131
132 static let keys: Set<String> = ["name", "title", "file", "function", "when", "timeout", "workspace"]
133 static let hookKeys: Set<String> = ["event", "file", "function", "timeout", "workspace"]
134
135 /// The commands of a `commands.toml`, as `manifest` reads them.
136 public static func parse(_ toml: String, problems: inout [String], exists: (String) -> Bool) throws -> [UserCommand] {
137 try manifest(toml, problems: &problems, exists: exists).commands
138 }
139
140 /// The commands and hooks of a `commands.toml`. Entries that can't be used are skipped and
141 /// reported in `problems`; with a missing or newer `api`, none is used. `exists` says
142 /// whether a module path (relative to `commands/`) is there. A file that isn't valid TOML
143 /// throws.
144 public static func manifest(_ toml: String, problems: inout [String], exists: (String) -> Bool) throws
145 -> (commands: [UserCommand], hooks: [UserHook]) {
146 let tables = try TOML.parse(toml)
147 var api: Int?
148 var result: [UserCommand] = []
149 var hooks: [UserHook] = []
150 var names = Set<String>()
151 for table in tables {
152 if table.name.isEmpty {
153 for key in table.keys where key != "api" { problems.append("unknown key \(key)") }
154 if let value = table.values["api"] {
155 guard let number = value.integer else {
156 problems.append("api must be a number")
157 continue
158 }
159 api = number
160 }
161 continue
162 }
163 guard ["command", "hook"].contains(table.name), table.isArrayElement else {
164 problems.append("line \(table.line): unknown table [\(table.name)]")
165 continue
166 }
167 if table.name == "hook" {
168 func problem(_ text: String) { problems.append("hook at line \(table.line): \(text)") }
169 for key in table.keys where !hookKeys.contains(key) { problem("unknown key \(key)") }
170 guard let name = table.values["event"]?.string else {
171 problem("missing event")
172 continue
173 }
174 guard let event = UserHook.Event(rawValue: name) else {
175 problem("unknown event \(name); the events are \(UserHook.Event.allCases.map(\.rawValue).joined(separator: " and "))")
176 continue
177 }
178 guard let module = module(table, exists: exists, problem: problem) else { continue }
179 hooks.append(UserHook(event: event, file: module.file, function: module.function, timeout: module.timeout, workspace: module.workspace))
180 continue
181 }
182 guard let name = table.values["name"]?.string, NamedMacros.isValidName(name) else {
183 problems.append("line \(table.line): command needs a name of letters, digits, - and _")
184 continue
185 }
186 func problem(_ text: String) { problems.append("command \(name): \(text)") }
187 for key in table.keys where !keys.contains(key) { problem("unknown key \(key)") }
188 guard names.insert(name).inserted else {
189 problem("defined twice")
190 continue
191 }
192 guard let module = module(table, exists: exists, problem: problem) else { continue }
193 let when = table.values["when"]?.string
194 if let when, !KeyContext.names.contains(when) {
195 problem("unknown context \(when)")
196 continue
197 }
198 if let value = table.values["title"], value.string == nil { problem("title must be a string") }
199 let title = table.values["title"]?.string.flatMap { $0.isEmpty ? nil : $0 } ?? name
200 result.append(UserCommand(name: name, title: title, file: module.file, function: module.function, when: when,
201 timeout: module.timeout, workspace: module.workspace))
202 }
203 guard let api else {
204 if !result.isEmpty || !hooks.isEmpty || tables.contains(where: { ["command", "hook"].contains($0.name) }) {
205 problems.append("missing api = \(apiVersion)")
206 }
207 return ([], [])
208 }
209 guard api == apiVersion else {
210 problems.append(api > apiVersion ? "api \(api) needs a newer orgstar" : "unknown api \(api)")
211 return ([], [])
212 }
213 return (result, hooks)
214 }
215
216 /// The `file`, `function`, `timeout` and `workspace` of a command or hook; nil once the
217 /// first that can't be used is reported.
218 private static func module(_ table: TOML.Table, exists: (String) -> Bool, problem: (String) -> Void)
219 -> (file: String, function: String, timeout: Int, workspace: Bool)? {
220 guard let file = table.values["file"]?.string, !file.isEmpty else {
221 problem("missing file")
222 return nil
223 }
224 guard isModulePath(file) else {
225 problem("file must be a .js or .mjs file in \(folderName)/")
226 return nil
227 }
228 guard exists(file) else {
229 problem("no file \(folderName)/\(file)")
230 return nil
231 }
232 guard let function = table.values["function"]?.string, isIdentifier(function) else {
233 problem("function must be the name of an exported function")
234 return nil
235 }
236 var timeout = defaultTimeout
237 if let value = table.values["timeout"] {
238 guard let seconds = value.integer, (1...maximumTimeout).contains(seconds) else {
239 problem("timeout must be 1 to \(maximumTimeout) seconds")
240 return nil
241 }
242 timeout = seconds
243 }
244 var workspace = false
245 if let value = table.values["workspace"] {
246 guard let flag = value.bool else {
247 problem("workspace must be true or false")
248 return nil
249 }
250 workspace = flag
251 }
252 return (file, function, timeout, workspace)
253 }
254
255 /// A path of `.js` or `.mjs` file below `commands/`, without `.`, `..` or empty parts.
256 public static func isModulePath(_ path: String) -> Bool {
257 let parts = path.split(separator: "/", omittingEmptySubsequences: false)
258 return parts.allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains(where: { "?#%\\".contains($0) }) }
259 && (path.hasSuffix(".js") || path.hasSuffix(".mjs"))
260 }
261
262 static func isIdentifier(_ name: String) -> Bool {
263 guard let first = name.unicodeScalars.first, !CharacterSet.decimalDigits.contains(first) else { return false }
264 return name.unicodeScalars.allSatisfy { $0.isASCII && (CharacterSet.alphanumerics.contains($0) || $0 == "_" || $0 == "$") }
265 }
266}