Sources/OrgDocument/Saving.swift

8f2ce3e9aea5e545a257dab3e7600f258daab10b
orgstar/Sources/OrgDocument/Saving.swift

140 lines · 7059 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    /// Another writer's version, replaced by ours and not kept, was put back; ours isn't on disk.
 41    case otherVersionRestored
 42}
 43
 44/// The save sequence from the design: read, merge if the file moved, check again, replace,
 45/// read back. Emacs and Syncthing don't coordinate, so the sequence can't lock them out; it
 46/// narrows the window and makes sure every version it displaces lands in recovery.
 47public struct Saver: Sendable {
 48    public let fileSystem: FileSystem
 49    public let recovery: RecoveryStore
 50    public var maxAttempts = 3
 51    /// For a state that's thrown away after the save (a file that isn't open): puts back, as it
 52    /// was, the version another writer had on disk just before ours replaced it. Set, a version
 53    /// that recovery can't keep is restored and the save throws `otherVersionRestored`, rather
 54    /// than merged into the state.
 55    public var restoreOverwritten: (@Sendable (URL) throws -> Void)?
 56
 57    public init(fileSystem: FileSystem, recovery: RecoveryStore) {
 58        self.fileSystem = fileSystem
 59        self.recovery = recovery
 60    }
 61
 62    public func save(_ state: inout DocumentState, to url: URL) throws -> SaveOutcome {
 63        guard state.isEditable else { throw DocumentState.EditError.readOnly }
 64        for _ in 0..<maxAttempts {
 65            let disk = try fileSystem.read(url)
 66            var merged: [TextEdit]?
 67            if let disk, disk != state.mergeBase {
 68                try recovery.keep(disk, for: url, label: "external")
 69                try recovery.keep(state.encodedText(), for: url, label: "local")
 70                switch state.diskChanged(to: disk) {
 71                case .conflict(let conflicts): return .conflict(conflicts)
 72                case .merged(let edits), .reloaded(let edits): merged = edits
 73                case .unchanged: break
 74                }
 75            }
 76            let bytes = try state.encodedText()
 77            guard try fileSystem.read(url) == disk else { continue }
 78            // A snapshot is a convenience: one that can't be kept doesn't stop the save.
 79            if let disk, disk != bytes { try? recovery.keepSnapshot(disk, for: url) }
 80
 81            let replaced = try fileSystem.replace(url, with: bytes)
 82            state.didWrite(bytes)
 83            if replaced != disk, let replaced {
 84                return .overwroteExternalChange(try keepOverwritten(replaced, base: disk ?? [], in: &state, url: url))
 85            }
 86
 87            if let after = try fileSystem.read(url), after != bytes {
 88                // Ours is in the buffer whether or not a copy can be kept.
 89                try? recovery.keep(bytes, for: url, label: "local")
 90                return .changedAfterWrite(state.diskChanged(to: after))
 91            }
 92            return merged.map { .mergedAndSaved($0) } ?? .saved
 93        }
 94        throw SaveError.fileKeepsChanging
 95    }
 96
 97    /// Writes the buffer over whatever is on disk, for keeping our version over a conflicting
 98    /// one. The replaced version goes to recovery unless it is the merge base.
 99    public func overwrite(_ state: inout DocumentState, to url: URL) throws {
100        let bytes = try state.encodedText()
101        // The version Keep Mine replaces goes to recovery first; when it can't, nothing is written.
102        let disk = try fileSystem.read(url)
103        if let disk, disk != state.mergeBase { try recovery.keep(disk, for: url, label: "external") }
104        let base = state.mergeBase
105        let replaced = try fileSystem.replace(url, with: bytes)
106        state.didWrite(bytes)
107        if let replaced, replaced != disk, replaced != base {
108            _ = try keepOverwritten(replaced, base: base, in: &state, url: url, merge: false)
109        }
110    }
111
112    /// `replaced`, a version another writer put on disk just before ours replaced it, kept: in
113    /// recovery and, when `merge`, merged into the buffer. When recovery can't keep it (it holds
114    /// text that can only be kept encrypted, without a passphrase) and it isn't merged, it goes
115    /// into the buffer beside ours between conflict markers, so it's never lost.
116    func keepOverwritten(_ replaced: [UInt8], base: [UInt8], in state: inout DocumentState, url: URL, merge: Bool = true) throws -> DocumentState.ExternalChange {
117        if let restoreOverwritten {
118            do {
119                try recovery.keep(replaced, for: url, label: "external")
120                return merge ? state.mergeOverwritten(replaced, base: base) : .unchanged
121            } catch {
122                try restoreOverwritten(url)
123                throw SaveError.otherVersionRestored
124            }
125        }
126        let change: DocumentState.ExternalChange = merge ? state.mergeOverwritten(replaced, base: base) : .conflict([])
127        do {
128            try recovery.keep(replaced, for: url, label: "external")
129            return merge ? change : .unchanged
130        } catch {
131            if case .merged = change { return change }
132            let theirs = SourceText(bytes: replaced).text
133            let both = mergeWithMarkers(base: SourceText(bytes: base).text, ours: state.text, theirs: theirs, oursLabel: "yours", theirsLabel: "disk")
134            let edits = lineEdits(from: state.text, to: both)
135            guard (try? state.apply(edits, baseRevision: state.revision)) != nil else { return change }
136            // A conflict with none listed: both versions are in the buffer between markers.
137            return .conflict([])
138        }
139    }
140}
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