Sources/OrgCore/Commands/UserCommands.swift

61025559a3989ea7536dda296a9e27ddc7909aac
orgstar/Sources/OrgCore/Commands/UserCommands.swift

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