Sources/OrgApp/UserCommandFile.swift

b6a348930a231ab1ffd793a69f2d512f8b60bad8
orgstar/Sources/OrgApp/UserCommandFile.swift

262 lines · 14051 bytes

  1import Foundation
  2import OrgCore
  3
  4/// `commands.toml` in the configuration folder and the modules in `commands/` beside it.
  5public enum UserCommandFile {
  6    /// Reads `commands.toml` in `folder` into `store`, without running anything. The problems
  7    /// found, each starting with the file's name; a missing file is none. A module iCloud hasn't
  8    /// downloaded is reported and its download started; its command or hook is kept.
  9    @discardableResult
 10    public static func load(into store: UserCommands = .shared, folder: URL, read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }) -> [String] {
 11        let modules = folder.appendingPathComponent(UserCommands.folderName)
 12        guard let text = read(folder.appendingPathComponent(UserCommands.fileName)) else {
 13            store.replace([], folder: nil)
 14            return []
 15        }
 16        var problems: [String] = []
 17        var commands: [UserCommand] = []
 18        var hooks: [UserHook] = []
 19        do {
 20            (commands, hooks) = try UserCommands.manifest(text, problems: &problems) { path in
 21                FileManager.default.fileExists(atPath: modules.appendingPathComponent(path).path) || placeholder(modules.appendingPathComponent(path)) != nil
 22            }
 23        } catch {
 24            problems.append("\(error)")
 25        }
 26        for file in Set(commands.map(\.file) + hooks.map(\.file)).sorted() where needsDownload(modules.appendingPathComponent(file)) {
 27            problems.append("\(UserCommands.folderName)/\(file) isn't downloaded from iCloud yet")
 28        }
 29        store.replace(commands, hooks: hooks, folder: commands.isEmpty && hooks.isEmpty ? nil : modules)
 30        return problems.map { "\(UserCommands.fileName): \($0)" }
 31    }
 32
 33    /// The `.name.icloud` file iCloud leaves for `url` until it is downloaded, when there is one.
 34    static func placeholder(_ url: URL) -> URL? {
 35        let placeholder = url.deletingLastPathComponent().appendingPathComponent("." + url.lastPathComponent + ".icloud")
 36        return FileManager.default.fileExists(atPath: placeholder.path) ? placeholder : nil
 37    }
 38
 39    /// Whether `url` is in iCloud and not downloaded; if so its download is started.
 40    static func needsDownload(_ url: URL) -> Bool {
 41        let values = try? url.resourceValues(forKeys: [.isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey])
 42        let missing = placeholder(url) != nil
 43            || values?.isUbiquitousItem == true && values?.ubiquitousItemDownloadingStatus.map { $0 != .current } == true
 44        if missing { try? FileManager.default.startDownloadingUbiquitousItem(at: url) }
 45        return missing
 46    }
 47
 48    /// `path` relative to the folder of `roots` it's in, for `org.file()`; its name when it's
 49    /// in none.
 50    public static func relativePath(_ path: String, roots: [String]) -> String {
 51        let root = roots.filter { path.hasPrefix($0.hasSuffix("/") ? $0 : $0 + "/") }.max { $0.count < $1.count }
 52        guard let root else { return (path as NSString).lastPathComponent }
 53        return String(path.dropFirst(root.count).drop { $0 == "/" })
 54    }
 55
 56    // MARK: - Trust
 57
 58    /// The text trust is kept for: `file` and every module it imports, each under its path, in
 59    /// path order. Nil when `file` can't be read.
 60    @MainActor
 61    public static func trustedText(_ file: String, modules: URL) -> String? {
 62        moduleTexts(file, modules: modules).map(trustedText)
 63    }
 64
 65    static func trustedText(_ texts: [String: String?]) -> String {
 66        texts.keys.sorted().map { "// \($0)\n\(texts[$0]! ?? "(missing)")" }.joined(separator: "\n")
 67    }
 68
 69    /// `file` and every module it imports, directly or through another, by path in `modules`;
 70    /// nil for an import that can't be read. Nil when `file` can't be read.
 71    @MainActor
 72    static func moduleTexts(_ file: String, modules: URL) -> [String: String?]? {
 73        var seen: [String: String?] = [:]
 74        var pending = [file]
 75        while let path = pending.popLast() {
 76            guard !seen.keys.contains(path) else { continue }
 77            #if canImport(WebKit)
 78            let data = CommandHost.Files.file(path, in: modules)
 79            #else
 80            let data = FileManager.default.contents(atPath: modules.appendingPathComponent(path).path)
 81            #endif
 82            guard let data, let text = String(data: data, encoding: .utf8) else {
 83                if path == file { return nil }
 84                seen[path] = .some(nil)
 85                continue
 86            }
 87            seen[path] = text
 88            pending += imports(text, from: path)
 89        }
 90        return seen
 91    }
 92
 93    private static let importPatterns = [
 94        #"\b(?:import|export)\s[^;'"]*?\bfrom\s*['"]([^'"\n]+)['"]"#,
 95        #"\bimport\s*['"]([^'"\n]+)['"]"#,
 96        #"\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)"#,
 97    ].map { try! NSRegularExpression(pattern: $0) }
 98
 99    /// The modules `text`, at `path` in `commands/`, imports by relative path, as paths in
