SPB Git

Repository Public

VersionedStore.swift 6.1 KB 131 lines swift

1import Foundation23/// Where SP Term keeps its files. Everything lives under one directory (0700) that can be4/// redirected for tests or isolated runs (`-SPTermDataDir`).5public struct StoreLocations: Sendable, Equatable {6    public let root: URL78    public init(root: URL) { self.root = root }910    /// `~/Library/Application Support/SP Term`.11    public static func standard() -> StoreLocations {12        let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first13            ?? URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Application Support")14        return StoreLocations(root: base.appendingPathComponent("SP Term", isDirectory: true))15    }1617    public var settings: URL { root.appendingPathComponent("settings.json") }18    public var lastSession: URL { root.appendingPathComponent("last-session.json") }19    public var workspaces: URL { root.appendingPathComponent("workspaces.json") }20    public var snippets: URL { root.appendingPathComponent("snippets.json") }21    public var hosts: URL { root.appendingPathComponent("hosts.json") }22    public var providers: URL { root.appendingPathComponent("ai-providers.json") }23    public var history: URL { root.appendingPathComponent("history.jsonl") }2425    /// Creates the directory, owner-only.26    public func prepare() throws {27        try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true,28                                                attributes: [.posixPermissions: 0o700])29        try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: root.path)30    }31}3233public enum StoreError: Error, Equatable {34    /// The file was written by a newer build than this one understands.35    case newerSchema(found: Int, supported: Int)36    case missingMigration(from: Int)37}3839/// Result of loading a versioned file.40public enum LoadOutcome<Value: Sendable>: Sendable {41    case loaded(Value)42    /// No file yet.43    case missing44    /// The file could not be read; it was moved aside to `backup` and defaults should be used.45    case recovered(backup: URL?, reason: String)4647    public var value: Value? { if case .loaded(let v) = self { return v } else { return nil } }48}4950/// A JSON file with an explicit schema version, atomic owner-only writes, step-by-step51/// migrations and crash/corruption recovery (a bad file is set aside, never silently deleted).52///53/// On-disk format: `{"schemaVersion": N, "payload": …}`.54public struct VersionedStore<Value: Codable & Sendable>: Sendable {55    /// Transforms the JSON payload of version `n` into version `n + 1`.56    public typealias Migration = @Sendable (Any) throws -> Any5758    public let url: URL59    public let currentVersion: Int60    private let migrations: [Int: Migration]6162    public init(url: URL, currentVersion: Int, migrations: [Int: Migration] = [:]) {63        self.url = url64        self.currentVersion = currentVersion65        self.migrations = migrations66    }6768    public func load() -> LoadOutcome<Value> {69        guard FileManager.default.fileExists(atPath: url.path) else { return .missing }70        do {71            let data = try Data(contentsOf: url)72            guard let envelope = try JSONSerialization.jsonObject(with: data) as? [String: Any],73                  var version = envelope["schemaVersion"] as? Int, var payload = envelope["payload"] else {74                throw CocoaError(.fileReadCorruptFile)75            }76            guard version <= currentVersion else { throw StoreError.newerSchema(found: version, supported: currentVersion) }77            while version < currentVersion {78                guard let migrate = migrations[version] else { throw StoreError.missingMigration(from: version) }79                payload = try migrate(payload)80                version += 181            }82            let payloadData = try JSONSerialization.data(withJSONObject: payload, options: [.fragmentsAllowed])83            return .loaded(try Self.decoder.decode(Value.self, from: payloadData))84        } catch {85            return .recovered(backup: setAside(), reason: String(describing: error))86        }87    }8889    public func save(_ value: Value) throws {90        let payload = try JSONSerialization.jsonObject(with: Self.encoder.encode(value), options: [.fragmentsAllowed])91        let envelope: [String: Any] = ["schemaVersion": currentVersion, "payload": payload]92        let data = try JSONSerialization.data(withJSONObject: envelope, options: [.prettyPrinted, .sortedKeys])93        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true,94                                                attributes: [.posixPermissions: 0o700])95        // Write to a sibling temp file (0600 from the start) and rename over the target:96        // a crash mid-write leaves the previous file intact.97        let temp = url.deletingLastPathComponent().appendingPathComponent(".\(url.lastPathComponent).\(UUID().uuidString).tmp")98        guard FileManager.default.createFile(atPath: temp.path, contents: data, attributes: [.posixPermissions: 0o600]) else {99            throw CocoaError(.fileWriteUnknown)100        }101        do {102            _ = try FileManager.default.replaceItemAt(url, withItemAt: temp)103            try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)104        } catch {105            try? FileManager.default.removeItem(at: temp)106            throw error107        }108    }109110    public func delete() {111        try? FileManager.default.removeItem(at: url)112    }113114    private func setAside() -> URL? {115        let stamp = Int(Date().timeIntervalSince1970)116        let backup = url.deletingLastPathComponent().appendingPathComponent("\(url.lastPathComponent).unreadable-\(stamp)")117        do { try FileManager.default.moveItem(at: url, to: backup); return backup } catch { return nil }118    }119120    static var encoder: JSONEncoder {121        let e = JSONEncoder()122        e.dateEncodingStrategy = .iso8601123        return e124    }125    static var decoder: JSONDecoder {126        let d = JSONDecoder()127        d.dateDecodingStrategy = .iso8601128        return d129    }130}131
Files main
Menu

Theme