Sources/OrgCore/Commands/UserCommands.swift
193 lines · 8407 bytes
11 symbols in this file
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/// The commands of `commands.toml`, which the app reads from the configuration folder.
57public final class UserCommands: @unchecked Sendable {
58 public static let shared = UserCommands()
59 public static let commandPrefix = "user."
60 public static let fileName = "commands.toml"
61 /// The folder beside `commands.toml` that holds the modules.
62 public static let folderName = "commands"
63 /// The newest `api` this version runs.
64 public static let apiVersion = 1
65 public static let defaultTimeout = 2
66 public static let maximumTimeout = 30
67
68 private let lock = NSLock()
69 private var commands: [UserCommand] = []
70 private var modules: URL?
71
72 public init() {}
73
74 /// In file order.
75 public var all: [UserCommand] { lock.withLock { commands } }
76
77 /// The `commands` folder the modules are in; nil before a file was read.
78 public var folder: URL? { lock.withLock { modules } }
79
80 public func command(_ id: String) -> UserCommand? {
81 guard id.hasPrefix(Self.commandPrefix) else { return nil }
82 let name = id.dropFirst(Self.commandPrefix.count)
83 return lock.withLock { commands.first { $0.name == name } }
84 }
85
86 /// Replaces every command, as from the file, with the folder their modules are in.
87 public func replace(_ all: [UserCommand], folder: URL?) {
88 lock.withLock {
89 commands = all
90 modules = folder
91 }
92 }
93
94 static let keys: Set<String> = ["name", "title", "file", "function", "when", "timeout", "workspace"]
95
96 /// The commands of a `commands.toml`. Entries that can't be used are skipped and reported in
97 /// `problems`; with a missing or newer `api`, none is used. `exists` says whether a module
98 /// path (relative to `commands/`) is there. A file that isn't valid TOML throws.
99 public static func parse(_ toml: String, problems: inout [String], exists: (String) -> Bool) throws -> [UserCommand] {
100 let tables = try TOML.parse(toml)
101 var api: Int?
102 var result: [UserCommand] = []
103 var names = Set<String>()
104 for table in tables {
105 if table.name.isEmpty {
106 for key in table.keys where key != "api" { problems.append("unknown key \(key)") }
107 if let value = table.values["api"] {
108 guard let number = value.integer else {
109 problems.append("api must be a number")
110 continue
111 }
112 api = number
113 }
114 continue
115 }
116 guard table.name == "command", table.isArrayElement else {
117 problems.append("line \(table.line): unknown table [\(table.name)]")
118 continue
119 }
120 guard let name = table.values["name"]?.string, NamedMacros.isValidName(name) else {
121 problems.append("line \(table.line): command needs a name of letters, digits, - and _")
122 continue
123 }
124 func problem(_ text: String) { problems.append("command \(name): \(text)") }
125 for key in table.keys where !keys.contains(key) { problem("unknown key \(key)") }
126 guard names.insert(name).inserted else {
127 problem("defined twice")
128 continue
129 }
130 guard let file = table.values["file"]?.string, !file.isEmpty else {
131 problem("missing file")
132 continue
133 }
134 guard isModulePath(file) else {
135 problem("file must be a .js or .mjs file in \(folderName)/")
136 continue
137 }
138 guard exists(file) else {
139 problem("no file \(folderName)/\(file)")
140 continue
141 }
142 guard let function = table.values["function"]?.string, isIdentifier(function) else {
143 problem("function must be the name of an exported function")
144 continue
145 }
146 let when = table.values["when"]?.string
147 if let when, !KeyContext.names.contains(when) {
148 problem("unknown context \(when)")
149 continue
150 }
151 var timeout = defaultTimeout
152 if let value = table.values["timeout"] {
153 guard let seconds = value.integer, (1...maximumTimeout).contains(seconds) else {
154 problem("timeout must be 1 to \(maximumTimeout) seconds")
155 continue
156 }
157 timeout = seconds
158 }
159 var workspace = false
160 if let value = table.values["workspace"] {
161 guard let flag = value.bool else {
162 problem("workspace must be true or false")
163 continue
164 }
165 workspace = flag
166 }
167 if let value = table.values["title"], value.string == nil { problem("title must be a string") }
168 let title = table.values["title"]?.string.flatMap { $0.isEmpty ? nil : $0 } ?? name
169 result.append(UserCommand(name: name, title: title, file: file, function: function, when: when, timeout: timeout, workspace: workspace))
170 }
171 guard let api else {
172 if !result.isEmpty || tables.contains(where: { $0.name == "command" }) { problems.append("missing api = \(apiVersion)") }
173 return []
174 }
175 guard api == apiVersion else {
176 problems.append(api > apiVersion ? "api \(api) needs a newer orgstar" : "unknown api \(api)")
177 return []
178 }
179 return result
180 }
181
182 /// A path of `.js` or `.mjs` file below `commands/`, without `.`, `..` or empty parts.
183 public static func isModulePath(_ path: String) -> Bool {
184 let parts = path.split(separator: "/", omittingEmptySubsequences: false)
185 return parts.allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains(where: { "?#%\\".contains($0) }) }
186 && (path.hasSuffix(".js") || path.hasSuffix(".mjs"))
187 }
188
189 static func isIdentifier(_ name: String) -> Bool {
190 guard let first = name.unicodeScalars.first, !CharacterSet.decimalDigits.contains(first) else { return false }
191 return name.unicodeScalars.allSatisfy { $0.isASCII && (CharacterSet.alphanumerics.contains($0) || $0 == "_" || $0 == "$") }
192 }
193}