Sources/OrgDocument/Saving.swift

124 lines · 6162 bytes

  1import Foundation
  2import OrgCore
  3
  4public protocol FileSystem: Sendable {
  5    /// The file's bytes, or nil if it doesn't exist.
  6    func read(_ url: URL) throws -> [UInt8]?
  7    /// Replaces the file through a temporary file in the same folder. Returns the bytes that
  8    /// were replaced, read from the replaced file itself, or nil if there was none.
  9    func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]?
 10}
 11
 12public protocol RecoveryStore: Sendable {
 13    func keep(_ bytes: [UInt8], for url: URL, label: String) throws
 14    /// Offered the version a save is about to replace, to keep now and then as a snapshot.
 15    func keepSnapshot(_ bytes: [UInt8], for url: URL) throws
 16}
 17
 18extension RecoveryStore {
 19    public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {}
 20}
 21
 22public enum SaveOutcome: Sendable, Equatable {
 23    case saved
 24    /// The file had changed since it was read; the change merged cleanly into the buffer and
 25    /// the merge was written.
 26    case mergedAndSaved([TextEdit])
 27    /// The file had changed and the change conflicts. Nothing was written; the buffer is
 28    /// unchanged.
 29    case conflict([MergeConflict])
 30    /// Another writer replaced the file between our last check and our write. Ours is on disk;
 31    /// theirs is in recovery and was merged into the buffer where possible.
 32    case overwroteExternalChange(DocumentState.ExternalChange)
 33    /// Another writer changed the file right after our write. Theirs is on disk; ours is in
 34    /// recovery.
 35    case changedAfterWrite(DocumentState.ExternalChange)
 36}
 37
 38public enum SaveError: Error, Equatable {
 39    case fileKeepsChanging
 40}
 41
 42/// The save sequence from the design: read, merge if the file moved, check again, replace,
 43/// read back. Emacs and Syncthing don't coordinate, so the sequence can't lock them out; it
 44/// narrows the window and makes sure every version it displaces lands in recovery.
 45public struct Saver: Sendable {
 46    public let fileSystem: FileSystem
 47    public let recovery: RecoveryStore
 48    public var maxAttempts = 3
 49
 50    public init(fileSystem: FileSystem, recovery: RecoveryStore) {
 51        self.fileSystem = fileSystem
 52        self.recovery = recovery
 53    }
 54
 55    public func save(_ state: inout DocumentState, to url: URL) throws -> SaveOutcome {
 56        guard state.isEditable else { throw DocumentState.EditError.readOnly }
 57        for _ in 0..<maxAttempts {
 58            let disk = try fileSystem.read(url)
 59            var merged: [TextEdit]?
 60            if let disk, disk != state.mergeBase {
 61                try recovery.keep(disk, for: url, label: "external")
 62                try recovery.keep(state.encodedText(), for: url, label: "local")
 63                switch state.diskChanged(to: disk) {
 64                case .conflict(let conflicts): return .conflict(conflicts)
 65                case .merged(let edits), .reloaded(let edits): merged = edits
 66                case .unchanged: break
 67                }
 68            }
 69            let bytes = try state.encodedText()
 70            guard try fileSystem.read(url) == disk else { continue }
 71            // A snapshot is a convenience: one that can't be kept doesn't stop the save.
 72            if let disk, disk != bytes { try? recovery.keepSnapshot(disk, for: url) }
 73
 74            let replaced = try fileSystem.replace(url, with: bytes)
 75            state.didWrite(bytes)
 76            if replaced != disk, let replaced {
 77                return .overwroteExternalChange(keepOverwritten(replaced, base: disk ?? [], in: &state, url: url))
 78            }
 79
 80            if let after = try fileSystem.read(url), after != bytes {
 81                // Ours is in the buffer whether or not a copy can be kept.
 82                try? recovery.keep(bytes, for: url, label: "local")
 83                return .changedAfterWrite(state.diskChanged(to: after))
 84            }
 85            return merged.map { .mergedAndSaved($0) } ?? .saved
 86        }
 87        throw SaveError.fileKeepsChanging
 88    }
 89
 90    /// Writes the buffer over whatever is on disk, for keeping our version over a conflicting
 91    /// one. The replaced version goes to recovery unless it is the merge base.
 92    public func overwrite(_ state: inout DocumentState, to url: URL) throws {
 93        let bytes = try state.encodedText()
 94        // The version Keep Mine replaces goes to recovery first; when it can't, nothing is written.
 95        let disk = try fileSystem.read(url)
 96        if let disk, disk != state.mergeBase { try recovery.keep(disk, for: url, label: "external") }
 97        let base = state.mergeBase
 98        let replaced = try fileSystem.replace(url, with: bytes)
 99        state.didWrite(bytes)
100        if let replaced, replaced != disk, replaced != base {
101            _ = keepOverwritten(replaced, base: base, in: &state, url: url, merge: false)
102        }
103    }
104
105    /// `replaced`, a version another writer put on disk just before ours replaced it, kept: in
106    /// recovery and, when `merge`, merged into the buffer. When recovery can't keep it (it holds
107    /// text that can only be kept encrypted, without a passphrase) and it isn't merged, it goes
108    /// into the buffer beside ours between conflict markers, so it's never lost.
109    func keepOverwritten(_ replaced: [UInt8], base: [UInt8], in state: inout DocumentState, url: URL, merge: Bool = true) -> DocumentState.ExternalChange {
110        let change: DocumentState.ExternalChange = merge ? state.mergeOverwritten(replaced, base: base) : .conflict([])
111        do {
112            try recovery.keep(replaced, for: url, label: "external")
113            return merge ? change : .unchanged
114        } catch {
115            if case .merged = change { return change }
116            let theirs = SourceText(bytes: replaced).text
117            let both = mergeWithMarkers(base: SourceText(bytes: base).text, ours: state.text, theirs: theirs, oursLabel: "yours", theirsLabel: "disk")
118            let edits = lineEdits(from: state.text, to: both)
119            guard (try? state.apply(edits, baseRevision: state.revision)) != nil else { return change }
120            // A conflict with none listed: both versions are in the buffer between markers.
121            return .conflict([])
122        }
123    }
124}
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