@trama-dev/runtime 0.4.0 → 0.5.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/dist/tree.js ADDED
@@ -0,0 +1,1409 @@
1
+ // What a directory holds — and the two things done with it: a copy is made
2
+ // somewhere else, and what a run did to the copy is carried back.
3
+ //
4
+ // Both rest on one reading of a tree. It says what is at every path under a
5
+ // directory — a file, a directory, a link, or something that is not content —
6
+ // or it throws. There is no entry it passes over: what a reading leaves out is
7
+ // taken, by whoever compares two readings, to have been removed.
8
+ import { accessSync, chmodSync, closeSync, constants, copyFileSync, lstatSync, mkdirSync, openSync, readdirSync, readSync, renameSync, rmdirSync, rmSync, statSync, symlinkSync, unlinkSync, } from "fs";
9
+ import { basename, dirname, isAbsolute, join, relative, sep } from "path";
10
+ import { identityIn, identityOf, linksOf, linkText, realRootOf, utf8Text } from "./path-guard.js";
11
+ import { stagedNameFor } from "./replace-file.js";
12
+ import { messageOf } from "./errors.js";
13
+ /** The path of the directory a tree is of. It is in no directory of the tree, and every other path is under it. */
14
+ const ITSELF = ".";
15
+ /** The order in which a path comes before every path under it. (As text "." comes after "-x", which is under it.) */
16
+ const inOrder = (a, b) => (a === b ? 0 : a === ITSELF || (b !== ITSELF && a < b) ? -1 : 1);
17
+ const NOT_CONTENT = { kind: "other" };
18
+ /** What is at a path — the path itself, not what a link there leads to. Undefined if nothing is. */
19
+ export function entryAt(path) {
20
+ const stat = lstatSync(path, { bigint: true, throwIfNoEntry: false });
21
+ if (!stat)
22
+ return undefined;
23
+ const mode = Number(stat.mode & 4095n);
24
+ const id = identityIn(stat);
25
+ if (stat.isFile()) {
26
+ // The time of the last change is the system's own: it moves when the file is written, replaced, or
27
+ // has its permissions changed, and no program can put it back. (The time of the last write can be.)
28
+ return { kind: "file", mode, size: Number(stat.size), stamp: `${id}:${stat.ctimeNs}:${stat.size}`, id };
29
+ }
30
+ if (stat.isDirectory())
31
+ return { kind: "dir", mode, id };
32
+ if (stat.isSymbolicLink()) {
33
+ let text;
34
+ try {
35
+ text = linkText(path);
36
+ }
37
+ catch (err) {
38
+ // No link is there any more: the place changed between the two questions, and is asked again.
39
+ const code = err.code;
40
+ if (code === "ENOENT" || code === "EINVAL")
41
+ return entryAt(path);
42
+ throw err;
43
+ }
44
+ return text === undefined ? NOT_CONTENT : { kind: "link", text, id };
45
+ }
46
+ return NOT_CONTENT;
47
+ }
48
+ /** Which file, directory or link an entry is — undefined of what is none. */
49
+ const idOf = (entry) => (entry === undefined || entry.kind === "other" ? undefined : entry.id);
50
+ /**
51
+ * Whether two entries are the same thing, unchanged. Nothing is the same as
52
+ * nothing. A directory is the same if it allows the same — what it holds is
53
+ * other paths. What is not content is never taken for the same: nothing is
54
+ * known of it that could be compared.
55
+ */
56
+ function same(a, b) {
57
+ if (a === undefined || b === undefined)
58
+ return a === b;
59
+ if (a.kind === "file" && b.kind === "file")
60
+ return a.stamp === b.stamp;
61
+ if (a.kind === "dir" && b.kind === "dir")
62
+ return a.mode === b.mode;
63
+ if (a.kind === "link" && b.kind === "link")
64
+ return a.text === b.text;
65
+ return false;
66
+ }
67
+ /** The names in a directory. One that is not text cannot be told from another, or looked up again: it throws. */
68
+ function namesIn(dir) {
69
+ return readdirSync(dir, "buffer").map((raw) => {
70
+ const name = utf8Text(raw);
71
+ if (name === undefined)
72
+ throw new Error(`${dir} holds a name that is not readable as text`);
73
+ return name;
74
+ });
75
+ }
76
+ const gone = (err) => err.code === "ENOENT";
77
+ /** Whether a refusal says that there is no such place: nothing is there, or the system takes no such name. */
78
+ const noSuchPlace = (err) => ["ENOENT", "ENOTDIR", "ENAMETOOLONG"].includes(err.code ?? "");
79
+ /**
80
+ * Go through a directory and everything under it, a directory before what it
81
+ * holds. `visit` is given each path, what is there, and where that is; if it
82
+ * returns false the entry is left out, and not gone into.
83
+ *
84
+ * Whatever goes wrong, the walk throws — with one exception, which is not
85
+ * something going wrong: a directory may be in use while it is read, and what
86
+ * has gone by the time it is come to is not there. (A directory that goes
87
+ * after it was looked at is one with nothing in it.)
88
+ */
89
+ function walk(root, visit) {
90
+ const into = (dir, prefix, names) => {
91
+ for (const name of names) {
92
+ const at = join(dir, name);
93
+ const entry = entryAt(at);
94
+ if (!entry)
95
+ continue;
96
+ const path = prefix + name;
97
+ if (visit(path, entry, at) === false || entry.kind !== "dir")
98
+ continue;
99
+ let inside;
100
+ try {
101
+ inside = namesIn(at);
102
+ }
103
+ catch (err) {
104
+ if (gone(err))
105
+ continue;
106
+ throw err;
107
+ }
108
+ into(at, `${path}/`, inside);
109
+ }
110
+ };
111
+ const itself = entryAt(root);
112
+ if (itself && visit(ITSELF, itself, root) === false)
113
+ return;
114
+ into(root, "", namesIn(root)); // (which says so, if no directory is there)
115
+ }
116
+ /** Whether two files hold the same bytes. Read a piece at a time: a file may be larger than can be held at once. */
117
+ function sameBytes(one, other) {
118
+ const fill = (fd, into) => {
119
+ let have = 0;
120
+ for (let got; have < into.length && (got = readSync(fd, into, have, into.length - have, null)) > 0;)
121
+ have += got;
122
+ return have;
123
+ };
124
+ const a = openSync(one, "r");
125
+ try {
126
+ const b = openSync(other, "r");
127
+ try {
128
+ const mine = Buffer.allocUnsafe(1 << 16);
129
+ const theirs = Buffer.allocUnsafe(1 << 16);
130
+ for (;;) {
131
+ const have = fill(a, mine);
132
+ if (fill(b, theirs) !== have || mine.compare(theirs, 0, have, 0, have) !== 0)
133
+ return false;
134
+ if (have < mine.length)
135
+ return true;
136
+ }
137
+ }
138
+ finally {
139
+ closeSync(b);
140
+ }
141
+ }
142
+ finally {
143
+ closeSync(a);
144
+ }
145
+ }
146
+ /** What a directory is and holds. The directory must be there, and all of it readable. */
147
+ export function readTree(dir) {
148
+ const tree = new Map();
149
+ walk(realRootOf(dir), (path, entry) => { tree.set(path, entry); });
150
+ return tree;
151
+ }
152
+ /**
153
+ * Make `toDir` — an empty directory — what `fromDir` is: allowing what it
154
+ * allows and holding what it holds. Returns what that was: the directory, and
155
+ * each entry as it was when it was copied. `leaveOut` names
156
+ * what is no part of it; those entries are neither copied nor returned.
157
+ *
158
+ * What a directory holds is its files, its directories with what they allow,
159
+ * and its links. What is not content is not carried over, though the tree
160
+ * returned says it is there. The directory itself is one of its directories
161
+ * in this: the copy is left allowing what it allows — to its owner, and to
162
+ * everybody else. (So a copy that is to be nobody else's is made in a
163
+ * directory that is nobody else's.)
164
+ *
165
+ * A link is made to name, in the copy, what it names here: the same place in
166
+ * the copy if that is under `fromDir`, and the same place outside it if not.
167
+ * Most links do that as they are written, and are kept so — but for the
168
+ * letters of a name the copy does not have as it is written, where its file
169
+ * system tells apart what this one takes for one name. Not one whose
170
+ * way steps out of the directory over its top with "..", or into it from
171
+ * outside: from the copy's place those words lead somewhere else — or back
172
+ * into the original, where what was done through the link in the copy would
173
+ * be done to the original. Such a link is rewritten. If its way comes to the
174
+ * directory from outside and stays in it, what it says from there on is said
175
+ * of the directory, and is kept, said of the copy: only the part that comes
176
+ * to the directory is replaced, and a link of the directory on the rest of
177
+ * the way is still passed through in the copy, wherever it then leads. If
178
+ * not — the way ends outside — the link is made to name the place itself.
179
+ * A link whose way cannot be followed here names nothing that can be told,
180
+ * and is not carried over. Whether it can be is asked of this reading, and of
181
+ * the system: a link the system will not follow — too many links on its way,
182
+ * a name too long — is not carried either, whatever it says, since a copy of
183
+ * it could come to be followed where a link on its way is rewritten shorter.
184
+ * Nor is one whose rewritten words the system will not have for a link.
185
+ *
186
+ * The tree returned is read in the same pass that copies, each entry before
187
+ * it is copied. So the copy never holds what the tree does not know of; and
188
+ * an entry that changes while it is copied is in the tree as it was before,
189
+ * which is the side to err on — it will not be taken for untouched later.
190
+ */
191
+ export function copyTree(fromDir, toDir, leaveOut = () => false) {
192
+ const from = realRootOf(fromDir);
193
+ const to = realRootOf(toDir);
194
+ const tree = new Map();
195
+ const dirs = [];
196
+ /** What was copied, by what it is: the paths the copy has it under. (A file may have several names.) */
197
+ const copiedAs = new Map();
198
+ const copiedIs = (id, path) => { copiedAs.set(id, [...(copiedAs.get(id) ?? []), path]); };
199
+ /** The links whose words name things of the directory, to be read again when all of the copy is there. */
200
+ const written = [];
201
+ const read = linksOf(from);
202
+ /**
203
+ * What a link must say in the copy — undefined if what it names cannot be
204
+ * told — and, of that, the `words` that name things of the directory: said
205
+ * from `dir`, after what stands `before` them.
206
+ */
207
+ const inCopy = (link, text) => {
208
+ try {
209
+ try {
210
+ statSync(link);
211
+ }
212
+ catch (err) {
213
+ if (!gone(err))
214
+ throw err; // (that nothing is there yet is no refusal to go there)
215
+ }
216
+ const lead = read.names(dirname(link), text);
217
+ // (Words from the top that never come to the directory name nothing of it: they need no second reading,
218
+ // which for such words is a long one.)
219
+ if (!lead.strays)
220
+ return { says: text, own: isAbsolute(text) ? undefined : { before: "", dir: dirname(link), words: text } };
221
+ // A way that strays and does not come home ends outside the directory: the place is itself, from anywhere.
222
+ if (lead.home === undefined)
223
+ return { says: lead.to };
224
+ return { says: to + lead.home, own: lead.home === "" ? undefined : { before: to + sep, dir: from, words: lead.home.slice(sep.length) } };
225
+ }
226
+ catch {
227
+ return undefined;
228
+ }
229
+ };
230
+ /**
231
+ * Words of a link, each name in the letters the copy knows it by. A file
232
+ * system may take "data" for the name of what its directory lists as
233
+ * "Data", and the copy's need not: there the words would lead nowhere. So a
234
+ * name the copy does not have as it is written, and has under the name its
235
+ * directory lists here — the one that reads the same — is written as that. Where each name is looked up is
236
+ * asked of the words before it; which directory of the copy that is, and
237
+ * what the copy calls the thing, is known from the copying: a name of
238
+ * something that is not in the copy is left as it is.
239
+ */
240
+ const spelled = (dir, words) => {
241
+ const steps = words.split(sep);
242
+ return steps.map((step, i) => {
243
+ if (step === "" || step === "." || step === "..")
244
+ return step;
245
+ try {
246
+ const at = i === 0 ? dir : read.names(dir, steps.slice(0, i).join(sep) + sep).to;
247
+ const [inDir] = copiedAs.get(identityOf(at) ?? "") ?? [];
248
+ if (inDir === undefined || identityOf(join(to, inDir, step)) !== undefined)
249
+ return step;
250
+ const names = (copiedAs.get(identityOf(join(at, step)) ?? "") ?? []).filter((path) => dirname(path) === inDir).map((path) => basename(path));
251
+ return names.find((other) => reads(other) === reads(step)) ?? step;
252
+ }
253
+ catch {
254
+ return step;
255
+ }
256
+ }).join(sep);
257
+ };
258
+ walk(from, (path, entry, source) => {
259
+ if (leaveOut(source, entry))
260
+ return false;
261
+ const copied = join(to, path);
262
+ tree.set(path, entry);
263
+ if (entry.kind === "dir") {
264
+ if (path !== ITSELF)
265
+ mkdirSync(copied); // (the copy itself is there: it is what was given)
266
+ dirs.push({ copied, mode: entry.mode });
267
+ copiedIs(entry.id, path);
268
+ }
269
+ else if (entry.kind === "file") {
270
+ try {
271
+ // The copy is empty where this goes: a name that is there already is two names of the directory taken for one.
272
+ copyFileSync(source, copied, constants.COPYFILE_EXCL);
273
+ copiedIs(entry.id, path);
274
+ }
275
+ catch (err) {
276
+ if (!gone(err) || lstatSync(source, { throwIfNoEntry: false }))
277
+ throw err;
278
+ tree.delete(path); // gone since it was looked at
279
+ }
280
+ }
281
+ else if (entry.kind === "link") {
282
+ const said = inCopy(source, entry.text);
283
+ try {
284
+ if (said === undefined)
285
+ tree.set(path, NOT_CONTENT);
286
+ else {
287
+ symlinkSync(said.says, copied);
288
+ copiedIs(entry.id, path);
289
+ if (said.own)
290
+ written.push({ copied, says: said.says, ...said.own });
291
+ }
292
+ }
293
+ catch (err) {
294
+ // Words made for the copy that are too long for a link: they cannot be said here at all.
295
+ if (said?.says === entry.text || err.code !== "ENAMETOOLONG")
296
+ throw err;
297
+ tree.set(path, NOT_CONTENT);
298
+ }
299
+ }
300
+ });
301
+ // The letters of each link's words, now that the copy can be asked what it has.
302
+ for (const { copied, says, before, dir, words } of written) {
303
+ const spelt = before + spelled(dir, words);
304
+ if (spelt === says)
305
+ continue;
306
+ unlinkSync(copied);
307
+ try {
308
+ symlinkSync(spelt, copied);
309
+ }
310
+ catch (err) {
311
+ symlinkSync(says, copied);
312
+ if (err.code !== "ENAMETOOLONG")
313
+ throw err;
314
+ }
315
+ }
316
+ // Last, and the deepest first: a directory that may not be written to has to be filled before it is closed.
317
+ for (const { copied, mode } of dirs.reverse())
318
+ chmodSync(copied, mode);
319
+ return tree;
320
+ }
321
+ /** A name as it reads, whatever its letters: what tells one name of a file from another, where a file system takes several for one. */
322
+ const reads = (name) => name.normalize("NFD").toLowerCase();
323
+ /**
324
+ * The name a directory lists for what it knows as `name` — which need not be
325
+ * the letters given: a file system may take "Program.ts" and "program.ts"
326
+ * for one name. Undefined if nothing is there.
327
+ *
328
+ * Found by what is there. A file may have more names than one in a directory,
329
+ * and then the one meant is the one that reads the same as the name given.
330
+ */
331
+ function nameListed(dir, name) {
332
+ const what = identityOf(join(dir, name));
333
+ if (what === undefined)
334
+ return undefined;
335
+ const names = namesIn(dir);
336
+ if (names.includes(name))
337
+ return name;
338
+ const its = names.filter((other) => identityOf(join(dir, other)) === what);
339
+ return its.find((other) => reads(other) === reads(name)) ?? its[0];
340
+ }
341
+ /**
342
+ * The path a reading of `dir` has for a place: each step by the name its
343
+ * directory lists for it, and "." for the directory itself. Undefined if
344
+ * nothing is there, or the place is not in `dir`. The place is named without
345
+ * links.
346
+ */
347
+ export function pathAsListed(dir, place) {
348
+ const root = realRootOf(dir);
349
+ const steps = relative(root, place).split(sep);
350
+ if (steps[0] === "")
351
+ return identityOf(root) === undefined ? undefined : ITSELF;
352
+ if (steps[0] === "..")
353
+ return undefined; // (outside: its first step up is there to be found, whatever the directory is)
354
+ let at = root;
355
+ for (const [i, step] of steps.entries()) {
356
+ const name = nameListed(at, step);
357
+ if (name === undefined)
358
+ return undefined;
359
+ at = join(at, steps[i] = name);
360
+ }
361
+ return steps.join("/");
362
+ }
363
+ /**
364
+ * Carry what a run did to a copy back into the directory it is a copy of.
365
+ *
366
+ * @param stagedDir - the copy, as the run left it
367
+ * @param realDir - the directory it was copied from
368
+ * @param before - the copy as it was before the run (readTree)
369
+ * @param seed - the real directory as it was when the copy was made (copyTree)
370
+ * @param together - things that are one thing to the caller: each list the
371
+ * `id`s (see Entry) of the files, links and directories that are one
372
+ *
373
+ * What the run did is where the copy differs from what it was: a file, a
374
+ * directory or a link made, removed, changed, or put where something of
375
+ * another kind was; permissions changed — those of the directory itself
376
+ * among them, which is a directory like any in it: only that it is neither
377
+ * made nor removed. Each difference is carried over on
378
+ * one condition: the place in the real directory is still as it was when the
379
+ * copy was made — and so is the directory it is in. If not, somebody else —
380
+ * the user, another run of the same project — has been there since, and
381
+ * theirs is kept. A place that already holds what the run left needs nothing
382
+ * done, whoever made it so.
383
+ *
384
+ * There is no path this leaves out. Where the caller has itself put
385
+ * something into the real directory since the copy was made, it says so in
386
+ * `seed`: the place is then as the seed has it, and what the run did there is
387
+ * carried over like anything else.
388
+ *
389
+ * All of that is found out before anything is done. What cannot arrive is
390
+ * then left alone, with everything under it; and a directory the run removed,
391
+ * or put something else in the place of, goes only if all that is in it goes
392
+ * — if anything in it stays, or it holds something the run never saw, the
393
+ * directory stays whole. What the run moved — a file, a link, a directory —
394
+ * goes from where it was only if it arrives where the run moved it: what it
395
+ * holds is not to be in neither place. (What was moved is known by its `id`,
396
+ * see Entry. What the run copied and then removed is a new file, and is not
397
+ * known to be the old one's.) And what the caller says is one thing — a
398
+ * link, say, with the file that makes it lead somewhere: the things in one
399
+ * list of `together`, each known by what it is, at every path where the copy
400
+ * had it before the run or has it now — arrives together or not at all: if
401
+ * one of those paths is left alone, nothing is done at any of them. A part
402
+ * the run left as it was has nothing to arrive, but the rest leans on it: if
403
+ * it is not, in the project, as it was when the copy was made, that is told
404
+ * of it, and the rest does not arrive. (So that all this holds where the
405
+ * system refuses in the doing, what is done at such a path is only what can
406
+ * be taken back: a file there is not written into but has the new one put in
407
+ * its place, and what is to go from there is moved aside first, as what is
408
+ * taken the place of is. A directory among them that stays a directory is
409
+ * not left alone with the rest — what else the run did in it could not be
410
+ * taken for undone with it — but what it was to be left allowing does not
411
+ * arrive either, and that is told of it. And a part the run left as it was,
412
+ * and that is not so in the project, is told of besides, as that: nothing
413
+ * under it is left alone for it — and nothing is told of it where nothing is
414
+ * held back for it.) So what is returned as not arrived is as it
415
+ * was, at that path and under it. That holds where the system refuses, in
416
+ * the doing, what had been found possible — see how it is done, below — as
417
+ * long as it does not also refuse to put back what was moved aside; then
418
+ * the report says where that is.
419
+ *
420
+ * Some things are told of besides, which are not that. What was moved aside
421
+ * to go, or made ready and not needed, and which the system will not have
422
+ * removed, is told of at the name it is left under — a path that is none of
423
+ * the run's. A directory the run removed which the system will not remove,
424
+ * or not with all that was in it, holds what is left, as it would had the
425
+ * run removed it there, and is told of so. A directory or a file that could
426
+ * not be given, at the end, what it is to allow is told of for that: what
427
+ * it holds has arrived, unless that is told of itself. A file that could not
428
+ * be written into, and had a new one put in its place, is told of for that.
429
+ * (If the system will not have the new one put there either, the file did
430
+ * not arrive, and the report says that what it held may be damaged, and
431
+ * where what it was to hold is.)
432
+ *
433
+ * Finding out is looking, and a directory that is closed cannot be looked
434
+ * into. One of the real directory's — or the directory itself — is opened
435
+ * for it, as it is for what is then done in it, and one of the copy's is
436
+ * opened to be read: both are this merge's to open. Each is left, at the end,
437
+ * allowing what the run left it allowing — or, if that did not arrive, what
438
+ * it allowed. (One that somebody else gave other permissions since the copy
439
+ * was made is theirs, and is not opened: nothing is made or removed in it.)
440
+ *
441
+ * A path is a name, and the real directory has the last word on its names:
442
+ * its file system may take "Notes.txt" and "notes.txt" for one. A path of
443
+ * the tree whose place holds something, though the directory does not list
444
+ * the name as the tree spells it, is such a second spelling — the run
445
+ * spelled a name anew, or made one beside another on a file system that
446
+ * tells them apart. To a tree that is one entry removed and another made; in
447
+ * the real directory the two are one place, and removing the one would
448
+ * remove the other. Neither is touched: nothing is done to what is there
449
+ * under any name the run changed, and each is told of as not arrived. (What
450
+ * is there is known by what it is. All the names of a file that has several
451
+ * are therefore left, where one would have done.) If what is there is a
452
+ * directory, nothing is done in it either: a path through it is a path
453
+ * through the other, and what the run left under the two names is in one
454
+ * place. And two names the run made where nothing was, which the directory
455
+ * turns out to take for one when the second is put there: neither is put.
456
+ * (That can only be seen in the putting. If the first was not put, for a
457
+ * reason of its own, the second is — and what is told of the first is then
458
+ * true of the name as the run spelled it, not as the directory takes it.)
459
+ * The same is asked of the way to a path: a directory on it that the real
460
+ * one no longer lists as the tree spells it — somebody spelled it anew — is
461
+ * not the tree's directory any more, and nothing is done in it.
462
+ *
463
+ * What is to be done is done so that nothing is lost by its being done in
464
+ * part. A file or a link that is to be where something is, is made beside
465
+ * the place first. Then what the run made is made, a directory before what
466
+ * goes in it. What is in the place of it is not removed but moved aside,
467
+ * under a name of its own beside the place, and what was made beside the
468
+ * place is moved in. (Only a directory that stays a directory, and a file
469
+ * the run wrote into that can be written into, stay and are changed where
470
+ * they are. A file that is written into has what it is to hold made beside
471
+ * it first all the same: if the system will not have the writing — which it
472
+ * may have begun — that takes its place.) Where the system will not have a thing done, that
473
+ * thing is left alone like what was found impossible beforehand, with what
474
+ * follows from it — and what follows may be that something already done is
475
+ * not to stand: what the run moved from there did not arrive where it went.
476
+ * Then what was put there is removed again, and what was moved aside comes
477
+ * back. Only when all that is settled does what was moved aside go for good,
478
+ * and what the run removed, where it is. (A runner that is stopped in the
479
+ * middle leaves what it had moved aside, or made ready, where it is: under
480
+ * names that begin with .trama-tmp-.) It is where the run ended that is
481
+ * carried over, not the steps by which it got there.
482
+ *
483
+ * A file the run wrote into is written into, if it may be, and stays the
484
+ * file it is — as does one that holds what the run left already, and has
485
+ * only what it allows changed. Where the run put another file in the place,
486
+ * or the file may not be written into, or the system will not have it
487
+ * written into after all, a new one is put in its place — and then a second
488
+ * name of the old file is none of the new one, and holds whatever the
489
+ * writing left. A link is written as the run wrote it
490
+ * — the run took its copy for the directory itself — unless its way comes to
491
+ * the copy from outside: by the copy's full path, or out of the copy and
492
+ * back in by its name. What such a link says from there on is said of the
493
+ * real directory, wherever that leads from there. So a link the copy
494
+ * was given in other words than the directory's own (see copyTree), if the
495
+ * run moved it, is merged in those words: it names what the run found it to
496
+ * name, which is not always what the directory's own words would name from
497
+ * the new place. And a link the run made that climbs out of its directory
498
+ * with ".." and does not come back says the same in the real directory, and
499
+ * names from there what it names from there.
500
+ *
501
+ * Nothing is thrown. What could not be carried over is returned, each path
502
+ * with the reason, so that a run whose work did not all arrive is not passed
503
+ * off as one whose work did. Under a path that did not arrive, what was not
504
+ * looked at for that reason is not listed: it is as it was, with the path.
505
+ */
506
+ export function mergeTree(stagedDir, realDir, before, seed, together = []) {
507
+ let copy;
508
+ let real;
509
+ const after = new Map();
510
+ try {
511
+ real = realRootOf(realDir);
512
+ // The directory is the one that was copied — which the seed knows by what it is. Where it is gone, or another
513
+ // is at its path by now, there is nothing here that the run's work is the work on.
514
+ const itself = entryAt(real), copied = seed.get(ITSELF);
515
+ if (itself?.kind !== "dir")
516
+ return [{ path: ITSELF, why: "the project is no longer there; nothing was merged into it" }];
517
+ if (copied?.kind === "dir" && copied.id !== itself.id) {
518
+ return [{ path: ITSELF, why: "another directory is at the project's path than the one that was copied; nothing was merged into it" }];
519
+ }
520
+ }
521
+ catch (err) {
522
+ return [{ path: ITSELF, why: `the project could not be come to (${messageOf(err)}); nothing was merged into it` }];
523
+ }
524
+ try {
525
+ copy = realRootOf(stagedDir);
526
+ walk(copy, (path, entry, at) => {
527
+ after.set(path, entry); // as the run left it
528
+ if (entry.kind === "dir" && (entry.mode & 0o500) !== 0o500)
529
+ chmodSync(at, entry.mode | 0o500);
530
+ });
531
+ }
532
+ catch (err) {
533
+ // What the run left cannot be told. Nothing is merged — least of all as a removal of what cannot be seen.
534
+ return [{ path: ITSELF, why: `what the run left could not be read (${messageOf(err)}); none of it was merged` }];
535
+ }
536
+ /**
537
+ * Whether what is at a path, though it looks the same, is something the run
538
+ * moved there from another place. (Something new that looks the same is no
539
+ * change: nothing depends on its being there.)
540
+ */
541
+ const wasSomewhere = new Set([...before.values()].map(idOf));
542
+ const movedHere = (path) => {
543
+ const id = idOf(after.get(path));
544
+ return id !== undefined && id !== idOf(before.get(path)) && wasSomewhere.has(id);
545
+ };
546
+ // Sorted, a path comes before every path under it.
547
+ const changed = [...new Set([...before.keys(), ...after.keys()])]
548
+ .filter((path) => !same(before.get(path), after.get(path)) || movedHere(path))
549
+ .sort(inOrder);
550
+ const isChanged = new Set(changed);
551
+ /**
552
+ * What is one thing to the caller (see `together`), as paths: by each path
553
+ * where the copy has a part of such a thing — had it before the run, or has
554
+ * it now — the things it is a part of, each as all its paths.
555
+ */
556
+ const partOf = new Map();
557
+ if (together.length > 0) {
558
+ const where = new Map();
559
+ for (const tree of [before, after]) {
560
+ for (const [path, entry] of tree) {
561
+ const id = idOf(entry);
562
+ if (id === undefined)
563
+ continue;
564
+ const those = where.get(id);
565
+ if (those)
566
+ those.add(path);
567
+ else
568
+ where.set(id, new Set([path]));
569
+ }
570
+ }
571
+ for (const ids of together) {
572
+ const paths = [...new Set(ids.flatMap((id) => [...(where.get(id) ?? [])]))];
573
+ for (const part of paths) {
574
+ const those = partOf.get(part);
575
+ if (those)
576
+ those.push(paths);
577
+ else
578
+ partOf.set(part, [paths]);
579
+ }
580
+ }
581
+ }
582
+ const parts = [...partOf.keys()].sort();
583
+ /** What did not arrive, and why: found out beforehand, or — once things are being done — told by the system. */
584
+ const refused = new Map();
585
+ /** Whether a path is under one of some paths. */
586
+ const underOne = (path, of) => {
587
+ for (let end = path.lastIndexOf("/"); end !== -1; end = path.lastIndexOf("/", end - 1)) {
588
+ if (of.has(path.slice(0, end)))
589
+ return true;
590
+ }
591
+ return path !== ITSELF && of.has(ITSELF);
592
+ };
593
+ /** Whether a path is one of those that did not arrive, or under one. */
594
+ const leftAlone = (path) => refused.has(path) || underOne(path, refused);
595
+ const said = linksOf(copy);
596
+ /** What a link the run left at a path says in the real directory. */
597
+ const inReal = (path, text) => {
598
+ const rest = said.sinceRoot(join(copy, dirname(path)), text);
599
+ return rest === undefined ? text : real + rest;
600
+ };
601
+ /** The file the run left at a path. One it left unreadable is read all the same. */
602
+ const stagedFile = (path) => {
603
+ const staged = join(copy, path);
604
+ const left = after.get(path);
605
+ if (left?.kind === "file" && (left.mode & 0o400) === 0)
606
+ chmodSync(staged, left.mode | 0o400);
607
+ return staged;
608
+ };
609
+ /** What the run left at a path, as it is to be in the real directory — refused if it is nothing that can be put there. */
610
+ const wanted = (path, is) => {
611
+ if (is.kind === "other") {
612
+ throw new Error("the run left there what is not content — a pipe, a socket, a device, a link whose words are not text — and it is not carried into the project");
613
+ }
614
+ return is.kind === "link" ? { ...is, text: inReal(path, is.text) } : is;
615
+ };
616
+ /** Whether a file of the real directory holds what the file the run left at a path holds. One that may not be read is not known to. */
617
+ const sameAlready = new Map();
618
+ const holdsBytes = (there, place, want, path) => {
619
+ if (there.kind !== "file" || there.size !== want.size)
620
+ return false;
621
+ let known = sameAlready.get(path);
622
+ if (known === undefined) {
623
+ try {
624
+ known = sameBytes(stagedFile(path), place);
625
+ }
626
+ catch {
627
+ known = false;
628
+ }
629
+ sameAlready.set(path, known);
630
+ }
631
+ return known;
632
+ };
633
+ /** Whether a place already holds what is wanted at a path. */
634
+ const holds = (there, place, want, path) => {
635
+ if (want.kind === "file")
636
+ return there?.kind === "file" && there.mode === want.mode && holdsBytes(there, place, want, path);
637
+ if (want.kind === "dir")
638
+ return there?.kind === "dir" && there.mode === want.mode;
639
+ return want.kind === "link" && there?.kind === "link" && there.text === want.text;
640
+ };
641
+ /**
642
+ * Directories of the real one opened to be looked into or changed, and
643
+ * those this merge makes: what each is to be left allowing — what it
644
+ * allowed, until what the run left it allowing arrives.
645
+ */
646
+ const opened = new Set();
647
+ /**
648
+ * Each with which directory it is, what it is to be left allowing, and what
649
+ * this merge has it allowing for now (-1: not known — it was made, and
650
+ * could not then be given what it was to allow while it is filled).
651
+ */
652
+ const toClose = new Map();
653
+ const open = (dir) => {
654
+ if (opened.has(dir))
655
+ return;
656
+ const place = join(real, dir);
657
+ const there = entryAt(place);
658
+ if (there?.kind === "dir") {
659
+ const closing = { id: identityOf(place), mode: there.mode, has: there.mode };
660
+ toClose.set(dir, closing);
661
+ if ((there.mode | 0o700) !== there.mode) {
662
+ chmodSync(place, there.mode | 0o700);
663
+ closing.has = there.mode | 0o700;
664
+ }
665
+ } // (if it is no directory, what is done in it will say so)
666
+ opened.add(dir); // only now: if it could not be opened, the next to need it open is told so too
667
+ };
668
+ /** Whether a deed is at a directory that is to be a directory: what it allows is all that changes there. */
669
+ const staysADirectory = ({ want, there }) => want?.kind === "dir" && there?.kind === "dir";
670
+ /** Whether a deed is at a directory that is to go — removed, or with something else in its place. */
671
+ const goesAsADirectory = ({ want, there }) => there?.kind === "dir" && want?.kind !== "dir";
672
+ /** Directories the run made that are to be made here: they are not in the real directory yet. */
673
+ const toMake = new Set();
674
+ /**
675
+ * Whether the way to a directory of the tree is the real directory's own:
676
+ * every step of it a directory, none a link put there since. (Asked as far
677
+ * as the way exists: a directory still to be made is made by this merge.)
678
+ */
679
+ const own = new Map();
680
+ const ownWay = (dir) => {
681
+ if (dir === ITSELF)
682
+ return true;
683
+ if (toMake.has(dir))
684
+ return ownWay(dirname(dir));
685
+ let known = own.get(dir);
686
+ if (known === undefined) {
687
+ known = ownWay(dirname(dir)) && entryAt(join(real, dir))?.kind === "dir" && spells(dirname(dir), basename(dir));
688
+ own.set(dir, known);
689
+ }
690
+ return known;
691
+ };
692
+ /** Whether a directory the run did not change is as it was when the copy was made. Asked once, before it is opened. */
693
+ const asItWas = new Map();
694
+ const unchanged = (dir) => {
695
+ let known = asItWas.get(dir);
696
+ if (known === undefined)
697
+ asItWas.set(dir, known = same(entryAt(join(real, dir)), seed.get(dir)));
698
+ return known;
699
+ };
700
+ /** Whether a directory lists a name as it is spelled. */
701
+ const listed = new Map();
702
+ const spells = (dir, name) => {
703
+ let names = listed.get(dir);
704
+ if (!names)
705
+ listed.set(dir, names = new Set(namesIn(join(real, dir))));
706
+ return names.has(name);
707
+ };
708
+ /** What is in the real directory under a name that is not the directory's own for it: by what it is, the tree's path. */
709
+ const otherwise = new Map();
710
+ /**
711
+ * What is to be done at a path — nothing, if the place is as the run left
712
+ * it already. Throws if it cannot be done: with why, which is all that is
713
+ * done about it. It looks, and opens a directory to look; no more. (So
714
+ * every directory in which something is then done is open by then.)
715
+ */
716
+ const decide = (path) => {
717
+ const was = before.get(path);
718
+ const is = after.get(path);
719
+ const place = join(real, path);
720
+ const dir = dirname(path);
721
+ let there;
722
+ /** That somebody changed the directory it is in — which is said only once it is known that something needs doing there. */
723
+ let notInIt;
724
+ if (path === ITSELF) {
725
+ // The directory itself is in no directory of the tree: it is where it is, by the name it was given.
726
+ there = entryAt(place);
727
+ }
728
+ else if (!toMake.has(dir)) {
729
+ // (In a directory still to be made there is nothing — whatever is, for now, at the place of that directory.)
730
+ if (!ownWay(dir)) {
731
+ // No way that is the directory's own leads there any more. What the run removed is, then, not there —
732
+ // unless something is, by the way as it is now: under another spelling of a directory, or through a
733
+ // link put in its place. That is somebody's, and is left; but it is not gone, and that is said.
734
+ if (!is) {
735
+ let found;
736
+ try {
737
+ found = entryAt(place);
738
+ }
739
+ catch (err) {
740
+ if (!noSuchPlace(err))
741
+ throw err;
742
+ }
743
+ if (!found)
744
+ return undefined;
745
+ }
746
+ throw new Error("the directory it is in is no longer there in the project, by that name");
747
+ }
748
+ // The directory it is in. One the run changed has its own turn, before this; any other must be as it was.
749
+ if (!isChanged.has(dir) && !unchanged(dir)) {
750
+ notInIt = new Error(dir === ITSELF ? "what the project's own directory allows was changed meanwhile" : `what ${dir} allows was changed in the project meanwhile`);
751
+ }
752
+ let byItsName;
753
+ try {
754
+ // It is looked into as it will be changed: opened, if it is closed — unless that it is closed is somebody
755
+ // else's doing. (What the run left as it was is only looked at, which a directory that held it allows.)
756
+ if (!notInIt && isChanged.has(path))
757
+ open(dir);
758
+ there = entryAt(place);
759
+ byItsName = !there || spells(dir, basename(path));
760
+ }
761
+ catch (err) {
762
+ throw notInIt ?? err;
763
+ }
764
+ if (!byItsName) {
765
+ const what = identityOf(place);
766
+ if (what)
767
+ otherwise.set(what, path);
768
+ throw new Error("the project's file system takes that name for one that is there already, spelled otherwise: what is there is left as it was");
769
+ }
770
+ }
771
+ if (!is && !there)
772
+ return undefined;
773
+ // What the run left as it was, and is as it was in the project, needs nothing done. (It is looked at because
774
+ // it is part of what is one thing: see the loop below.)
775
+ if (!isChanged.has(path) && same(there, seed.get(path)))
776
+ return undefined;
777
+ const want = is && wanted(path, is);
778
+ // A place that holds what the run left needs nothing done — whoever made it so, and whatever became of its
779
+ // directory, as long as it can still be looked into: one that somebody closed is not opened to find out.
780
+ if (want && holds(there, place, want, path))
781
+ return undefined;
782
+ if (notInIt)
783
+ throw notInIt;
784
+ if (!was && there)
785
+ throw new Error("something else is at that place in the project");
786
+ if (was && !same(there, seed.get(path))) {
787
+ throw new Error(want ? "it was changed or removed in the project meanwhile" : "the run removed it, but it was changed in the project meanwhile");
788
+ }
789
+ if (goesAsADirectory({ want, there })) {
790
+ // It is to go — and can, if it holds nothing but what this merge removes from it.
791
+ const goes = (child) => before.has(child) && !after.has(child);
792
+ const kept = namesIn(place).find((name) => !goes(`${path}/${name}`));
793
+ if (kept !== undefined)
794
+ throw new Error(`the run removed it, but it holds something in the project that is not removed with it (${kept})`);
795
+ }
796
+ if (want?.kind === "dir" && there?.kind !== "dir")
797
+ toMake.add(path);
798
+ return { path, place, want, there };
799
+ };
800
+ const deeds = [];
801
+ /** Parts of things that the run left as they were, and that are not so in the project: by the path, why. */
802
+ const amiss = new Map();
803
+ // What the run changed — and the parts of what is one thing that it did not: nothing is to be done there, but
804
+ // the rest of the thing leans on their being there as they were.
805
+ for (const path of [...new Set([...changed, ...parts])].sort(inOrder)) {
806
+ if (leftAlone(path))
807
+ continue;
808
+ try {
809
+ const deed = decide(path);
810
+ if (deed)
811
+ deeds.push(deed);
812
+ }
813
+ catch (err) {
814
+ // (A part the run left as it was did not fail to arrive: nothing under it is left alone for its sake.)
815
+ (isChanged.has(path) ? refused : amiss).set(path, messageOf(err));
816
+ }
817
+ }
818
+ // What the real directory takes for one name is one thing there: nothing is done to it under any name — nor,
819
+ // if it is a directory, in it: a path through it is a path through the other.
820
+ if (otherwise.size > 0) {
821
+ /** The path the run left that is taken for a name of a directory, or of one it is in — if any is. */
822
+ const takenFor = new Map();
823
+ const through = (dir) => {
824
+ if (dir === ITSELF)
825
+ return undefined;
826
+ if (!takenFor.has(dir))
827
+ takenFor.set(dir, otherwise.get(identityOf(join(real, dir)) ?? "") ?? through(dirname(dir)));
828
+ return takenFor.get(dir);
829
+ };
830
+ for (const { path, place, there } of deeds) {
831
+ if (path === ITSELF || leftAlone(path))
832
+ continue;
833
+ try {
834
+ const other = there && otherwise.get(identityOf(place) ?? "");
835
+ const above = other === undefined ? through(dirname(path)) : undefined;
836
+ if (other !== undefined) {
837
+ refused.set(path, `the run left ${other}, which the project's file system takes for a name of this, or of what is one file with it: it is left as it was`);
838
+ }
839
+ else if (above !== undefined) {
840
+ refused.set(path, `the run left ${above}, which the project's file system takes for a name of a directory this is in: it is left as it was`);
841
+ }
842
+ }
843
+ catch (err) {
844
+ refused.set(path, messageOf(err));
845
+ }
846
+ }
847
+ }
848
+ /** Where each file, directory and link is, as the run left things. */
849
+ const nowAt = new Map();
850
+ for (const [path, is] of after) {
851
+ const id = idOf(is);
852
+ if (id === undefined)
853
+ continue;
854
+ const those = nowAt.get(id);
855
+ if (those)
856
+ those.push(path);
857
+ else
858
+ nowAt.set(id, [path]);
859
+ }
860
+ /**
861
+ * Where the run has what is at a deed's place, if that is to go from there
862
+ * or be taken the place of. (If it is there still, among other places, it
863
+ * has not been moved from there. A directory that stays a directory is not
864
+ * one that goes, whichever directory the run has there: what it holds is
865
+ * seen to path by path.)
866
+ */
867
+ const wentTo = (deed) => {
868
+ const id = staysADirectory(deed) ? undefined : idOf(before.get(deed.path));
869
+ return (id === undefined ? undefined : nowAt.get(id)) ?? [];
870
+ };
871
+ const deedAt = new Map(deeds.map((deed) => [deed.path, deed]));
872
+ /** By each place the run moved something to, the deeds at the places it moved it from. */
873
+ const cameFrom = new Map();
874
+ /** Of each deed at a place the run moved something from, how many of the places it moved it to may yet arrive. */
875
+ const mayArriveAt = new Map();
876
+ for (const deed of deeds) {
877
+ const all = wentTo(deed);
878
+ if (all.length > 0)
879
+ mayArriveAt.set(deed, all.length);
880
+ for (const to of all) {
881
+ let those = cameFrom.get(to);
882
+ if (!those)
883
+ cameFrom.set(to, those = []);
884
+ those.push(deed);
885
+ }
886
+ }
887
+ /** The places the run moved something to, in order. */
888
+ const arrivals = [...cameFrom.keys()].sort();
889
+ /**
890
+ * What follows from what did not arrive, for what was to go from where it
891
+ * was — until nothing more follows. What the run moved goes from where it
892
+ * was only if it arrives where it went: what it holds is not to be in
893
+ * neither place. And a directory goes only if all that is in it goes. Each
894
+ * can bring the other about: what stays in a directory keeps the directory,
895
+ * and a directory that stays is in the way of what was moved to its place.
896
+ * (Each path that did not arrive is followed up once, and each place
897
+ * something was moved to is counted out once.)
898
+ */
899
+ const followedUp = new Set();
900
+ const countedOut = new Set();
901
+ /** Of the things that are one (see `partOf`), those of which a part has not arrived, or is not as it was. */
902
+ const broken = new Set();
903
+ /**
904
+ * The directories that stay directories, of such things: by the path, what
905
+ * the thing did not arrive for. A directory like that is not left alone
906
+ * with the rest — what else was done in it could not be taken for undone
907
+ * with it — but what it was to be left allowing does not arrive.
908
+ */
909
+ const heldBack = new Map();
910
+ /** Of paths in order, those that are a given path or under it. */
911
+ const atOrUnder = (sorted, path) => {
912
+ const under = `${path}/`;
913
+ const found = sorted[firstNotBefore(sorted, path)] === path ? [path] : [];
914
+ for (let at = firstNotBefore(sorted, under); at < sorted.length && sorted[at].startsWith(under); at++)
915
+ found.push(sorted[at]);
916
+ return found;
917
+ };
918
+ const settle = () => {
919
+ const toFollowUp = [...refused.keys()].filter((path) => !followedUp.has(path));
920
+ const refuse = (path, why) => {
921
+ if (leftAlone(path))
922
+ return;
923
+ refused.set(path, why());
924
+ toFollowUp.push(path);
925
+ };
926
+ /**
927
+ * The things a path is part of do not arrive: it did not, or is not as it
928
+ * was. Says whether anything is held back for that. (What follows from a
929
+ * directory's being held back is followed up in turn, not gone into: a
930
+ * chain of things may be as long as the caller makes it.)
931
+ */
932
+ const without = (first, how) => {
933
+ let any = false;
934
+ const toDo = [[first, how]];
935
+ for (let next; (next = toDo.pop()) !== undefined;) {
936
+ const [part, which] = next;
937
+ // All the paths of the things it is part of, in order: a path under one that is left alone is left alone
938
+ // with it.
939
+ const others = new Set();
940
+ for (const paths of partOf.get(part) ?? []) {
941
+ if (broken.has(paths))
942
+ continue;
943
+ broken.add(paths);
944
+ for (const other of paths)
945
+ others.add(other);
946
+ }
947
+ for (const other of [...others].sort(inOrder)) {
948
+ const deed = deedAt.get(other);
949
+ if (!deed || leftAlone(other))
950
+ continue;
951
+ any = true;
952
+ if (!staysADirectory(deed)) {
953
+ refuse(other, () => `it is one thing with ${part}, ${which}: it is left as it was`);
954
+ }
955
+ else if (!heldBack.has(other)) {
956
+ heldBack.set(other, `${part}, ${which}`);
957
+ // (And what else it is one thing with does not arrive without what it was to allow.)
958
+ toDo.push([other, "which is not given what it was to allow"]);
959
+ }
960
+ }
961
+ }
962
+ return any;
963
+ };
964
+ // A part the run left as it was, and that is not so in the project. (It is told of only if something is
965
+ // held back for it: where the rest is in place already, nothing was left undone.)
966
+ for (const [part, why] of amiss) {
967
+ if (without(part, "which is not as it was in the project"))
968
+ tell(part, `the run left it as it was, but ${why}: what it is one thing with did not arrive`);
969
+ }
970
+ amiss.clear();
971
+ for (let path; (path = toFollowUp.pop()) !== undefined;) {
972
+ followedUp.add(path);
973
+ const stays = path;
974
+ // The directories it is in, which were to go.
975
+ for (let end = path.lastIndexOf("/"); end !== -1; end = path.lastIndexOf("/", end - 1)) {
976
+ const above = deedAt.get(path.slice(0, end));
977
+ if (above && goesAsADirectory(above))
978
+ refuse(above.path, () => `the run removed it, but not all that is in it can go (${stays})`);
979
+ }
980
+ // What was moved to it, or to somewhere under it, has not arrived there.
981
+ for (const to of atOrUnder(arrivals, path)) {
982
+ if (countedOut.has(to))
983
+ continue;
984
+ countedOut.add(to);
985
+ for (const from of cameFrom.get(to)) {
986
+ const left = mayArriveAt.get(from) - 1;
987
+ mayArriveAt.set(from, left);
988
+ if (left === 0)
989
+ refuse(from.path, () => `the run moved what was here to ${wentTo(from).join(", ")}, which did not arrive: it is left as it was`);
990
+ }
991
+ }
992
+ // What it, or something under it, is one thing with does not arrive without it.
993
+ for (const part of atOrUnder(parts, path))
994
+ without(part, part === path ? "which did not arrive" : `which is under ${path}, which did not arrive`);
995
+ }
996
+ };
997
+ // --- Doing it ---
998
+ /** The deeds, by the directory each is in. */
999
+ const inDir = new Map();
1000
+ for (const deed of deeds) {
1001
+ const dir = dirname(deed.path);
1002
+ let those = inDir.get(dir);
1003
+ if (!those)
1004
+ inDir.set(dir, those = []);
1005
+ those.push(deed);
1006
+ }
1007
+ /** What there is to say besides what did not arrive (see above): by the path, what. */
1008
+ const besides = new Map();
1009
+ const tell = (path, what) => besides.set(path, besides.has(path) ? `${besides.get(path)} — and ${what}` : what);
1010
+ /** A place of the real directory, as a path of it. */
1011
+ const pathOf = (place) => relative(real, place).split(sep).join("/") || ITSELF;
1012
+ const leftover = (path, failed) => `what was at ${path}, and was to go, is here: the system would not have it all removed (${messageOf(failed)})`;
1013
+ /** Remove what was made beside a place and is not going to be moved in. What will not go is told of. Throws nothing. */
1014
+ const discard = (made, madeFor) => {
1015
+ try {
1016
+ rmSync(made, { force: true });
1017
+ }
1018
+ catch (err) {
1019
+ // It is told of if it is there — or cannot be known not to be.
1020
+ let there = true;
1021
+ try {
1022
+ there = lstatSync(made, { throwIfNoEntry: false }) !== undefined;
1023
+ }
1024
+ catch (cannot) {
1025
+ there = !noSuchPlace(cannot);
1026
+ }
1027
+ if (there)
1028
+ tell(pathOf(made), `it was made ready for ${madeFor}, and the system would not have it removed (${messageOf(err)})`);
1029
+ }
1030
+ };
1031
+ /** Make a file or a link the run left beside its place, under a name of its own, ready to be moved in. */
1032
+ const beside = (path, want, place) => {
1033
+ const made = stagedNameFor(place);
1034
+ try {
1035
+ if (want.kind === "link") {
1036
+ symlinkSync(want.text, made);
1037
+ }
1038
+ else if (want.kind === "file") {
1039
+ copyFileSync(stagedFile(path), made, constants.COPYFILE_EXCL);
1040
+ if (modeAt(made) !== want.mode)
1041
+ chmodSync(made, want.mode);
1042
+ }
1043
+ }
1044
+ catch (err) {
1045
+ discard(made, path);
1046
+ throw err;
1047
+ }
1048
+ return made;
1049
+ };
1050
+ /** What has been made beside its place and is yet to be moved in. */
1051
+ const ready = new Map();
1052
+ /**
1053
+ * What was at a place and has been moved aside, under a name of its own
1054
+ * beside it, for what the run left to take the place: by the path, where
1055
+ * it is now. It is kept until all that follows from its going is known to
1056
+ * have arrived, and comes back if not.
1057
+ */
1058
+ const aside = new Map();
1059
+ /** The places where this merge has put something in the place of what was there, or of nothing. */
1060
+ const put = new Set();
1061
+ /** What this merge has put where nothing was: by what it is, the path. */
1062
+ const putAnew = new Map();
1063
+ /** The directories that are not, now, where their path says: by the path, where they are — or were last, if they have gone since. */
1064
+ const elsewhere = new Map();
1065
+ const setAside = ({ path, place, there }) => {
1066
+ const kept = stagedNameFor(place);
1067
+ renameSync(place, kept);
1068
+ if (there?.kind === "dir")
1069
+ elsewhere.set(path, kept);
1070
+ return kept;
1071
+ };
1072
+ /**
1073
+ * Remove from a directory what the run removed from it — all it held when
1074
+ * that was looked at; more than that is not removed — and say what the
1075
+ * system would not have removed, if anything. What will go, goes, whatever
1076
+ * would not go before it.
1077
+ */
1078
+ const emptied = (dir, at) => {
1079
+ let failed;
1080
+ for (const inIt of inDir.get(dir) ?? []) {
1081
+ if (!inIt.there || aside.has(inIt.path))
1082
+ continue; // (what was moved aside to go has gone, or is told of where it is)
1083
+ const its = join(at, basename(inIt.path));
1084
+ try {
1085
+ if (inIt.there.kind === "dir") {
1086
+ const inThat = emptied(inIt.path, its);
1087
+ failed ??= inThat;
1088
+ rmdirSync(its);
1089
+ }
1090
+ else {
1091
+ unlinkSync(its);
1092
+ }
1093
+ }
1094
+ catch (err) {
1095
+ failed ??= err;
1096
+ }
1097
+ }
1098
+ return failed;
1099
+ };
1100
+ /** The directories that were to go and have been seen to as one, with all that was under them. */
1101
+ const seenTo = new Set();
1102
+ /** Remove what the run removed from a directory, and the directory, where it is. Says what the system would not have removed, if anything. */
1103
+ const removed = (deed, at) => {
1104
+ seenTo.add(deed.path);
1105
+ let failed = emptied(deed.path, at);
1106
+ try {
1107
+ rmdirSync(at);
1108
+ }
1109
+ catch (err) {
1110
+ failed ??= err;
1111
+ }
1112
+ return failed;
1113
+ };
1114
+ /**
1115
+ * The places where what is there stays and takes what the run left into
1116
+ * itself: a directory that is to be a directory; or a file the run wrote
1117
+ * into — the same file, afterwards, not another put in its place — which
1118
+ * may be written into, or holds what the run left already. Anything else
1119
+ * that is there is taken the place of. So is a file that is one thing with
1120
+ * other paths: what is written into cannot be taken back, should the rest
1121
+ * of the thing not arrive, and what is put in a place can.
1122
+ */
1123
+ const takes = new Set();
1124
+ for (const { path, place, want, there } of deeds) {
1125
+ if (!want || !there || leftAlone(path))
1126
+ continue;
1127
+ const itself = !partOf.has(path) && want.kind === "file" && there.kind === "file" && idOf(before.get(path)) === idOf(after.get(path))
1128
+ && (mayBeWrittenTo(place) || holdsBytes(there, place, want, path));
1129
+ if (itself || staysADirectory({ want, there }))
1130
+ takes.add(path);
1131
+ }
1132
+ /** Do one step of each deed that still stands. What the system will not have done is left alone. */
1133
+ const each = (list, step) => {
1134
+ for (const deed of list) {
1135
+ if (leftAlone(deed.path))
1136
+ continue;
1137
+ try {
1138
+ step(deed);
1139
+ }
1140
+ catch (err) {
1141
+ refused.set(deed.path, messageOf(err));
1142
+ }
1143
+ }
1144
+ };
1145
+ settle();
1146
+ // What is to be put where something is, is made first, beside the place: if the system will not have it made,
1147
+ // nothing has been touched for its sake. (Also what a file is to take into itself: see below.)
1148
+ each(deeds, ({ path, place, want, there }) => {
1149
+ if (!there || !want || want.kind === "dir")
1150
+ return;
1151
+ if (takes.has(path) && want.kind === "file" && holdsBytes(there, place, want, path))
1152
+ return;
1153
+ ready.set(path, beside(path, want, place));
1154
+ });
1155
+ settle(); // (so that what follows from what could not be made ready is not first done, and then undone)
1156
+ // What the run made, or changed — a directory before what goes in it. What is in the place of it is moved aside.
1157
+ each(deeds, (deed) => {
1158
+ const { path, place, want, there } = deed;
1159
+ if (!want) {
1160
+ // What is to go, and is one thing with other paths, is moved aside like what is taken the place of: it
1161
+ // comes back if the rest of the thing does not arrive. (Unless it has gone aside already, in its directory.)
1162
+ if (there && partOf.has(path) && !underOne(path, elsewhere))
1163
+ aside.set(path, setAside(deed));
1164
+ return;
1165
+ }
1166
+ const made = ready.get(path);
1167
+ if (takes.has(path)) {
1168
+ if (want.kind === "dir") {
1169
+ // What it allows is what changed: it is opened like any other, and closed to that. (Not one whose thing
1170
+ // does not arrive: nothing is done to that for its own sake.)
1171
+ if (heldBack.has(path))
1172
+ return;
1173
+ open(path);
1174
+ const closing = toClose.get(path);
1175
+ if (!closing)
1176
+ throw new Error("it is no longer a directory in the project");
1177
+ // Of what is one thing, whether the system will have it changed is to be known now, while the rest can
1178
+ // still be taken back — not at the end, when it is closed. (It is changed now as far as leaves it open.)
1179
+ if (partOf.has(path)) {
1180
+ chmodSync(place, want.mode | 0o700);
1181
+ closing.has = want.mode | 0o700;
1182
+ }
1183
+ closing.mode = want.mode;
1184
+ return;
1185
+ }
1186
+ if (want.kind !== "file")
1187
+ return;
1188
+ if (made !== undefined) {
1189
+ // It is written into, and stays the file it is. Should the system not have that — and it may have begun,
1190
+ // and what the file held be gone — the new file, which is whole beside it, takes its place, and that is
1191
+ // told of: it is another file then, and what was another name of the old one is none of this one.
1192
+ try {
1193
+ copyFileSync(stagedFile(path), place);
1194
+ }
1195
+ catch (err) {
1196
+ try {
1197
+ renameSync(made, place);
1198
+ }
1199
+ catch (again) {
1200
+ ready.delete(path); // (it is not removed: it is the only whole one there is)
1201
+ throw new Error(`${messageOf(err)} — and a new file could not be put in its place either (${messageOf(again)}): what it held may be damaged, and what it was to hold is beside it, as ${basename(made)}`);
1202
+ }
1203
+ ready.delete(path);
1204
+ tell(path, `it could not be written into (${messageOf(err)}): a new file, holding what the run left, was put in its place`);
1205
+ }
1206
+ if (ready.delete(path))
1207
+ discard(made, path);
1208
+ }
1209
+ try {
1210
+ if (modeAt(place) !== want.mode)
1211
+ chmodSync(place, want.mode);
1212
+ }
1213
+ catch (err) {
1214
+ tell(path, `what it is to allow (${want.mode.toString(8)}) could not be set (${messageOf(err)}); what it holds arrived`);
1215
+ }
1216
+ return;
1217
+ }
1218
+ if (there)
1219
+ aside.set(path, setAside(deed));
1220
+ try {
1221
+ if (want.kind === "dir") {
1222
+ mkdirSync(place);
1223
+ put.add(path);
1224
+ const closing = { id: identityOf(place), mode: want.mode, has: -1 };
1225
+ toClose.set(path, closing);
1226
+ chmodSync(place, want.mode | 0o700);
1227
+ closing.has = want.mode | 0o700;
1228
+ }
1229
+ else if (made !== undefined) {
1230
+ renameSync(made, place);
1231
+ ready.delete(path);
1232
+ put.add(path);
1233
+ }
1234
+ else if (want.kind === "link") {
1235
+ symlinkSync(want.text, place);
1236
+ put.add(path);
1237
+ }
1238
+ else if (want.kind === "file") {
1239
+ copyFileSync(stagedFile(path), place, constants.COPYFILE_EXCL);
1240
+ put.add(path);
1241
+ if (modeAt(place) !== want.mode)
1242
+ chmodSync(place, want.mode);
1243
+ }
1244
+ }
1245
+ catch (err) {
1246
+ // Where nothing was, and something is in the way now that this merge put there itself, under another path:
1247
+ // the real directory takes the two names for one. That could not be seen while neither was there. Neither
1248
+ // is put there — the other is taken back, with what follows from that.
1249
+ if (!there && !put.has(path)) {
1250
+ let other;
1251
+ try {
1252
+ other = putAnew.get(identityOf(place) ?? "");
1253
+ }
1254
+ catch {
1255
+ // (what cannot be looked at is not known to be that)
1256
+ }
1257
+ if (other !== undefined) {
1258
+ refused.set(other, `the run left ${path} too, which the project's file system takes for the same name: neither is put there`);
1259
+ throw new Error(`the run left ${other} too, which the project's file system takes for the same name: neither is put there`);
1260
+ }
1261
+ }
1262
+ throw err;
1263
+ }
1264
+ if (!there) {
1265
+ const what = identityOf(place);
1266
+ if (what !== undefined)
1267
+ putAnew.set(what, path);
1268
+ }
1269
+ });
1270
+ settle();
1271
+ // What was moved aside: where what took its place stands, it goes; where that did not stand after all — the
1272
+ // system would not have it put there, or what was moved from there did not arrive where the run moved it — what
1273
+ // was put there goes, and it comes back. The deepest first.
1274
+ for (const deed of [...deeds].reverse()) {
1275
+ const { path, place, want, there } = deed;
1276
+ const kept = aside.get(path);
1277
+ if (!leftAlone(path)) {
1278
+ if (kept === undefined)
1279
+ continue;
1280
+ let failed;
1281
+ try {
1282
+ if (there?.kind === "dir")
1283
+ failed = removed(deed, kept);
1284
+ else
1285
+ unlinkSync(kept);
1286
+ }
1287
+ catch (err) {
1288
+ failed = err;
1289
+ }
1290
+ if (failed !== undefined)
1291
+ tell(pathOf(kept), leftover(path, failed));
1292
+ }
1293
+ else if (kept !== undefined || put.has(path)) {
1294
+ try {
1295
+ // Only what this merge put there goes — of a directory, the directory, once what was put in it has gone.
1296
+ if (put.has(path)) {
1297
+ if (want?.kind === "dir") {
1298
+ rmdirSync(place);
1299
+ toClose.delete(path); // (it is gone: there is nothing of it to close)
1300
+ }
1301
+ else {
1302
+ unlinkSync(place);
1303
+ }
1304
+ }
1305
+ if (kept !== undefined) {
1306
+ renameSync(kept, place);
1307
+ elsewhere.delete(path);
1308
+ }
1309
+ }
1310
+ catch (err) {
1311
+ const where = kept === undefined ? "" : `: what was there is beside it, as ${basename(kept)}`;
1312
+ refused.set(path, `${refused.get(path) ?? "it is in what did not arrive"} — and it could not be put back as it was (${messageOf(err)})${where}`);
1313
+ }
1314
+ }
1315
+ }
1316
+ // And what the run removed, where it is: nothing waits for it any more, and nothing is to take its place. Of a
1317
+ // directory the system will not have removed, or not with all that was in it, what is left is there — as it
1318
+ // would be had the run removed it there.
1319
+ each(deeds, (deed) => {
1320
+ const { path, place, want, there } = deed;
1321
+ if (want || !there || aside.has(path) || underOne(path, seenTo))
1322
+ return;
1323
+ if (there.kind !== "dir")
1324
+ return void unlinkSync(place);
1325
+ const failed = removed(deed, place);
1326
+ if (failed !== undefined)
1327
+ tell(path, `the run removed it, and the system would not have it removed, or not all that was in it (${messageOf(failed)}): what is left is there`);
1328
+ });
1329
+ // What was made ready and never moved in is not left lying there.
1330
+ for (const [path, made] of ready)
1331
+ discard(made, path);
1332
+ // What a directory was to be left allowing, of a thing that did not arrive, does not arrive: it is closed to
1333
+ // what it allowed.
1334
+ for (const [path, what] of heldBack) {
1335
+ const { want, there } = deedAt.get(path);
1336
+ if (leftAlone(path) || want?.kind !== "dir" || there?.kind !== "dir")
1337
+ continue;
1338
+ const closing = toClose.get(path);
1339
+ if (closing)
1340
+ closing.mode = there.mode;
1341
+ tell(path, `what it was to allow (${want.mode.toString(8)}) is one thing with ${what}: it is left allowing what it allowed`);
1342
+ }
1343
+ // The directories that this merge has allowing something else than they are to be left allowing are closed — the
1344
+ // deepest first, each where it is now, and only if it is that directory: at the place of one that is gone there
1345
+ // may be something else by now.
1346
+ const placeNow = (path) => {
1347
+ for (let end = path.length; end !== -1; end = path.lastIndexOf("/", end - 1)) {
1348
+ const moved = elsewhere.get(path.slice(0, end));
1349
+ if (moved !== undefined)
1350
+ return moved + path.slice(end);
1351
+ }
1352
+ return join(real, path);
1353
+ };
1354
+ for (const [path, { id, mode, has }] of [...toClose].sort(([a], [b]) => inOrder(b, a))) {
1355
+ if (has === mode)
1356
+ continue;
1357
+ const place = placeNow(path);
1358
+ try {
1359
+ if (id === undefined || identityOf(place) !== id)
1360
+ continue;
1361
+ }
1362
+ catch (err) {
1363
+ // Where there is no such place there is nothing to close. Where it cannot be come to, it may be there, open.
1364
+ if (!gone(err) && err.code !== "ENOTDIR") {
1365
+ tell(pathOf(place), `it was opened, and cannot be come to to be given back what it is to allow (${mode.toString(8)}): ${messageOf(err)}`);
1366
+ }
1367
+ continue;
1368
+ }
1369
+ try {
1370
+ if (modeAt(place) !== mode)
1371
+ chmodSync(place, mode);
1372
+ }
1373
+ catch (err) {
1374
+ // What it was to be left allowing did not arrive, or could not be put back. What is in it is another matter.
1375
+ const why = `what it is to allow (${mode.toString(8)}) could not be set (${messageOf(err)})`;
1376
+ const at = pathOf(place);
1377
+ if (refused.has(at))
1378
+ refused.set(at, `${refused.get(at)} — and ${why}`);
1379
+ else
1380
+ tell(at, `${why}; what is in it is told of by itself, if it did not arrive`);
1381
+ }
1382
+ }
1383
+ // What is told: what did not arrive, and what there is to say besides. (Every path that was left alone by
1384
+ // itself, with its reason: where two of them are a directory and a path in it, each is the other's reason
1385
+ // as often as not, and neither is left out for the other.)
1386
+ return [...refused, ...besides].map(([path, why]) => ({ path, why }));
1387
+ }
1388
+ /** Where, in a list in order, the first entry is that does not come before a given one. */
1389
+ function firstNotBefore(list, given) {
1390
+ let low = 0;
1391
+ for (let high = list.length; low < high;) {
1392
+ const middle = (low + high) >> 1;
1393
+ if (list[middle] < given)
1394
+ low = middle + 1;
1395
+ else
1396
+ high = middle;
1397
+ }
1398
+ return low;
1399
+ }
1400
+ const mayBeWrittenTo = (path) => {
1401
+ try {
1402
+ accessSync(path, constants.W_OK);
1403
+ return true;
1404
+ }
1405
+ catch {
1406
+ return false;
1407
+ }
1408
+ };
1409
+ const modeAt = (path) => lstatSync(path).mode & 0o7777;