@wirecat/cli-core 0.720.0 → 0.721.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/config-command.js +8 -2
- package/dist/cli/config-issues.d.ts +3 -1
- package/dist/cli/config-issues.js +9 -2
- package/dist/cli/documents/file-conflicts.d.ts +25 -0
- package/dist/cli/documents/file-conflicts.js +102 -0
- package/dist/cli/documents/file-edit.d.ts +29 -0
- package/dist/cli/documents/file-edit.js +352 -0
- package/dist/cli/documents/file-update.d.ts +43 -0
- package/dist/cli/documents/file-update.js +95 -0
- package/dist/cli/documents/history.d.ts +34 -0
- package/dist/cli/documents/history.js +89 -0
- package/dist/cli/documents/index.d.ts +9 -2
- package/dist/cli/documents/index.js +9 -2
- package/dist/cli/documents/library.js +10 -0
- package/dist/cli/permission-keys.d.ts +6 -0
- package/dist/cli/permission-keys.js +15 -3
- package/dist/cli/service-api.d.ts +1 -1
- package/dist/cli/service-api.js +16 -34
- package/dist/documents/file-mirror-model.d.ts +18 -1
- package/dist/documents/index.d.ts +7 -4
- package/dist/documents/index.js +4 -1
- package/dist/documents/model.d.ts +16 -1
- package/dist/errors/reasons.js +4 -0
- package/dist/services/documents/block-diff.d.ts +13 -3
- package/dist/services/documents/block-diff.js +13 -7
- package/dist/services/documents/ingestion.d.ts +21 -2
- package/dist/services/documents/ingestion.js +29 -2
- package/dist/services/documents/plan.js +16 -7
- package/dist/services/documents/ports.d.ts +2 -0
- package/dist/services/documents/sync.d.ts +1 -0
- package/dist/services/documents/sync.js +9 -4
- package/dist/services/files/conflicts.d.ts +78 -0
- package/dist/services/files/conflicts.js +183 -0
- package/dist/services/files/guarded-write.d.ts +34 -0
- package/dist/services/files/guarded-write.js +42 -0
- package/dist/services/files/listing.d.ts +8 -0
- package/dist/services/files/listing.js +1 -1
- package/dist/services/files/local-files.d.ts +54 -0
- package/dist/services/files/local-files.js +143 -0
- package/dist/services/files/mirror-state.d.ts +14 -0
- package/dist/services/files/mirror-state.js +65 -0
- package/dist/services/files/mirror.d.ts +3 -13
- package/dist/services/files/mirror.js +163 -204
- package/dist/services/files/text-merge.d.ts +27 -0
- package/dist/services/files/text-merge.js +134 -0
- package/dist/services/files/versions.d.ts +36 -9
- package/dist/services/files/versions.js +40 -12
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/index.d.ts +1 -0
- package/dist/store/index.js +1 -0
- package/dist/store/sqlite/document-history.d.ts +84 -0
- package/dist/store/sqlite/document-history.js +158 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +17 -0
- package/dist/store/sqlite/notes.d.ts +9 -10
- package/dist/store/sqlite/notes.js +33 -21
- package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
- package/dist/store/sqlite/schema/document-changes.js +11 -0
- package/dist/store/sqlite/schema.d.ts +65 -0
- package/dist/store/sqlite/schema.js +5 -0
- package/package.json +2 -2
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { mkdir, rm, stat,
|
|
2
|
+
import { mkdir, rm, stat, writeFile } from "node:fs/promises";
|
|
3
3
|
import { dirname, join, posix } from "node:path";
|
|
4
|
-
import { CliError
|
|
5
|
-
import
|
|
6
|
-
import {
|
|
7
|
-
import { assertNoLink, hashFile, localTemp, placeNew, replaceLocal, safePath, scanLocal, skippedName, } from "../documents/push.js";
|
|
4
|
+
import { CliError } from "@wirecat/cli-base";
|
|
5
|
+
import { eachMirror, heldCheck } from "../documents/mirrors.js";
|
|
6
|
+
import { assertNoLink, localTemp, replaceLocal, safePath, skippedName, } from "../documents/push.js";
|
|
8
7
|
import { excludedBy } from "./exclusions.js";
|
|
9
|
-
import {
|
|
8
|
+
import { listRemote } from "./listing.js";
|
|
9
|
+
import { ancestors, copyName, freeSpace, gigabytes, linkFree, MAX_FILES, renameLocal, scan, shortOfSpace, spareFor, trashLocal, under, whole, } from "./local-files.js";
|
|
10
|
+
import { mergeable, mergeText } from "./text-merge.js";
|
|
11
|
+
export { fileMirrorStatus, fileSyncState } from "./mirror-state.js";
|
|
10
12
|
const HINTS = {
|
|
11
13
|
preview: "--dry-run",
|
|
12
14
|
repin: "--repin",
|
|
@@ -22,11 +24,9 @@ const HINTS = {
|
|
|
22
24
|
*/
|
|
23
25
|
export const MAX_DELETIONS = 10;
|
|
24
26
|
export const MAX_REPLACEMENTS = 50;
|
|
25
|
-
/**
|
|
26
|
-
const
|
|
27
|
-
const MAX_FILES = 100_000;
|
|
27
|
+
/** The whole-file step `keep` settles a conflict with when both sides changed. */
|
|
28
|
+
const KEPT = { local: "upload", remote: "download", both: "keep-both" };
|
|
28
29
|
const CHECKS = 8;
|
|
29
|
-
const TRASH = ".wirecat-trash";
|
|
30
30
|
const SAVE_EVERY_MS = 1_000;
|
|
31
31
|
/** A temporary file's tag from any operation id, safe in a file name. */
|
|
32
32
|
const tagOf = (operationId) => createHash("sha256").update(operationId).digest("hex").slice(0, 8);
|
|
@@ -35,7 +35,7 @@ const sameFile = (local, remote) => local.hash === remote.sha256;
|
|
|
35
35
|
* The three-way comparison of one path: the local file now, the remote file now and the last sync. A side is
|
|
36
36
|
* "same" when its content still has the last sync's hash.
|
|
37
37
|
*/
|
|
38
|
-
const decide = (path, sure, local, remote, base, keep) => {
|
|
38
|
+
const decide = (path, sure, local, remote, base, keep, merges = false) => {
|
|
39
39
|
const step = (kind, reason) => ({
|
|
40
40
|
kind,
|
|
41
41
|
path,
|
|
@@ -70,6 +70,8 @@ const decide = (path, sure, local, remote, base, keep) => {
|
|
|
70
70
|
return settle("deleted here, changed on the remote", "trash-remote", "download", "download");
|
|
71
71
|
if (!remote)
|
|
72
72
|
return settle("changed here, deleted on the remote", "upload", "trash-local", "upload");
|
|
73
|
+
if (merges)
|
|
74
|
+
return step("merge");
|
|
73
75
|
return settle("changed on both sides", "upload", "download", "keep-both");
|
|
74
76
|
function settle(reason, ...[ifLocal, ifRemote, ifBoth]) {
|
|
75
77
|
if (keep === "local")
|
|
@@ -81,98 +83,8 @@ const decide = (path, sure, local, remote, base, keep) => {
|
|
|
81
83
|
return step("conflict", reason);
|
|
82
84
|
}
|
|
83
85
|
};
|
|
84
|
-
/** `name (conflict 2026-11-18 disk).ext`, numbered when that name is taken. */
|
|
85
|
-
const copyName = (path, remote, date, taken) => {
|
|
86
|
-
const extension = posix.extname(path);
|
|
87
|
-
const stem = path.slice(0, path.length - extension.length);
|
|
88
|
-
for (let n = 1;; n++) {
|
|
89
|
-
const candidate = `${stem} (conflict ${date} ${remote}${n > 1 ? ` ${n}` : ""})${extension}`;
|
|
90
|
-
if (!taken(candidate))
|
|
91
|
-
return candidate;
|
|
92
|
-
}
|
|
93
|
-
};
|
|
94
|
-
/** Moves a file into `<root>/.wirecat-trash/<date>/` while it still has `hash`; false when it changed. */
|
|
95
|
-
const trashLocal = async (root, path, hash, date) => {
|
|
96
|
-
await assertNoLink(root, path);
|
|
97
|
-
await assertNoLink(root, posix.join(TRASH, date, path));
|
|
98
|
-
const from = join(root, path);
|
|
99
|
-
if ((await hashFile(from)).sha256 !== hash)
|
|
100
|
-
return false;
|
|
101
|
-
const into = join(root, TRASH, date, path);
|
|
102
|
-
await mkdir(dirname(into), { recursive: true });
|
|
103
|
-
for (let n = 1;; n++) {
|
|
104
|
-
try {
|
|
105
|
-
await placeNew(from, n > 1 ? `${into}.${n}` : into);
|
|
106
|
-
break;
|
|
107
|
-
}
|
|
108
|
-
catch (error) {
|
|
109
|
-
if (error.code !== "EEXIST")
|
|
110
|
-
throw error;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
await unlink(from);
|
|
114
|
-
return true;
|
|
115
|
-
};
|
|
116
|
-
/** Renames a local file while it still has `hash` and nothing holds the new name; false otherwise. */
|
|
117
|
-
const renameLocal = async (root, from, to, hash) => {
|
|
118
|
-
await assertNoLink(root, from);
|
|
119
|
-
await assertNoLink(root, to);
|
|
120
|
-
const source = join(root, from);
|
|
121
|
-
if ((await hashFile(source)).sha256 !== hash)
|
|
122
|
-
return false;
|
|
123
|
-
await mkdir(dirname(join(root, to)), { recursive: true });
|
|
124
|
-
try {
|
|
125
|
-
await placeNew(source, join(root, to));
|
|
126
|
-
}
|
|
127
|
-
catch (error) {
|
|
128
|
-
if (error.code === "EEXIST")
|
|
129
|
-
return false;
|
|
130
|
-
throw error;
|
|
131
|
-
}
|
|
132
|
-
await unlink(source);
|
|
133
|
-
return true;
|
|
134
|
-
};
|
|
135
|
-
/** Every local file but excluded ones, hashed only when its size or mtime moved since the last sync. */
|
|
136
|
-
const scan = async (root, entries, excluded, maxFiles = MAX_FILES) => {
|
|
137
|
-
const { files, links } = await scanLocal(root, () => "file", maxFiles, (path) => {
|
|
138
|
-
const entry = entries[path];
|
|
139
|
-
return entry && { size: entry.localSize, mtimeMs: entry.localMtimeMs, hash: entry.sha256 };
|
|
140
|
-
}, excluded);
|
|
141
|
-
return { files: files, links };
|
|
142
|
-
};
|
|
143
86
|
/** Remote files the mirror covers: hidden files and editor leftovers are skipped, as they are locally. */
|
|
144
87
|
const mirrored = (files) => files.filter((file) => !file.path.split("/").some(skippedName));
|
|
145
|
-
/** False when `path` or a folder on the way to it is a symbolic link, so nothing under it is touched. */
|
|
146
|
-
const linkFree = (root, path) => assertNoLink(root, path).then(() => true, (error) => {
|
|
147
|
-
if (isCliError(error) && error.details?.reason === "mirror.symlink")
|
|
148
|
-
return false;
|
|
149
|
-
throw error;
|
|
150
|
-
});
|
|
151
|
-
/** True when the file at `absolute` is missing or has one of `hashes`: no partial copy is left there. */
|
|
152
|
-
const whole = async (absolute, hashes) => {
|
|
153
|
-
try {
|
|
154
|
-
return hashes.includes((await hashFile(absolute)).sha256);
|
|
155
|
-
}
|
|
156
|
-
catch (error) {
|
|
157
|
-
return error.code === "ENOENT";
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
/** True when `path` is `link` or lies under it. */
|
|
161
|
-
const under = (path, link) => path === link || path.startsWith(`${link}/`);
|
|
162
|
-
/** Free bytes and the device of the file system holding `path`, or of its nearest folder that exists. */
|
|
163
|
-
const freeSpace = async (path) => {
|
|
164
|
-
for (let at = path;; at = dirname(at)) {
|
|
165
|
-
try {
|
|
166
|
-
const [{ bavail, bsize }, { dev }] = await Promise.all([statfs(at), stat(at)]);
|
|
167
|
-
return { free: bavail * bsize, dev };
|
|
168
|
-
}
|
|
169
|
-
catch (error) {
|
|
170
|
-
if (error.code !== "ENOENT" || dirname(at) === at)
|
|
171
|
-
throw error;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
};
|
|
175
|
-
const gigabytes = (bytes) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
|
|
176
88
|
/**
|
|
177
89
|
* Syncs a local folder and a remote folder of plain files both ways, whole files at a time. Each path is compared
|
|
178
90
|
* three ways (local now, remote now, last sync): a change on one side is copied to the other, the same content on
|
|
@@ -264,6 +176,7 @@ export const syncFileMirror = async (options) => {
|
|
|
264
176
|
const result = {
|
|
265
177
|
uploaded: [],
|
|
266
178
|
downloaded: [],
|
|
179
|
+
merged: [],
|
|
267
180
|
trashed: [],
|
|
268
181
|
renamed: [],
|
|
269
182
|
adopted: [],
|
|
@@ -342,7 +255,23 @@ export const syncFileMirror = async (options) => {
|
|
|
342
255
|
continue;
|
|
343
256
|
}
|
|
344
257
|
// A re-pinned run settles nothing: whatever `keep` says, different content is a conflict.
|
|
345
|
-
|
|
258
|
+
// Asked only of a file both sides changed: the store is not read for every unchanged one.
|
|
259
|
+
const merges = here !== undefined &&
|
|
260
|
+
file !== undefined &&
|
|
261
|
+
entry !== undefined &&
|
|
262
|
+
here.hash !== entry.sha256 &&
|
|
263
|
+
file.sha256 !== entry.sha256 &&
|
|
264
|
+
mergeable(path, here.size, file.size, entry.size) &&
|
|
265
|
+
versions.has(entry.sha256);
|
|
266
|
+
const step = decide(path, sure, here, file, entry, repin ? undefined : keep, merges);
|
|
267
|
+
// The same three contents the last run could not merge are not downloaded and merged again at every watch cycle.
|
|
268
|
+
const known = state.conflicts?.[path];
|
|
269
|
+
if (step?.kind === "merge" &&
|
|
270
|
+
known?.kept &&
|
|
271
|
+
known.base === entry?.sha256 &&
|
|
272
|
+
known.local === here?.hash &&
|
|
273
|
+
known.remote === file?.sha256)
|
|
274
|
+
Object.assign(step, keep ? { kind: KEPT[keep] } : { kind: "conflict", reason: known.reason });
|
|
346
275
|
if (step)
|
|
347
276
|
steps.push(step);
|
|
348
277
|
else
|
|
@@ -366,12 +295,37 @@ export const syncFileMirror = async (options) => {
|
|
|
366
295
|
if (why)
|
|
367
296
|
Object.assign(step, { kind: "unknown", reason: "remote", why });
|
|
368
297
|
}));
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
298
|
+
const earlier = state.conflicts ?? {};
|
|
299
|
+
const conflicts = {};
|
|
300
|
+
/** Reports and records a conflict; `kept` are the contents a failed merge kept, logged once per set of them. */
|
|
301
|
+
const conflict = (step, reason, kept) => {
|
|
302
|
+
result.conflicts.push({
|
|
303
|
+
path: step.path,
|
|
304
|
+
reason,
|
|
305
|
+
...(kept?.segments ? { parts: kept.segments } : {}),
|
|
306
|
+
...(step.local ? { localChangedAt: new Date(step.local.mtimeMs).toISOString(), localSize: step.local.size } : {}),
|
|
307
|
+
...(step.remote ? { remoteChangedAt: step.remote.modifiedAt, remoteSize: step.remote.size } : {}),
|
|
308
|
+
});
|
|
309
|
+
const found = {
|
|
310
|
+
reason,
|
|
311
|
+
at: new Date(now()).toISOString(),
|
|
312
|
+
...(step.base ? { base: step.base.sha256 } : {}),
|
|
313
|
+
...(step.local ? { local: step.local.hash } : {}),
|
|
314
|
+
...(step.remote ? { remote: step.remote.sha256, remoteFile: step.remote } : {}),
|
|
315
|
+
};
|
|
316
|
+
const before = earlier[step.path];
|
|
317
|
+
const same = before?.base === found.base && before?.local === found.local && before?.remote === found.remote;
|
|
318
|
+
if (kept) {
|
|
319
|
+
found.kept = true;
|
|
320
|
+
// A conflict `keep` settles at once is no conflict anyone resolves later.
|
|
321
|
+
if (!keep && (!same || !before?.kept))
|
|
322
|
+
versions.log({ path: step.path, event: "conflict", direction: "both", parts: kept.parts });
|
|
323
|
+
}
|
|
324
|
+
else if (same && before?.kept)
|
|
325
|
+
found.kept = true;
|
|
326
|
+
// A conflict seen again keeps the time it was first found.
|
|
327
|
+
conflicts[step.path] = same && before ? { ...found, at: before.at } : found;
|
|
328
|
+
};
|
|
375
329
|
for (const step of steps) {
|
|
376
330
|
if (step.kind === "conflict")
|
|
377
331
|
conflict(step, step.reason ?? "");
|
|
@@ -383,7 +337,10 @@ export const syncFileMirror = async (options) => {
|
|
|
383
337
|
});
|
|
384
338
|
}
|
|
385
339
|
const deletions = steps.filter((step) => step.kind === "trash-local" || step.kind === "trash-remote").length;
|
|
386
|
-
const replacements = steps.filter((step) => (step.kind === "upload" && step.remote) ||
|
|
340
|
+
const replacements = steps.filter((step) => (step.kind === "upload" && step.remote) ||
|
|
341
|
+
(step.kind === "download" && step.local) ||
|
|
342
|
+
step.kind === "keep-both" ||
|
|
343
|
+
step.kind === "merge").length;
|
|
387
344
|
const over = [
|
|
388
345
|
...(deletions > MAX_DELETIONS
|
|
389
346
|
? [
|
|
@@ -512,7 +469,13 @@ export const syncFileMirror = async (options) => {
|
|
|
512
469
|
reason: "mirror.remote-changed",
|
|
513
470
|
});
|
|
514
471
|
};
|
|
515
|
-
|
|
472
|
+
/** Keeps a mergeable file's synced content, the base of its next merge; a file that changed meanwhile has none. */
|
|
473
|
+
const keepBase = async (path, absolute, sha256, size) => {
|
|
474
|
+
// A base that could not be kept costs a conflict at the next change on both sides, never this run's write.
|
|
475
|
+
if (mergeable(path, size) && !versions.has(sha256))
|
|
476
|
+
await versions.keep(absolute).catch(() => undefined);
|
|
477
|
+
};
|
|
478
|
+
const upload = async (path, from, expect, created, replaced, merged = false) => {
|
|
516
479
|
if (replaced)
|
|
517
480
|
await keepRemote(path, replaced);
|
|
518
481
|
for (const up of ancestors(path))
|
|
@@ -524,6 +487,9 @@ export const syncFileMirror = async (options) => {
|
|
|
524
487
|
if (sent.sha256 !== undefined && sent.sha256 !== from.hash)
|
|
525
488
|
throw new CliError("conflict", "the local file changed during the upload", { reason: "upload.mismatch" });
|
|
526
489
|
record(path, sent, from, from.hash);
|
|
490
|
+
await keepBase(path, from.absolute, from.hash, from.size);
|
|
491
|
+
if (merged)
|
|
492
|
+
return;
|
|
527
493
|
versions.log({
|
|
528
494
|
path,
|
|
529
495
|
event: created ? "created" : "changed",
|
|
@@ -564,8 +530,10 @@ export const syncFileMirror = async (options) => {
|
|
|
564
530
|
delete state.pending[path];
|
|
565
531
|
if (!written)
|
|
566
532
|
return false;
|
|
567
|
-
if (recorded)
|
|
533
|
+
if (recorded) {
|
|
568
534
|
record(path, file, await stat(absolute), written.sha256);
|
|
535
|
+
await keepBase(path, absolute, written.sha256, file.size);
|
|
536
|
+
}
|
|
569
537
|
versions.log({
|
|
570
538
|
path,
|
|
571
539
|
event: old ? "changed" : "created",
|
|
@@ -579,14 +547,72 @@ export const syncFileMirror = async (options) => {
|
|
|
579
547
|
};
|
|
580
548
|
const expectOf = (file) => file ? { sha256: file.sha256, ...(file.md5 ? { md5: file.md5 } : {}) } : { absent: true };
|
|
581
549
|
const changedHere = (step) => conflict(step, "the local file changed during the sync");
|
|
550
|
+
/**
|
|
551
|
+
* Merges a text file both sides changed: the remote and the local contents are kept first, the merge reads all
|
|
552
|
+
* three from the store, and the result is written locally, then uploaded over the remote the listing saw. False
|
|
553
|
+
* when the lines conflict, so `keep` can settle the file whole.
|
|
554
|
+
*/
|
|
555
|
+
const merge = async (step, here, there, last) => {
|
|
556
|
+
const { path } = step;
|
|
557
|
+
const remoteHash = there.sha256;
|
|
558
|
+
await keepRemote(path, there);
|
|
559
|
+
if ((await versions.keep(here.absolute)) !== here.hash) {
|
|
560
|
+
changedHere(step);
|
|
561
|
+
return true;
|
|
562
|
+
}
|
|
563
|
+
const parts = { base: last.sha256, local: here.hash, remote: remoteHash };
|
|
564
|
+
const [base, mine, theirs] = await Promise.all([last.sha256, here.hash, remoteHash].map((hash) => versions.read(hash)));
|
|
565
|
+
if (!base || !mine || !theirs) {
|
|
566
|
+
conflict(step, "changed on both sides, and the earlier version to merge against is no longer kept");
|
|
567
|
+
return false;
|
|
568
|
+
}
|
|
569
|
+
const merged = await mergeText(path, base, mine, theirs);
|
|
570
|
+
if (!("merged" in merged)) {
|
|
571
|
+
conflict(step, "changed on both sides in the same lines", {
|
|
572
|
+
parts,
|
|
573
|
+
segments: merged.conflicts.map(({ base, local, remote }) => ({ base, local, remote })),
|
|
574
|
+
});
|
|
575
|
+
return false;
|
|
576
|
+
}
|
|
577
|
+
const outcome = await versions.keep((temp) => writeFile(temp, merged.merged, { flag: "wx", mode: 0o600 }));
|
|
578
|
+
const absolute = join(root, path);
|
|
579
|
+
await assertNoLink(root, path);
|
|
580
|
+
const operationId = options.operationId();
|
|
581
|
+
const written = await write("update", "local", path, () => replaceLocal(absolute, here.hash, merged.merged, { tag: tagOf(operationId), sha256: outcome }), operationId);
|
|
582
|
+
if (!written) {
|
|
583
|
+
changedHere(step);
|
|
584
|
+
return true;
|
|
585
|
+
}
|
|
586
|
+
const placed = await stat(absolute);
|
|
587
|
+
// Both sides as the remote is now, with a local size no file has: a crash before the upload leaves the merged
|
|
588
|
+
// file a local change, hashed again and sent by the next run, never merged twice.
|
|
589
|
+
state.entries[path] = {
|
|
590
|
+
id: there.id,
|
|
591
|
+
size: there.size,
|
|
592
|
+
sha256: remoteHash,
|
|
593
|
+
...(there.md5 ? { md5: there.md5 } : {}),
|
|
594
|
+
remoteModified: there.modifiedAt,
|
|
595
|
+
localMtimeMs: -1,
|
|
596
|
+
localSize: -1,
|
|
597
|
+
syncedAt: new Date(now()).toISOString(),
|
|
598
|
+
};
|
|
599
|
+
save(true);
|
|
600
|
+
versions.log({ path, event: "merged", direction: "both", parts, new: outcome, size: placed.size });
|
|
601
|
+
const sent = { ...here, hash: outcome, size: placed.size, mtimeMs: placed.mtimeMs };
|
|
602
|
+
await upload(path, sent, expectOf(there), false, undefined, true);
|
|
603
|
+
result.merged.push(path);
|
|
604
|
+
return true;
|
|
605
|
+
};
|
|
582
606
|
const run = async (step) => {
|
|
583
607
|
const { path, local: here, remote: there, base: last } = step;
|
|
584
608
|
switch (step.kind) {
|
|
585
609
|
case "conflict":
|
|
586
610
|
return;
|
|
587
611
|
case "adopt":
|
|
588
|
-
if (here && there)
|
|
612
|
+
if (here && there) {
|
|
589
613
|
record(path, there, here, here.hash);
|
|
614
|
+
await keepBase(path, here.absolute, here.hash, here.size);
|
|
615
|
+
}
|
|
590
616
|
result.adopted.push(path);
|
|
591
617
|
return;
|
|
592
618
|
case "forget":
|
|
@@ -643,6 +669,15 @@ export const syncFileMirror = async (options) => {
|
|
|
643
669
|
result.renamed.push({ from: path, to });
|
|
644
670
|
return;
|
|
645
671
|
}
|
|
672
|
+
case "merge":
|
|
673
|
+
if (!here || !there || !last)
|
|
674
|
+
return;
|
|
675
|
+
if (!(await merge(step, here, there, last)) && keep) {
|
|
676
|
+
result.conflicts.pop();
|
|
677
|
+
delete conflicts[path];
|
|
678
|
+
return run({ ...step, kind: KEPT[keep] });
|
|
679
|
+
}
|
|
680
|
+
return;
|
|
646
681
|
case "keep-both": {
|
|
647
682
|
if (!here || !there)
|
|
648
683
|
return;
|
|
@@ -688,109 +723,33 @@ export const syncFileMirror = async (options) => {
|
|
|
688
723
|
state.pending[step.path] = { op: step.kind, operationId: lastOperation };
|
|
689
724
|
}
|
|
690
725
|
}
|
|
726
|
+
// A mirror synced before merges existed has no bases: an unchanged text file's content becomes its base now.
|
|
727
|
+
const stepped = new Set(steps.map((step) => step.path));
|
|
728
|
+
for (const [path, entry] of Object.entries(state.entries)) {
|
|
729
|
+
if (signal?.aborted)
|
|
730
|
+
break;
|
|
731
|
+
const here = local.get(path);
|
|
732
|
+
if (here?.hash === entry.sha256 && !stepped.has(path))
|
|
733
|
+
await keepBase(path, here.absolute, entry.sha256, here.size);
|
|
734
|
+
}
|
|
691
735
|
}
|
|
692
736
|
finally {
|
|
693
737
|
// Forgotten, so a file whose exclusion is removed later is a new file, never a deletion.
|
|
694
738
|
for (const path of Object.keys(state.entries))
|
|
695
739
|
if (excluded(path))
|
|
696
740
|
delete state.entries[path];
|
|
741
|
+
if (Object.keys(conflicts).length)
|
|
742
|
+
state.conflicts = conflicts;
|
|
743
|
+
else
|
|
744
|
+
delete state.conflicts;
|
|
697
745
|
save(true);
|
|
698
746
|
}
|
|
699
747
|
await options.assertHeld();
|
|
700
|
-
await versions.prune()
|
|
748
|
+
await versions.prune(Object.entries(state.entries)
|
|
749
|
+
.filter(([path, entry]) => mergeable(path, entry.size))
|
|
750
|
+
.map(([, entry]) => entry.sha256));
|
|
701
751
|
return result;
|
|
702
752
|
};
|
|
703
|
-
/**
|
|
704
|
-
* The free space a run needs that a file system lacks: downloads land under `root`, and the store keeps every
|
|
705
|
-
* content they replace or a deletion removes, plus each remote content an upload replaces that it lacks.
|
|
706
|
-
*/
|
|
707
|
-
const shortOfSpace = async (steps, root, versions, space) => {
|
|
708
|
-
let incoming = 0;
|
|
709
|
-
let kept = 0;
|
|
710
|
-
for (const step of steps) {
|
|
711
|
-
const local = step.local?.size ?? 0;
|
|
712
|
-
const remote = step.remote?.size ?? 0;
|
|
713
|
-
if (step.kind === "download") {
|
|
714
|
-
incoming += remote;
|
|
715
|
-
kept += local;
|
|
716
|
-
}
|
|
717
|
-
if (step.kind === "keep-both") {
|
|
718
|
-
incoming += remote;
|
|
719
|
-
kept += remote;
|
|
720
|
-
}
|
|
721
|
-
if (step.kind === "trash-local")
|
|
722
|
-
kept += local;
|
|
723
|
-
if (step.kind === "upload" && step.remote && !versions.has(step.remote.sha256))
|
|
724
|
-
kept += remote;
|
|
725
|
-
}
|
|
726
|
-
if (!incoming && !kept)
|
|
727
|
-
return undefined;
|
|
728
|
-
const here = await space(root);
|
|
729
|
-
const store = versions.dir === undefined ? here : await space(versions.dir);
|
|
730
|
-
const needs = store.dev === here.dev
|
|
731
|
-
? [{ path: root, needed: incoming + kept, free: here.free }]
|
|
732
|
-
: [
|
|
733
|
-
{ path: root, needed: incoming, free: here.free },
|
|
734
|
-
{ path: versions.dir, needed: kept, free: store.free },
|
|
735
|
-
];
|
|
736
|
-
return needs.find((need) => need.needed > 0 && need.free < need.needed + spareFor(need.needed));
|
|
737
|
-
};
|
|
738
|
-
const ancestors = (path) => {
|
|
739
|
-
const found = [];
|
|
740
|
-
for (let up = posix.dirname(path); up !== "."; up = posix.dirname(up))
|
|
741
|
-
found.unshift(up);
|
|
742
|
-
return found;
|
|
743
|
-
};
|
|
744
|
-
const entrySchema = v.object({
|
|
745
|
-
id: v.string(),
|
|
746
|
-
size: v.number(),
|
|
747
|
-
sha256: v.string(),
|
|
748
|
-
md5: v.optional(v.string()),
|
|
749
|
-
remoteModified: v.string(),
|
|
750
|
-
localMtimeMs: v.number(),
|
|
751
|
-
localSize: v.number(),
|
|
752
|
-
syncedAt: v.string(),
|
|
753
|
-
});
|
|
754
|
-
const stateSchema = v.object({
|
|
755
|
-
version: v.literal(1),
|
|
756
|
-
principal: v.string(),
|
|
757
|
-
root: v.string(),
|
|
758
|
-
target: v.string(),
|
|
759
|
-
rootId: v.optional(v.string()),
|
|
760
|
-
localRoot: v.optional(v.object({ dev: v.number(), ino: v.number() })),
|
|
761
|
-
entries: v.record(v.string(), entrySchema),
|
|
762
|
-
pending: v.record(v.string(), v.object({ op: v.string(), operationId: v.string(), created: v.optional(v.boolean()) })),
|
|
763
|
-
listing: v.optional(listingSchema),
|
|
764
|
-
});
|
|
765
|
-
/** A file mirror's state in `<dir>/<id>.json`, refused rather than reset when invalid. */
|
|
766
|
-
export const fileSyncState = (dir, mirror, principal) => jsonState(join(dir, `${mirror.id}.json`), stateSchema, () => ({
|
|
767
|
-
version: 1,
|
|
768
|
-
principal,
|
|
769
|
-
root: mirror.path,
|
|
770
|
-
target: mirror.folder,
|
|
771
|
-
entries: {},
|
|
772
|
-
pending: {},
|
|
773
|
-
}));
|
|
774
|
-
/** What each mirror's next sync would send from local changes alone; the remote is not asked. */
|
|
775
|
-
export const fileMirrorStatus = async (mirrors, stateOf) => {
|
|
776
|
-
const items = [];
|
|
777
|
-
for (const mirror of mirrors) {
|
|
778
|
-
const excluded = excludedBy(mirror.exclude);
|
|
779
|
-
const entries = Object.fromEntries(Object.entries(stateOf(mirror).read().entries).filter(([path]) => !excluded(path)));
|
|
780
|
-
const { files, links } = await scan(mirror.path, entries, excluded);
|
|
781
|
-
const seen = new Set(files.map((file) => file.path));
|
|
782
|
-
items.push({
|
|
783
|
-
id: mirror.id,
|
|
784
|
-
path: mirror.path,
|
|
785
|
-
folder: mirror.folder,
|
|
786
|
-
upload: files.filter((file) => entries[file.path]?.sha256 !== file.hash).map((file) => file.path),
|
|
787
|
-
delete: Object.keys(entries).filter((path) => !seen.has(path) && !links.some((link) => under(path, link))),
|
|
788
|
-
unchanged: files.length - files.filter((file) => entries[file.path]?.sha256 !== file.hash).length,
|
|
789
|
-
remote_checked: false,
|
|
790
|
-
});
|
|
791
|
-
}
|
|
792
|
-
return items;
|
|
793
|
-
};
|
|
794
753
|
/**
|
|
795
754
|
* A watch's `remoteChanges` for a file target: every mirror when the remote's revision moved since the last poll (or
|
|
796
755
|
* at the first poll), none when it did not, and every mirror at each poll when the target has no revision.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ConflictPart } from "../../documents/push-model.js";
|
|
2
|
+
/** Above this a text file is merged no more than a binary one: three copies are read whole into memory. */
|
|
3
|
+
export declare const MAX_MERGE_BYTES: number;
|
|
4
|
+
/** Whether a file both sides changed is merged line by line rather than reported as a conflict. */
|
|
5
|
+
export declare const mergeable: (path: string, ...sizes: number[]) => boolean;
|
|
6
|
+
/** One stretch of the merge: unchanged, changed on one side, the same change on both, or two different changes. */
|
|
7
|
+
export interface TextSegment extends ConflictPart {
|
|
8
|
+
kind: "same" | "local" | "remote" | "both" | "conflict";
|
|
9
|
+
/** The stretch's first line in the base, from 1. */
|
|
10
|
+
line: number;
|
|
11
|
+
}
|
|
12
|
+
export type TextMerge = {
|
|
13
|
+
merged: Buffer;
|
|
14
|
+
segments: TextSegment[];
|
|
15
|
+
} | {
|
|
16
|
+
conflicts: TextSegment[];
|
|
17
|
+
segments: TextSegment[];
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Merges a text file both sides changed since `base`, the content of the last sync. Lines are compared as bytes
|
|
21
|
+
* (read as latin1, which maps each byte to one character), so any 8-bit encoding, line endings and a byte-order mark
|
|
22
|
+
* pass through unchanged. Markdown that conflicts by lines gets a second try by blocks. `segments` always describe the
|
|
23
|
+
* line merge, so a conflict can be shown.
|
|
24
|
+
*/
|
|
25
|
+
export declare const mergeText: (path: string, base: Buffer, local: Buffer, remote: Buffer) => Promise<TextMerge>;
|
|
26
|
+
/** The segments' text as one file, with Git's markers around each conflict; `remote` names the other side. */
|
|
27
|
+
export declare const conflictText: (segments: TextSegment[], remote: string) => string;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import { markdownBlocks } from "../../documents/markdown-blocks.js";
|
|
3
|
+
import { adjoins, applied, diffSequence, mergeBlocks } from "../documents/block-diff.js";
|
|
4
|
+
import { spliceMarkdown } from "../documents/markdown-splice.js";
|
|
5
|
+
const MERGEABLE = new Set([".md", ".markdown", ".txt", ".csv", ".tsv"]);
|
|
6
|
+
/** Above this a text file is merged no more than a binary one: three copies are read whole into memory. */
|
|
7
|
+
export const MAX_MERGE_BYTES = 1024 * 1024;
|
|
8
|
+
const MARKDOWN = new Set([".md", ".markdown"]);
|
|
9
|
+
/** Whether a file both sides changed is merged line by line rather than reported as a conflict. */
|
|
10
|
+
export const mergeable = (path, ...sizes) => MERGEABLE.has(posix.extname(path).toLowerCase()) && sizes.every((size) => size <= MAX_MERGE_BYTES);
|
|
11
|
+
/** Lines with their own endings, so `\r\n`, a byte-order mark and a missing last newline come back byte for byte. */
|
|
12
|
+
const linesOf = (text) => text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
13
|
+
const same = (line) => line;
|
|
14
|
+
/**
|
|
15
|
+
* A three-way merge of line arrays, diff3 style: stretches both sides changed, unless changed the same, conflict.
|
|
16
|
+
* Edits on neighbouring lines conflict too, as in Git: two edits can read fine alone and wrong together.
|
|
17
|
+
*/
|
|
18
|
+
const mergeLines = (base, local, remote) => {
|
|
19
|
+
const tagged = [
|
|
20
|
+
...diffSequence(base, local, same).map((hunk) => ({ ...hunk, side: "local" })),
|
|
21
|
+
...diffSequence(base, remote, same).map((hunk) => ({ ...hunk, side: "remote" })),
|
|
22
|
+
].sort((a, b) => a.from - b.from || a.to - b.to);
|
|
23
|
+
const clusters = [];
|
|
24
|
+
for (const hunk of tagged) {
|
|
25
|
+
const last = clusters.at(-1);
|
|
26
|
+
if (last?.some((other) => adjoins(other, hunk)))
|
|
27
|
+
last.push(hunk);
|
|
28
|
+
else
|
|
29
|
+
clusters.push([hunk]);
|
|
30
|
+
}
|
|
31
|
+
const segments = [];
|
|
32
|
+
const unchanged = (from, to) => {
|
|
33
|
+
if (to <= from)
|
|
34
|
+
return;
|
|
35
|
+
const text = base.slice(from, to).join("");
|
|
36
|
+
segments.push({ kind: "same", line: from + 1, base: text, local: text, remote: text });
|
|
37
|
+
};
|
|
38
|
+
let at = 0;
|
|
39
|
+
for (const cluster of clusters) {
|
|
40
|
+
const from = cluster.reduce((low, hunk) => Math.min(low, hunk.from), Number.POSITIVE_INFINITY);
|
|
41
|
+
const to = cluster.reduce((high, hunk) => Math.max(high, hunk.to), 0);
|
|
42
|
+
unchanged(at, from);
|
|
43
|
+
at = Math.max(at, to);
|
|
44
|
+
const side = (name) => applied(base, from, to, cluster.filter((hunk) => hunk.side === name)).join("");
|
|
45
|
+
const original = base.slice(from, to).join("");
|
|
46
|
+
const mine = side("local");
|
|
47
|
+
const theirs = side("remote");
|
|
48
|
+
const kind = mine === original ? "remote" : theirs === original ? "local" : mine === theirs ? "both" : "conflict";
|
|
49
|
+
segments.push({ kind, line: from + 1, base: original, local: mine, remote: theirs });
|
|
50
|
+
}
|
|
51
|
+
unchanged(at, base.length);
|
|
52
|
+
return segments;
|
|
53
|
+
};
|
|
54
|
+
const decoded = (text) => Buffer.from(text, "latin1").toString("utf8");
|
|
55
|
+
/** The merge's bytes, and its segments as UTF-8 text a person reads. */
|
|
56
|
+
const resultOf = (lines) => {
|
|
57
|
+
const segments = lines.map((segment) => ({
|
|
58
|
+
...segment,
|
|
59
|
+
base: decoded(segment.base),
|
|
60
|
+
local: decoded(segment.local),
|
|
61
|
+
remote: decoded(segment.remote),
|
|
62
|
+
}));
|
|
63
|
+
const conflicts = segments.filter((segment) => segment.kind === "conflict");
|
|
64
|
+
if (conflicts.length)
|
|
65
|
+
return { conflicts, segments };
|
|
66
|
+
const text = lines.map((segment) => (segment.kind === "remote" ? segment.remote : segment.local)).join("");
|
|
67
|
+
return { merged: Buffer.from(text, "latin1"), segments };
|
|
68
|
+
};
|
|
69
|
+
const utf8 = (bytes) => {
|
|
70
|
+
const text = bytes.toString("utf8");
|
|
71
|
+
return Buffer.from(text, "utf8").equals(bytes) ? text : undefined;
|
|
72
|
+
};
|
|
73
|
+
const BOM = "";
|
|
74
|
+
const plain = (text) => (text.startsWith(BOM) ? text.slice(1) : text).replace(/\r\n/g, "\n");
|
|
75
|
+
/**
|
|
76
|
+
* Markdown that the line merge could not settle, merged by blocks: a checklist tick and a text edit on the same item
|
|
77
|
+
* no longer collide. Taken only when the remote's text is exactly what its blocks write over the base, so a change the
|
|
78
|
+
* blocks cannot see (front matter, a link definition, `_` for `*`) is never dropped; anything else stays a conflict.
|
|
79
|
+
*/
|
|
80
|
+
const mergeMarkdown = async (base, local, remote) => {
|
|
81
|
+
const [baseText, localText, remoteText] = [utf8(base), utf8(local), utf8(remote)];
|
|
82
|
+
if (baseText === undefined || localText === undefined || remoteText === undefined)
|
|
83
|
+
return undefined;
|
|
84
|
+
// The splice writes every line ending as CRLF once the file has one, which would change lines nobody edited.
|
|
85
|
+
if (/\r\n/.test(localText) && /(^|[^\r])\n/.test(localText))
|
|
86
|
+
return undefined;
|
|
87
|
+
const [baseBlocks, localBlocks, remoteBlocks] = await Promise.all([baseText, localText, remoteText].map((text) => markdownBlocks(plain(text))));
|
|
88
|
+
if (!baseBlocks || !localBlocks || !remoteBlocks)
|
|
89
|
+
return undefined;
|
|
90
|
+
if ((await spliceMarkdown(baseText, remoteBlocks)) !== remoteText)
|
|
91
|
+
return undefined;
|
|
92
|
+
const merged = mergeBlocks(baseBlocks, baseBlocks, localBlocks, remoteBlocks, undefined, adjoins);
|
|
93
|
+
if (merged.status !== "clean")
|
|
94
|
+
return undefined;
|
|
95
|
+
const text = await spliceMarkdown(localText, merged.blocks);
|
|
96
|
+
return text === undefined ? undefined : Buffer.from(text, "utf8");
|
|
97
|
+
};
|
|
98
|
+
/** Bytes that are no text a line merge can handle: a NUL, or a UTF-16 byte-order mark. */
|
|
99
|
+
const binary = (bytes) => bytes.includes(0) ||
|
|
100
|
+
(bytes.length >= 2 && ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff)));
|
|
101
|
+
/**
|
|
102
|
+
* Merges a text file both sides changed since `base`, the content of the last sync. Lines are compared as bytes
|
|
103
|
+
* (read as latin1, which maps each byte to one character), so any 8-bit encoding, line endings and a byte-order mark
|
|
104
|
+
* pass through unchanged. Markdown that conflicts by lines gets a second try by blocks. `segments` always describe the
|
|
105
|
+
* line merge, so a conflict can be shown.
|
|
106
|
+
*/
|
|
107
|
+
export const mergeText = async (path, base, local, remote) => {
|
|
108
|
+
if ([base, local, remote].some(binary)) {
|
|
109
|
+
const segment = {
|
|
110
|
+
kind: "conflict",
|
|
111
|
+
line: 1,
|
|
112
|
+
base: base.toString("utf8"),
|
|
113
|
+
local: local.toString("utf8"),
|
|
114
|
+
remote: remote.toString("utf8"),
|
|
115
|
+
};
|
|
116
|
+
return { conflicts: [segment], segments: [segment] };
|
|
117
|
+
}
|
|
118
|
+
const lines = (bytes) => linesOf(bytes.toString("latin1"));
|
|
119
|
+
const result = resultOf(mergeLines(lines(base), lines(local), lines(remote)));
|
|
120
|
+
if ("merged" in result || !MARKDOWN.has(posix.extname(path).toLowerCase()))
|
|
121
|
+
return result;
|
|
122
|
+
const merged = await mergeMarkdown(base, local, remote);
|
|
123
|
+
return merged ? { merged, segments: result.segments } : result;
|
|
124
|
+
};
|
|
125
|
+
/** The segments' text as one file, with Git's markers around each conflict; `remote` names the other side. */
|
|
126
|
+
export const conflictText = (segments, remote) => segments
|
|
127
|
+
.map((segment) => {
|
|
128
|
+
if (segment.kind !== "conflict")
|
|
129
|
+
return segment.kind === "remote" ? segment.remote : segment.local;
|
|
130
|
+
const block = (part) => (part && !part.endsWith("\n") ? `${part}\n` : part);
|
|
131
|
+
return (`<<<<<<< local\n${block(segment.local)}||||||| base\n${block(segment.base)}=======\n` +
|
|
132
|
+
`${block(segment.remote)}>>>>>>> ${remote}\n`);
|
|
133
|
+
})
|
|
134
|
+
.join("");
|