Sources/OrgApp/UserCommandFile.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Sources/OrgApp/UserCommandFile.swift

207 lines · 10665 bytes

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