import Foundation import OrgCore public protocol FileSystem: Sendable { /// The file's bytes, or nil if it doesn't exist. func read(_ url: URL) throws -> [UInt8]? /// Replaces the file through a temporary file in the same folder. Returns the bytes that /// were replaced, read from the replaced file itself, or nil if there was none. func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? } public protocol RecoveryStore: Sendable { func keep(_ bytes: [UInt8], for url: URL, label: String) throws /// Offered the version a save is about to replace, to keep now and then as a snapshot. func keepSnapshot(_ bytes: [UInt8], for url: URL) throws } extension RecoveryStore { public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {} } public enum SaveOutcome: Sendable, Equatable { case saved /// The file had changed since it was read; the change merged cleanly into the buffer and /// the merge was written. case mergedAndSaved([TextEdit]) /// The file had changed and the change conflicts. Nothing was written; the buffer is /// unchanged. case conflict([MergeConflict]) /// Another writer replaced the file between our last check and our write. Ours is on disk; /// theirs is in recovery and was merged into the buffer where possible. case overwroteExternalChange(DocumentState.ExternalChange) /// Another writer changed the file right after our write. Theirs is on disk; ours is in /// recovery. case changedAfterWrite(DocumentState.ExternalChange) } public enum SaveError: Error, Equatable { case fileKeepsChanging /// Another writer's version, replaced by ours and not kept, was put back; ours isn't on disk. case otherVersionRestored } /// The save sequence from the design: read, merge if the file moved, check again, replace, /// read back. Emacs and Syncthing don't coordinate, so the sequence can't lock them out; it /// narrows the window and makes sure every version it displaces lands in recovery. public struct Saver: Sendable { public let fileSystem: FileSystem public let recovery: RecoveryStore public var maxAttempts = 3 /// For a state that's thrown away after the save (a file that isn't open): puts back, as it /// was, the version another writer had on disk just before ours replaced it. Set, a version /// that recovery can't keep is restored and the save throws `otherVersionRestored`, rather /// than merged into the state. public var restoreOverwritten: (@Sendable (URL) throws -> Void)? public init(fileSystem: FileSystem, recovery: RecoveryStore) { self.fileSystem = fileSystem self.recovery = recovery } public func save(_ state: inout DocumentState, to url: URL) throws -> SaveOutcome { guard state.isEditable else { throw DocumentState.EditError.readOnly } for _ in 0.. DocumentState.ExternalChange { if let restoreOverwritten { do { try recovery.keep(replaced, for: url, label: "external") return merge ? state.mergeOverwritten(replaced, base: base) : .unchanged } catch { try restoreOverwritten(url) throw SaveError.otherVersionRestored } } let change: DocumentState.ExternalChange = merge ? state.mergeOverwritten(replaced, base: base) : .conflict([]) do { try recovery.keep(replaced, for: url, label: "external") return merge ? change : .unchanged } catch { if case .merged = change { return change } let theirs = SourceText(bytes: replaced).text let both = mergeWithMarkers(base: SourceText(bytes: base).text, ours: state.text, theirs: theirs, oursLabel: "yours", theirsLabel: "disk") let edits = lineEdits(from: state.text, to: both) guard (try? state.apply(edits, baseRevision: state.revision)) != nil else { return change } // A conflict with none listed: both versions are in the buffer between markers. return .conflict([]) } } }