Sources/OrgWorkspace/Reconciler.swift
116 lines · 5592 bytes
1import Foundation
2import OrgIndex
3
4public struct ReconcileReport: Sendable, Equatable {
5 public var indexed: [String] = []
6 public var touched: [String] = []
7 public var moved: [String] = []
8 public var removed: [String] = []
9 public var unchanged = 0
10 /// iCloud files asked to download; they are indexed once they arrive.
11 public var placeholders: [URL] = []
12}
13
14/// Brings the index in line with the files under a root. File events are only hints, so this
15/// is what runs at launch, after dropped events, and for every batch of changed paths.
16public struct Reconciler: Sendable {
17 public let index: IndexStore
18 public let settings: IndexSettings
19
20 public init(index: IndexStore, settings: IndexSettings) {
21 self.index = index
22 self.settings = settings
23 }
24
25 /// Reconciles the whole root.
26 public func reconcile(root: URL) throws -> ReconcileReport {
27 let discovery = try WorkspaceScanner.scan(root)
28 for placeholder in discovery.placeholders {
29 try? FileManager.default.startDownloadingUbiquitousItem(at: placeholder)
30 }
31 var report = try reconcile(root: root, found: discovery.files, known: index.fileStates(root: root.path))
32 report.placeholders = discovery.placeholders
33 return report
34 }
35
36 /// Reconciles only `paths` under the root, for a batch of file events.
37 public func reconcile(root: URL, paths: [URL]) throws -> ReconcileReport {
38 let wanted = Set(paths.map(\.standardizedFileURL.path))
39 let known = try index.fileStates(root: root.path).filter { wanted.contains($0.key) }
40 var found: [DiscoveredFile] = []
41 let rootComponents = root.standardizedFileURL.pathComponents.count
42 for url in paths.map(\.standardizedFileURL) {
43 // Files in hidden folders (`.git`) aren't part of the workspace, as in `scan`.
44 if url.pathComponents.dropFirst(rootComponents).dropLast().contains(where: { $0.hasPrefix(".") }) { continue }
45 guard case .file(let kind) = WorkspaceScanner.classify(url.lastPathComponent),
46 let values = try? url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey, .isDirectoryKey]),
47 values.isDirectory != true else { continue }
48 found.append(DiscoveredFile(
49 url: url, kind: kind, size: values.fileSize ?? 0,
50 mtime: values.contentModificationDate?.timeIntervalSince1970 ?? 0
51 ))
52 }
53 return try reconcile(root: root, found: found, known: known)
54 }
55
56 private func reconcile(root: URL, found: [DiscoveredFile], known: [String: FileState]) throws -> ReconcileReport {
57 var report = ReconcileReport()
58 var change = IndexChange()
59 var candidates: [(file: DiscoveredFile, bytes: [UInt8], hash: String)] = []
60
61 for file in found {
62 let path = file.url.path
63 if let state = known[path], state.size == file.size, state.mtime == file.mtime,
64 state.settingsVersion == settings.version, state.kind == file.kind {
65 report.unchanged += 1
66 continue
67 }
68 if file.kind == .other {
69 let record = FileRecord(path: path, root: root.path, unreadSize: file.size, mtime: file.mtime, settings: settings)
70 if let state = known[path], state.hash == record.hash, state.settingsVersion == settings.version, state.kind == .other {
71 report.unchanged += 1
72 } else {
73 candidates.append((file, [], record.hash))
74 }
75 continue
76 }
77 guard let data = try? Data(contentsOf: file.url) else { continue }
78 let bytes = [UInt8](data)
79 let hash = FileRecord.hash(bytes)
80 if let state = known[path], state.hash == hash, state.settingsVersion == settings.version, state.kind == file.kind {
81 change.touches.append((path, file.mtime))
82 report.touched.append(path)
83 } else {
84 candidates.append((file, bytes, hash))
85 }
86 }
87
88 // A file that vanished and one that appeared with the same content is a rename.
89 let foundPaths = Set(found.map(\.url.path))
90 var missing = known.filter { !foundPaths.contains($0.key) }
91 for candidate in candidates {
92 let path = candidate.file.url.path
93 if known[path] == nil,
94 let (oldPath, _) = missing.first(where: {
95 $0.value.hash == candidate.hash && $0.value.settingsVersion == settings.version && $0.value.kind == candidate.file.kind
96 }) {
97 missing[oldPath] = nil
98 change.moves.append((oldPath, path, candidate.file.mtime))
99 report.moved.append(path)
100 } else if candidate.file.kind == .other {
101 change.records.append(FileRecord(path: path, root: root.path, unreadSize: candidate.file.size, mtime: candidate.file.mtime, settings: settings))
102 report.indexed.append(path)
103 } else {
104 change.records.append(FileRecord(
105 path: path, root: root.path, kind: candidate.file.kind,
106 bytes: candidate.bytes, mtime: candidate.file.mtime, settings: settings
107 ))
108 report.indexed.append(path)
109 }
110 }
111 change.removals = missing.keys.sorted()
112 report.removed = change.removals
113 try index.apply(change)
114 return report
115 }
116}