public import Foundation public struct ActivityStore: Sendable { public enum Failure: Error, Equatable { case unsupportedVersion(Int) case invalidData case invalidFile } private struct Envelope: Codable { let version: Int let activity: ActivityLedger } public static let currentVersion = 1 public let fileURL: URL public init(fileURL: URL) { self.fileURL = fileURL } public func load() throws -> ActivityLedger { guard try exists() else { return ActivityLedger() } let envelope = try JSONDecoder().decode(Envelope.self, from: Data(contentsOf: fileURL)) guard envelope.version == Self.currentVersion else { throw Failure.unsupportedVersion(envelope.version) } try envelope.activity.validate() return envelope.activity } public func save(_ activity: ActivityLedger) throws { try activity.validate() _ = try load() let directory = fileURL.deletingLastPathComponent() try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys] let data = try encoder.encode(Envelope(version: Self.currentVersion, activity: activity)) try data.write(to: fileURL, options: .atomic) try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fileURL.path) } public func reset() throws { guard try exists() else { return } try FileManager.default.removeItem(at: fileURL) } private func exists() throws -> Bool { guard fileURL.isFileURL, !fileURL.lastPathComponent.isEmpty else { throw Failure.invalidFile } do { var currentURL = fileURL currentURL.removeAllCachedResourceValues() let values = try currentURL.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]) guard values.isRegularFile == true, values.isSymbolicLink != true else { throw Failure.invalidFile } return true } catch let error as CocoaError where error.code == .fileReadNoSuchFile { return false } } }