SPB Git

Repository Public

Stores.swift 8.6 KB 182 lines swift

1import Foundation2import SettingsModel3import WorkspaceKit45/// A named command template. `{{name}}` placeholders are filled in before the command is6/// *shown for review*; nothing in this module ever executes a snippet.7public struct Snippet: Codable, Sendable, Hashable, Identifiable {8    public var id: UUID9    public var name: String10    public var template: String11    public var note: String12    public var isFavorite: Bool1314    public init(id: UUID = UUID(), name: String, template: String, note: String = "", isFavorite: Bool = false) {15        self.id = id; self.name = name; self.template = template; self.note = note; self.isFavorite = isFavorite16    }1718    /// Placeholder names in order of first appearance. `{{name}}` or `{{name:default}}`.19    public var variables: [SnippetVariable] {20        var seen = Set<String>()21        var result: [SnippetVariable] = []22        for match in template.matches(of: Snippet.placeholder) {23            let name = String(match.output.1)24            guard seen.insert(name).inserted else { continue }25            result.append(SnippetVariable(name: name, defaultValue: match.output.2.map(String.init) ?? ""))26        }27        return result28    }2930    nonisolated(unsafe) static let placeholder = /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?::([^}]*))?\}\}/3132    /// Substitutes the placeholders. Values are inserted single-quoted for the shell unless33    /// `quoteValues` is false. A placeholder without a value keeps its default.34    public func render(_ values: [String: String], quoteValues: Bool = true) -> String {35        template.replacing(Snippet.placeholder) { match in36            let name = String(match.output.1)37            let value = values[name] ?? match.output.2.map(String.init) ?? ""38            return quoteValues ? Snippet.shellQuoted(value) : value39        }40    }4142    /// POSIX single-quote escaping; plain words are left bare for readability.43    public static func shellQuoted(_ value: String) -> String {44        if !value.isEmpty, value.unicodeScalars.allSatisfy({ safeScalars.contains($0) }) { return value }45        return "'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'"46    }47    static let safeScalars = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-./:@%+=,")48}4950public struct SnippetVariable: Sendable, Hashable {51    public var name: String52    public var defaultValue: String53}5455/// One line of the opt-in command history.56public struct HistoryEntry: Codable, Sendable, Hashable {57    public var date: Date58    public var command: String59    public var directory: String?60    public var host: String?61    /// Where the command came from: `snippet`, `assistant`, `broadcast`, `palette`.62    public var source: String6364    public init(date: Date = Date(), command: String, directory: String? = nil, host: String? = nil, source: String) {65        self.date = date; self.command = command; self.directory = directory; self.host = host; self.source = source66    }67}6869/// Append-only, bounded, owner-only command history. Writing is refused unless the caller70/// passes the user's opt-in (`enabled`) and private mode is off.71public struct HistoryStore: Sendable {72    public let url: URL73    public let maximumEntries: Int7475    public init(url: URL, maximumEntries: Int = 5000) {76        self.url = url77        self.maximumEntries = maximumEntries78    }7980    /// Returns `true` when the entry was written.81    @discardableResult82    public func append(_ entry: HistoryEntry, enabled: Bool, privateMode: Bool,83                       redact: (String) -> String = { $0 }) -> Bool {84        guard enabled, !privateMode else { return false }85        var safe = entry86        safe.command = redact(entry.command)87        let encoder = JSONEncoder()88        encoder.dateEncodingStrategy = .iso860189        guard var line = try? encoder.encode(safe) else { return false }90        line.append(0x0a)91        if !FileManager.default.fileExists(atPath: url.path) {92            try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true,93                                                     attributes: [.posixPermissions: 0o700])94            guard FileManager.default.createFile(atPath: url.path, contents: nil, attributes: [.posixPermissions: 0o600]) else { return false }95        }96        guard let handle = try? FileHandle(forWritingTo: url) else { return false }97        defer { try? handle.close() }98        _ = try? handle.seekToEnd()99        do { try handle.write(contentsOf: line) } catch { return false }100        trimIfNeeded()101        return true102    }103104    public func entries() -> [HistoryEntry] {105        guard let data = try? Data(contentsOf: url) else { return [] }106        let decoder = JSONDecoder()107        decoder.dateDecodingStrategy = .iso8601108        return data.split(separator: 0x0a).compactMap { try? decoder.decode(HistoryEntry.self, from: Data($0)) }109    }110111    public func search(_ query: String) -> [HistoryEntry] {112        guard !query.isEmpty else { return entries() }113        return entries().filter { $0.command.localizedCaseInsensitiveContains(query) }114    }115116    public func clear() { try? FileManager.default.removeItem(at: url) }117118    private func trimIfNeeded() {119        guard let data = try? Data(contentsOf: url) else { return }120        let lines = data.split(separator: 0x0a)121        guard lines.count > maximumEntries + maximumEntries / 10 else { return }122        var kept = Data()123        for line in lines.suffix(maximumEntries) { kept.append(contentsOf: line); kept.append(0x0a) }124        let temp = url.deletingLastPathComponent().appendingPathComponent(".history.\(UUID().uuidString).tmp")125        guard FileManager.default.createFile(atPath: temp.path, contents: kept, attributes: [.posixPermissions: 0o600]) else { return }126        _ = try? FileManager.default.replaceItemAt(url, withItemAt: temp)127    }128}129130/// The app's persistent state, one versioned file per concern.131public struct SessionStores: Sendable {132    public let locations: StoreLocations133    public let settings: VersionedStore<AppSettings>134    /// Layout autosaved while the app runs; restored at next launch (also after a crash).135    public let lastSession: VersionedStore<WorkspaceSnapshot>136    /// Workspaces the user saved by name.137    public let workspaces: VersionedStore<[WorkspaceSnapshot]>138    public let snippets: VersionedStore<[Snippet]>139    public let history: HistoryStore140141    public init(locations: StoreLocations) {142        self.locations = locations143        settings = VersionedStore(url: locations.settings, currentVersion: 1)144        // v1 stored a bare array of windows; v2 wraps them in a named snapshot.145        lastSession = VersionedStore(url: locations.lastSession, currentVersion: 2, migrations: [1: Self.wrapWindowsIntoSnapshot])146        workspaces = VersionedStore(url: locations.workspaces, currentVersion: 1)147        snippets = VersionedStore(url: locations.snippets, currentVersion: 1)148        history = HistoryStore(url: locations.history)149    }150151    static let wrapWindowsIntoSnapshot: VersionedStore<WorkspaceSnapshot>.Migration = { payload in152        guard let windows = payload as? [Any] else { throw CocoaError(.fileReadCorruptFile) }153        return ["id": UUID().uuidString, "name": "Last Session", "windows": windows,154                "savedAt": ISO8601DateFormatter().string(from: Date())] as [String: Any]155    }156157    /// Loads a workspace and repairs every tab so that a partially damaged file still opens.158    public func loadLastSession() -> WorkspaceSnapshot? {159        guard var snapshot = lastSession.load().value else { return nil }160        snapshot.windows = snapshot.windows.compactMap { window in161            var w = window162            w.tabs = window.tabs.compactMap { tab in163                var t = tab164                t.repair()165                return t.isEmpty ? nil : t166            }167            if w.tabs.isEmpty { return nil }168            if !w.tabs.contains(where: { $0.id == w.selectedTab }) { w.selectedTab = w.tabs.first?.id }169            return w170        }171        return snapshot.windows.isEmpty ? nil : snapshot172    }173174    public static let starterSnippets: [Snippet] = [175        Snippet(name: "Find large files", template: "find {{path:.}} -type f -size +{{size:100M}} -exec ls -lh {} +", note: "Lists files above a size."),176        Snippet(name: "Git log graph", template: "git log --oneline --graph --decorate -n {{count:30}}"),177        Snippet(name: "Listening ports", template: "lsof -nP -iTCP -sTCP:LISTEN"),178        Snippet(name: "Tail a log", template: "tail -n {{lines:200}} -f {{file}}"),179        Snippet(name: "Disk usage by folder", template: "du -sh {{path:.}}/* | sort -h"),180    ]181}182
Files main
Menu

Theme