100    /// `commands/`; imports that leave the folder are left out, since they can't load.
101    static func imports(_ text: String, from path: String) -> [String] {
102        let ns = text as NSString
103        var result: [String] = []
104        for pattern in importPatterns {
105            for match in pattern.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
106                let specifier = ns.substring(with: match.range(at: 1))
107                guard specifier.hasPrefix("./") || specifier.hasPrefix("../") else { continue }
108                var parts = path.split(separator: "/").dropLast().map(String.init)
109                var inside = true
110                for part in specifier.split(separator: "/") {
111                    switch part {
112                    case ".": continue
113                    case "..": if parts.popLast() == nil { inside = false }
114                    default: parts.append(String(part))
115                    }
116                }
117                let resolved = parts.joined(separator: "/")
118                if inside, UserCommands.isModulePath(resolved) { result.append(resolved) }
119            }
120        }
121        return result
122    }
123}
124
125/// The question before a command from a file this device hasn't trusted runs.
126@MainActor
127public enum UserCommandTrust {
128    public enum Answer: CaseIterable, Sendable {
129        case runOnce, always, dontRun
130
131        public var title: String {
132            switch self {
133            case .runOnce: String(localized: "Run Once", comment: "Answer to the question before a user command runs")
134            case .always: String(localized: "Always", comment: "Answer to the question before a user command runs")
135            case .dontRun: String(localized: "Don't Run", comment: "Answer to the question before a user command runs")
136            }
137        }
138    }
139
140    /// Put before the trusted text of a file trusted for commands with `workspace = true`. The
141    /// trusted text itself always starts with `// `, so no buffer-only text can match.
142    static let workspaceTrust = "\u{0}workspace\n"
143
144    public struct Question: Equatable, Sendable {
145        /// The command's file, as `commands/review.js`.
146        public let file: String
147        /// The modules it imports, directly or through another, as `commands/lib/dates.js`, in
148        /// path order. Trust covers them with the file.
149        public let imports: [String]
150        /// Its commands can also read every file in the folders and capture to them.
151        public let workspace: Bool
152        /// Asked for a hook on this event rather than a command.
153        public let hook: UserHook.Event?
154
155        public init(file: String, imports: [String] = [], workspace: Bool = false, hook: UserHook.Event? = nil) {
156            self.file = file
157            self.imports = imports
158            self.workspace = workspace
159            self.hook = hook
160        }
161
162        public var title: String {
163            hook == nil
164                ? String(localized: "Run commands from \(file)?", comment: "Asked before a user command from a file not yet trusted on this device runs")
165                : String(localized: "Run hooks from \(file)?", comment: "Asked before a user hook from a file not yet trusted on this device runs")
166        }
167
168        /// When the hook runs, the modules it imports, if any, and what its commands can do, a
169        /// line each.
170        public var message: String {
171            var lines: [String] = []
172            switch hook {
173            case .afterTodoStateChange?:
174                lines.append(String(localized: "This hook runs after you change an entry's TODO state.",
175                                    comment: "When an after-todo-state-change hook runs, in the question before it runs"))
176            case .captureBeforeFinalize?:
177                lines.append(String(localized: "This hook runs before a capture is filed and can change or cancel it.",
178                                    comment: "When a capture-before-finalize hook runs, in the question before it runs"))
179            case nil: break
180            }
181            if !imports.isEmpty {
182                let list = ListFormatter.localizedString(byJoining: imports)
183                lines.append(String(localized: "It imports \(list).", comment: "The modules a user command's file imports, in the question before it runs"))
184            }
185            lines.append(workspace
186                ? String(localized: "They can read and change the file you run them in, read every file in your folders and capture to them, but not use the network.",
187                         comment: "What user commands with access to the folders can do, in the question before they run")
188                : String(localized: "They can read and change the file you run them in, and nothing else: no other files and no network.",
189                         comment: "What user commands can do, in the question before they run"))
190            return lines.joined(separator: "\n")
191        }
192    }
193
194    /// Runs `run` at once when the command's file and its imports are trusted, else asks: Run
195    /// Once runs it, Always trusts the files as they are now and runs it, anything else says
196    /// why nothing ran through `refuse`. Trust for commands with `workspace = true` is kept
197    /// apart: it covers the file's other commands too, but trust given without it doesn't
198    /// cover them.
199    public static func check(_ command: UserCommand, modules: URL, trust: TrustStore,
200                             ask: @MainActor (Question, @escaping (Answer?) -> Void) -> Void,
201                             run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
202        check(file: command.file, workspace: command.workspace, modules: modules, trust: trust, ask: ask, run: run, refuse: refuse)
203    }
204
205    /// `check` for a hook: the same trust as its file's commands. Without `ask`, a hook from a
206    /// file not trusted here is refused.
207    public static func check(_ hook: UserHook, modules: URL, trust: TrustStore,
208                             ask: (@MainActor (Question, @escaping (Answer?) -> Void) -> Void)?,
209                             run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
210        let shown = "\(UserCommands.folderName)/\(hook.file)"
211        check(file: hook.file, workspace: hook.workspace, hook: hook.event, modules: modules, trust: trust, ask: ask ?? { _, _ in
212            refuse(String(localized: "\(shown) isn't trusted on this device yet, and orgstar can't ask here.",
213                          comment: "A hook from a file not yet trusted, skipped where orgstar can't ask, as for a capture from Shortcuts"))
214        }, run: run, refuse: refuse)
215    }
216
217    private static func check(file: String, workspace: Bool, hook: UserHook.Event? = nil, modules: URL, trust: TrustStore,
218                              ask: @MainActor (Question, @escaping (Answer?) -> Void) -> Void,
219                              run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
220        guard let texts = UserCommandFile.moduleTexts(file, modules: modules) else {
221            return refuse("No file \(UserCommands.folderName)/\(file)")
222        }
223        let text = UserCommandFile.trustedText(texts)
224        let path = modules.appendingPathComponent(file).path
225        let workspaceText = workspaceTrust + text
226        let accepted = workspace ? [workspaceText] : [text, workspaceText]
227        if accepted.contains(where: { trust.isTrusted(path: path, content: $0) }) { return run() }
228        let imports = texts.filter { $0.key != file && $0.value != nil }.keys.sorted()
229        let question = Question(file: "\(UserCommands.folderName)/\(file)",
230                                imports: imports.map { "\(UserCommands.folderName)/\($0)" }, workspace: workspace, hook: hook)
231        ask(question) { answer in
232            switch answer {
233            case .runOnce: run()
234            case .always:
235                trust.trust(path: path, content: accepted[0])
236                run()
237            case .dontRun, nil: refuse(String(localized: "Not run"))
238            }
239        }
240    }
241}
242
243/// What hooks need from the app: the trust kept for their files, the question for a file not yet
244/// trusted where the app can ask, where their messages go, and the folders for hooks with
245/// `workspace = true`.
246@MainActor
247public struct UserHookHost {
248    public var trust: TrustStore
249    /// Nil where the app can't ask; a hook from a file not trusted here is then skipped with a
250    /// message.
251    public var ask: (@MainActor (UserCommandTrust.Question, @escaping (UserCommandTrust.Answer?) -> Void) -> Void)?
252    public var report: @MainActor (String) -> Void
253    public var workspace: UserCommandWorkspace?
254
255    public init(trust: TrustStore, ask: (@MainActor (UserCommandTrust.Question, @escaping (UserCommandTrust.Answer?) -> Void) -> Void)?,
256                report: @escaping @MainActor (String) -> Void, workspace: UserCommandWorkspace? = nil) {
257        self.trust = trust
258        self.ask = ask
259        self.report = report
260        self.workspace = workspace
261    }
262}
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