-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathchange-detection.ts
More file actions
517 lines (455 loc) · 15.1 KB
/
change-detection.ts
File metadata and controls
517 lines (455 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
import { AutomergeUrl, Repo, UrlHeads } from "@automerge/automerge-repo";
import * as A from "@automerge/automerge";
import {
ChangeType,
FileType,
SyncSnapshot,
FileDocument,
DirectoryDocument,
DetectedChange,
} from "../types";
import {
readFileContent,
listDirectory,
normalizePath,
getRelativePath,
findFileInDirectoryHierarchy,
} from "../utils";
import { isContentEqual } from "../utils/content";
import { out } from "../utils/output";
/**
* Change detection engine
*/
export class ChangeDetector {
constructor(
private repo: Repo,
private rootPath: string,
private excludePatterns: string[] = []
) {}
/**
* Detect all changes between local filesystem and snapshot
*/
async detectChanges(snapshot: SyncSnapshot): Promise<DetectedChange[]> {
const changes: DetectedChange[] = [];
// Get current filesystem state
const currentFiles = await this.getCurrentFilesystemState();
// Check for local changes (new, modified, deleted files)
const localChanges = await this.detectLocalChanges(snapshot, currentFiles);
changes.push(...localChanges);
// Check for remote changes (changes in Automerge documents)
const remoteChanges = await this.detectRemoteChanges(snapshot);
changes.push(...remoteChanges);
// Check for new remote documents not in snapshot (critical for clone scenarios)
const newRemoteDocuments = await this.detectNewRemoteDocuments(snapshot);
changes.push(...newRemoteDocuments);
return changes;
}
/**
* Detect changes in local filesystem compared to snapshot
*/
private async detectLocalChanges(
snapshot: SyncSnapshot,
currentFiles: Map<string, { content: string | Uint8Array; type: FileType }>
): Promise<DetectedChange[]> {
const changes: DetectedChange[] = [];
// Check for new and modified files in parallel for better performance
await Promise.all(
Array.from(currentFiles.entries()).map(
async ([relativePath, fileInfo]) => {
const snapshotEntry = snapshot.files.get(relativePath);
if (!snapshotEntry) {
// New file
changes.push({
path: relativePath,
changeType: ChangeType.LOCAL_ONLY,
fileType: fileInfo.type,
localContent: fileInfo.content,
remoteContent: null,
});
} else {
// Check if content changed
const lastKnownContent = await this.getContentAtHead(
snapshotEntry.url,
snapshotEntry.head
);
const contentChanged = !isContentEqual(
fileInfo.content,
lastKnownContent
);
if (contentChanged) {
// Check remote state too
const currentRemoteContent = await this.getCurrentRemoteContent(
snapshotEntry.url
);
const remoteChanged = !isContentEqual(
lastKnownContent,
currentRemoteContent
);
const changeType = remoteChanged
? ChangeType.BOTH_CHANGED
: ChangeType.LOCAL_ONLY;
const remoteHead = await this.getCurrentRemoteHead(
snapshotEntry.url
);
changes.push({
path: relativePath,
changeType,
fileType: fileInfo.type,
localContent: fileInfo.content,
remoteContent: currentRemoteContent,
localHead: snapshotEntry.head,
remoteHead,
});
}
}
}
)
);
// Check for deleted files in parallel
await Promise.all(
Array.from(snapshot.files.entries())
.filter(([relativePath]) => !currentFiles.has(relativePath))
.map(async ([relativePath, snapshotEntry]) => {
// File was deleted locally
const currentRemoteContent = await this.getCurrentRemoteContent(
snapshotEntry.url
);
const lastKnownContent = await this.getContentAtHead(
snapshotEntry.url,
snapshotEntry.head
);
const remoteChanged = !isContentEqual(
lastKnownContent,
currentRemoteContent
);
const changeType = remoteChanged
? ChangeType.BOTH_CHANGED
: ChangeType.LOCAL_ONLY;
changes.push({
path: relativePath,
changeType,
fileType: FileType.TEXT, // Will be determined from document
localContent: null,
remoteContent: currentRemoteContent,
localHead: snapshotEntry.head,
remoteHead: await this.getCurrentRemoteHead(snapshotEntry.url),
});
})
);
return changes;
}
/**
* Detect changes in remote Automerge documents compared to snapshot
*/
private async detectRemoteChanges(
snapshot: SyncSnapshot
): Promise<DetectedChange[]> {
const changes: DetectedChange[] = [];
await Promise.all(
Array.from(snapshot.files.entries()).map(
async ([relativePath, snapshotEntry]) => {
// CRITICAL FIX: Check if file still exists in remote directory listing
// Files can be removed from the directory without their document heads changing
const stillExistsInDirectory = await this.fileExistsInRemoteDirectory(
snapshot.rootDirectoryUrl,
relativePath
);
if (!stillExistsInDirectory) {
// File was removed from remote directory listing
const localContent = await this.getLocalContent(relativePath);
// Only report as deleted if local file still exists
// (if local file is also deleted, detectLocalChanges handles it)
if (localContent !== null) {
changes.push({
path: relativePath,
changeType: ChangeType.REMOTE_ONLY,
fileType: FileType.TEXT,
localContent,
remoteContent: null, // File deleted remotely
localHead: snapshotEntry.head,
remoteHead: snapshotEntry.head,
});
}
return;
}
const currentRemoteHead = await this.getCurrentRemoteHead(
snapshotEntry.url
);
if (!A.equals(currentRemoteHead, snapshotEntry.head)) {
// Remote document has changed
const currentRemoteContent = await this.getCurrentRemoteContent(
snapshotEntry.url
);
const localContent = await this.getLocalContent(relativePath);
const lastKnownContent = await this.getContentAtHead(
snapshotEntry.url,
snapshotEntry.head
);
const localChanged = localContent
? !isContentEqual(localContent, lastKnownContent)
: false;
const changeType = localChanged
? ChangeType.BOTH_CHANGED
: ChangeType.REMOTE_ONLY;
changes.push({
path: relativePath,
changeType,
fileType: await this.getFileTypeFromContent(currentRemoteContent),
localContent,
remoteContent: currentRemoteContent,
localHead: snapshotEntry.head,
remoteHead: currentRemoteHead,
});
}
}
)
);
return changes;
}
/**
* Detect new remote documents from directory hierarchy that aren't in snapshot
* This is critical for clone scenarios where local snapshot is empty
*/
private async detectNewRemoteDocuments(
snapshot: SyncSnapshot
): Promise<DetectedChange[]> {
const changes: DetectedChange[] = [];
// If no root directory URL, nothing to discover
if (!snapshot.rootDirectoryUrl) {
return changes;
}
try {
// Recursively traverse the directory hierarchy
await this.discoverRemoteDocumentsRecursive(
snapshot.rootDirectoryUrl,
"",
snapshot,
changes
);
} catch (error) {
out.taskLine(`Failed to discover remote documents: ${error}`, true);
}
return changes;
}
/**
* Recursively discover remote documents in directory hierarchy
*/
private async discoverRemoteDocumentsRecursive(
directoryUrl: AutomergeUrl,
currentPath: string,
snapshot: SyncSnapshot,
changes: DetectedChange[]
): Promise<void> {
try {
const dirHandle = await this.repo.find<DirectoryDocument>(directoryUrl);
const dirDoc = await dirHandle.doc();
if (!dirDoc) {
return;
}
// Process each entry in the directory
for (const entry of dirDoc.docs) {
const entryPath = currentPath
? `${currentPath}/${entry.name}`
: entry.name;
if (entry.type === "file") {
// Check if this file is already tracked in the snapshot
const existingEntry = snapshot.files.get(entryPath);
if (!existingEntry) {
// This is a remote file not in our snapshot
const localContent = await this.getLocalContent(entryPath);
const remoteContent = await this.getCurrentRemoteContent(entry.url);
const remoteHead = await this.getCurrentRemoteHead(entry.url);
if (localContent && remoteContent) {
// File exists both locally and remotely but not in snapshot
changes.push({
path: entryPath,
changeType: ChangeType.BOTH_CHANGED,
fileType: await this.getFileTypeFromContent(remoteContent),
localContent,
remoteContent,
remoteHead,
});
} else if (localContent !== null && remoteContent === null) {
// File exists locally but not remotely (shouldn't happen in this flow)
changes.push({
path: entryPath,
changeType: ChangeType.LOCAL_ONLY,
fileType: await this.getFileTypeFromContent(localContent),
localContent,
remoteContent: null,
});
} else if (localContent === null && remoteContent !== null) {
// File exists remotely but not locally - this is what we need for clone!
changes.push({
path: entryPath,
changeType: ChangeType.REMOTE_ONLY,
fileType: await this.getFileTypeFromContent(remoteContent),
localContent: null,
remoteContent,
remoteHead,
});
}
// Only ignore if neither local nor remote content exists (ghost entry)
}
} else if (entry.type === "folder") {
// Recursively process subdirectory
await this.discoverRemoteDocumentsRecursive(
entry.url,
entryPath,
snapshot,
changes
);
}
}
} catch (error) {
out.taskLine(`Failed to process directory: ${error}`, true);
}
}
/**
* Get current filesystem state as a map
*/
private async getCurrentFilesystemState(): Promise<
Map<string, { content: string | Uint8Array; type: FileType }>
> {
const fileMap = new Map<
string,
{ content: string | Uint8Array; type: FileType }
>();
try {
const entries = await listDirectory(
this.rootPath,
true,
this.excludePatterns
);
const fileEntries = entries.filter(
(entry) => entry.type !== FileType.DIRECTORY
);
await Promise.all(
fileEntries.map(async (entry) => {
const relativePath = getRelativePath(this.rootPath, entry.path);
const content = await readFileContent(entry.path);
fileMap.set(relativePath, {
content,
type: entry.type,
});
})
);
} catch (error) {
out.taskLine(`Failed to scan filesystem: ${error}`, true);
}
return fileMap;
}
/**
* Get local file content if it exists
*/
private async getLocalContent(
relativePath: string
): Promise<string | Uint8Array | null> {
try {
const fullPath = normalizePath(this.rootPath + "/" + relativePath);
return await readFileContent(fullPath);
} catch {
return null;
}
}
/**
* Get content from Automerge document at specific head
*/
private async getContentAtHead(
url: AutomergeUrl,
heads: UrlHeads
): Promise<string | Uint8Array | null> {
const handle = await this.repo.find<FileDocument>(url);
const doc = await handle.view(heads).doc();
return (doc as FileDocument | undefined)?.content ?? null;
}
/**
* Get current content from Automerge document
*/
private async getCurrentRemoteContent(
url: AutomergeUrl
): Promise<string | Uint8Array | null> {
try {
const handle = await this.repo.find<FileDocument>(url);
const doc = await handle.doc();
if (!doc) return null;
const fileDoc = doc as FileDocument;
return fileDoc.content;
} catch (error) {
out.taskLine(`Failed to get remote content: ${error}`, true);
return null;
}
}
/**
* Get current head of Automerge document
*/
private async getCurrentRemoteHead(url: AutomergeUrl): Promise<UrlHeads> {
const handle = await this.repo.find<FileDocument>(url);
return handle.heads();
}
/**
* Determine file type from content
*/
private async getFileTypeFromContent(
content: string | Uint8Array | null
): Promise<FileType> {
if (!content) return FileType.TEXT;
if (content instanceof Uint8Array) {
return FileType.BINARY;
} else {
return FileType.TEXT;
}
}
/**
* Classify change type for a path
*/
async classifyChange(
relativePath: string,
snapshot: SyncSnapshot
): Promise<ChangeType> {
const snapshotEntry = snapshot.files.get(relativePath);
const localContent = await this.getLocalContent(relativePath);
if (!snapshotEntry) {
// New file
return ChangeType.LOCAL_ONLY;
}
const lastKnownContent = await this.getContentAtHead(
snapshotEntry.url,
snapshotEntry.head
);
const currentRemoteContent = await this.getCurrentRemoteContent(
snapshotEntry.url
);
const localChanged = localContent
? !isContentEqual(localContent, lastKnownContent)
: true;
const remoteChanged = !isContentEqual(
lastKnownContent,
currentRemoteContent
);
if (!localChanged && !remoteChanged) {
return ChangeType.NO_CHANGE;
} else if (localChanged && !remoteChanged) {
return ChangeType.LOCAL_ONLY;
} else if (!localChanged && remoteChanged) {
return ChangeType.REMOTE_ONLY;
} else {
return ChangeType.BOTH_CHANGED;
}
}
/**
* Check if a file exists in the remote directory hierarchy
*/
private async fileExistsInRemoteDirectory(
rootDirectoryUrl: AutomergeUrl | undefined,
filePath: string
): Promise<boolean> {
if (!rootDirectoryUrl) return false;
const entry = await findFileInDirectoryHierarchy(
this.repo,
rootDirectoryUrl,
filePath
);
return entry !== null;
}
}