Sources/OrgApp/UserCommandFile.swift

61025559a3989ea7536dda296a9e27ddc7909aac
orgstar/Sources/OrgApp/UserCommandFile.swift

145 lines · 7557 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 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        var seen: [String: String] = [:]
 62        var pending = [file]
 63        while let path = pending.popLast() {
 64            guard seen[path] == nil else { continue }
 65            #if canImport(WebKit)
 66            let data = CommandHost.Files.file(path, in: modules)
 67            #else
 68            let data = FileManager.default.contents(atPath: modules.appendingPathComponent(path).path)
 69            #endif
 70            guard let data, let text = String(data: data, encoding: .utf8) else {
 71                if path == file { return nil }
 72                seen[path] = "(missing)"
 73                continue
 74            }
 75            seen[path] = text
 76            pending += imports(text, from: path)
 77        }
 78        return seen.keys.sorted().map { "// \($0)\n\(seen[$0]!)" }.joined(separator: "\n")
 79    }
 80
 81    private static let importPatterns = [
 82        #"\b(?:import|export)\s[^;'"]*?\bfrom\s*['"]([^'"\n]+)['"]"#,
 83        #"\bimport\s*['"]([^'"\n]+)['"]"#,
 84        #"\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)"#,
 85    ].map { try! NSRegularExpression(pattern: $0) }
 86
 87    /// The modules `text`, at `path` in `commands/`, imports by relative path, as paths in
 88    /// `commands/`; imports that leave the folder are left out, since they can't load.
 89    static func imports(_ text: String, from path: String) -> [String] {
 90        let ns = text as NSString
 91        var result: [String] = []
 92        for pattern in importPatterns {
 93            for match in pattern.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
 94                let specifier = ns.substring(with: match.range(at: 1))
 95                guard specifier.hasPrefix("./") || specifier.hasPrefix("../") else { continue }
 96                var parts = path.split(separator: "/").dropLast().map(String.init)
 97                var inside = true
 98                for part in specifier.split(separator: "/") {
 99                    switch part {
100                    case ".": continue
101                    case "..": if parts.popLast() == nil { inside = false }
102                    default: parts.append(String(part))
103                    }
104                }
105                let resolved = parts.joined(separator: "/")
106                if inside, UserCommands.isModulePath(resolved) { result.append(resolved) }
107            }
108        }
109        return result
110    }
111}
112
113/// The question before a command from a file this device hasn't trusted runs.
114@MainActor
115public enum UserCommandTrust {
116    static var runOnce: String { String(localized: "Run Once", comment: "Answer to the question before a user command runs") }
117    static var always: String { String(localized: "Always", comment: "Answer to the question before a user command runs") }
118    static var dontRun: String { String(localized: "Don't Run", comment: "Answer to the question before a user command runs") }
119
120    /// Runs `run` at once when the command's file and its imports are trusted, else asks: Run
121    /// Once runs it, Always trusts the files as they are now and runs it, anything else says
122    /// why nothing ran through `refuse`.
123    public static func check(_ command: UserCommand, modules: URL, trust: TrustStore,
124                             ask: @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
125                             run: @escaping () -> Void, refuse: @escaping (String) -> Void) {
126        guard let text = UserCommandFile.trustedText(command.file, modules: modules) else {
127            return refuse("No file \(UserCommands.folderName)/\(command.file)")
128        }
129        let path = modules.appendingPathComponent(command.file).path
130        if trust.isTrusted(path: path, content: text) { return run() }
131        let choices = [runOnce, always, dontRun]
132        let file = "\(UserCommands.folderName)/\(command.file)"
133        let message = String(localized: "Run commands from \(file)?",
134                             comment: "Asked before a user command from a file not yet trusted on this device runs")
135        ask(Prompt(key: "confirm", message: message, choices: choices)) { answer in
136            switch answer {
137            case runOnce: run()
138            case always:
139                trust.trust(path: path, content: text)
140                run()
141            default: refuse(String(localized: "Not run"))
142            }
143        }
144    }
145}
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