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