- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/commands.ts?version=261&format=json
682 linesFirst import 74% · review 14% · codex-prose-authorship-1 11% · rename 1% · infra-split 1%Last change codex-prose-authorship-1 in version 108, 8 versions changed it
You're reading version 261. The newest is 318, and 1 version since then changed this file.
1// The abso commands other than `hook`: init, join, record, publish, sync, run
2// and status. Each returns what to print and the exit code, so tests can call
3// them directly.
5import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6import { join } from "node:path";
7// The engine's own key, so both sides match spellings the same way (#49). Not in core.ts: the edit mod installs core.ts alone.
8import {
9 type Api,
10 type Collision,
11 type FileChange,
12 type MergedLine,
13 type News,
14 newsLines,
15 type SyncAnswer,
16} from "./api.ts";
17import { bool, type Parsed, str, UsageError } from "./args.ts";
18import { blobOf, keptWholeAs, MAX_BLOB_BYTES, readKnownBlobs, writeKnownBlobs } from "./blobs.ts";
19import { type Env, EXIT, heard, type Output, open } from "./command-env.ts";
20import { findRoot, isReader } from "./config.ts";
21import { spellingText, uncomposedText } from "./core.ts";
22import { pairRenames } from "./diff.ts";
23import type { BlobToSend, TurnedBinary } from "./folder.ts";
24import {
25 absolute,
26 forgetKnown,
27 isLocalOnly,
28 isPaused,
29 type LeftOut,
30 listKnown,
31 newFileEndings,
32 normalize,
33 pausedPath,
34 readKnown,
35 removeFile,
36 unrecorded,
37 withEndingsOf,
38 writeFileAtomic,
39 writeKnown,
40} from "./folder.ts";
41import { withFolderLock } from "./lock.ts";
42import type { OnDisk } from "./modes.ts";
43import { applyMode, type FullMode, foldModes, onDisk, PLAIN, readKnownModes, writeKnownModes } from "./modes.ts";
44import { batchRecordItems, sendRecordBatches } from "./record-batches.ts";
45import { type Refused, screenAnswer, unsafePath } from "./safety.ts";
47export {
48 knownPrep,
49 parallelScript,
50 type RunStamp,
51 runBisect,
52 runCommand,
53 runLogs,
54 runPrep,
55 runRun,
56 shellWord,
57 undoGitBashPaths,
58 withEntries,
59} from "./box-commands.ts";
60export { collisionsHeading, collisionText, mergedLinesText } from "./collision-text.ts";
61export { type Env, EXIT, newsText, type Output, open, plural, takeNews } from "./command-env.ts";
62export { runInit, runJoin } from "./join-commands.ts";
63export { runPublish, runSync, sameVersionHint } from "./publish-commands.ts";
64export { imageTokens, runFetch, runServe, runShot } from "./serve-commands.ts";
65export {
66 crlfOnly,
67 missingHere,
68 missingText,
69 openCollisionsText,
70 runFixEol,
71 runMv,
72 runReader,
73 runSettle,
74 runStatus,
75 staleModText,
76} from "./status-commands.ts";
78import { gitMarkerLine } from "./settle.ts";
79import { stateDir } from "./state-dir.ts";
81// --- record ---
83interface Recorded {
84 readonly sent: number;
85 /** The paths sent. */
86 readonly paths: readonly string[];
87 /** Those of them sent as deleted (gone from the folder). */
88 readonly deleted: readonly string[];
89 /** Those of them new to avcs: no copy recorded before (#37: a file a script made is easy to miss). */
90 readonly added?: readonly string[];
91 /** Nothing was sent because the folder is paused (abso pause). */
92 readonly paused?: boolean;
93 readonly changed: readonly string[] | number | undefined;
94 readonly news: News;
95 readonly leftOut: readonly LeftOut[];
96 readonly turnedBinary: readonly TurnedBinary[];
97 /** Text files sent that hold what looks like a git conflict (a merge git left unfinished, or markers typed by hand). */
98 readonly gitMarkers?: readonly { path: string; line: number }[];
99 /** Sent files whose path is long enough to fail on Windows, here or in another agent's folder. */
100 readonly longPaths?: readonly { path: string; length: number }[];
101}
103/** The warning for text files that turned binary: what, where, and what to do. Empty when there are none. */
104export function turnedBinaryText(list: readonly TurnedBinary[]): string[] {
105 return list.map(
106 (t) =>
107 `NOT SENT: ${t.path} was text and now has ${t.why} at line ${t.line} (byte ${t.offset}). The server keeps its last text, so the other agents still have the old file. Fix the file; or, if it is meant to be binary now, pass --binary ${t.path}.`,
108 );
109}
111/** The paths given with --binary (comma-separated, relative to the folder). */
112export function meantBinary(args: Parsed): Set<string> {
113 return new Set(
114 (str(args, "binary") ?? "")
115 .split(",")
116 .map((p) => p.trim().replace(/\\/g, "/").replace(/^\.\//, ""))
117 .filter((p) => p !== ""),
118 );
119}
121/** One line naming the files left out, or none. */
122export function leftOutText(leftOut: readonly LeftOut[]): string[] {
123 if (leftOut.length === 0) return [];
124 const why = (f: LeftOut) => `${f.path}${f.kept ? " (the server keeps its last version)" : ""}`;
125 return [
126 `Left out, over the server's ${MAX_BLOB_BYTES / 1024 / 1024} MB limit for one file: ${leftOut.map(why).join(", ")}.`,
127 ];
128}
130/**
131 * A command that left files out for size did not do everything it was asked: say so in the exit code too, so
132 * a script, CI or an agent cannot read "ok" while a file is missing. Other exits (refused, queued) stay as they are.
133 */
134export function withLeftOut(out: Output, leftOut: readonly LeftOut[]): Output {
135 if (leftOut.length === 0) return out;
136 const text = out.text.includes("Left out,") ? out.text : [out.text, ...leftOutText(leftOut)].join("\n");
137 return {
138 ...out,
139 text: `${text}\nExit ${EXIT.error}: ${leftOut.length} file${leftOut.length === 1 ? " was" : "s were"} not sent.`,
140 json: { ...out.json, leftOut },
141 exit: out.exit === undefined || out.exit === EXIT.ok ? EXIT.error : out.exit,
142 };
143}
145/** Upload binary files' bytes before the record or init that names them, each hash once. */
146export async function uploadBlobs(api: Api, blobs: ReadonlyMap<string, BlobToSend>): Promise<void> {
147 const seen = new Set<string>();
148 for (const b of blobs.values()) {
149 if (seen.has(b.sha)) continue;
150 seen.add(b.sha);
151 await api.putBlob(b.sha, b.bytes);
152 }
153}
155/**
156 * Whether the file at `rel` is as the server last gave it (or gone), so a sync
157 * may replace it: text compared with the known copy, a binary file by hash.
158 */
159function untouchedOnDisk(
160 root: string,
161 rel: string,
162 now: OnDisk | undefined,
163 knownBlobs: ReadonlyMap<string, string>,
164): boolean {
165 if (now === undefined) return true;
166 if (now.text !== undefined) {
167 const known = readKnown(root, rel);
168 // A file the server keeps whole (#46) is known by its hash.
169 return known !== undefined ? normalize(now.text) === known : keptWholeAs(normalize(now.text), knownBlobs.get(rel));
170 }
171 const blob = knownBlobs.get(rel);
172 const b = blobOf(absolute(root, rel));
173 return blob !== undefined && b !== undefined && "sha" in b && b.sha === blob;
174}
176/** Send what differs from the known copy. Used by record, publish and sync. */
177/** Record the folder, holding its lock (#51): known copies, modes and blobs are rewritten. */
178export async function recordFolder(
179 root: string,
180 api: Api,
181 all = false,
182 binary: ReadonlySet<string> = new Set(),
183): Promise<Recorded> {
184 return withFolderLock(root, "record", () => recordFolderLocked(root, api, all, binary));
185}
187async function recordFolderLocked(
188 root: string,
189 api: Api,
190 all: boolean,
191 binary: ReadonlySet<string>,
192): Promise<Recorded> {
193 if (isPaused(root))
194 return {
195 sent: 0,
196 paths: [],
197 deleted: [],
198 paused: true,
199 changed: [],
200 news: undefined,
201 leftOut: [],
202 turnedBinary: [],
203 };
204 // A reader records nothing (#37); the server would refuse it anyway.
205 if (isReader(root))
206 return { sent: 0, paths: [], deleted: [], changed: [], news: undefined, leftOut: [], turnedBinary: [] };
207 const { files, blobs, modes, leftOut, turnedBinary } = unrecorded(root, all, binary);
208 const paths = [...new Set([...files.keys(), ...blobs.keys(), ...Object.keys(modes)])].sort();
209 const knownBefore = new Set([...listKnown(root), ...readKnownBlobs(root).keys()]);
210 const added = paths.filter((p) => files.get(p) !== null && !knownBefore.has(p));
211 const sent = paths.length;
212 const deleted = [...files]
213 .filter(([, text]) => text === null)
214 .map(([rel]) => rel)
215 .sort();
216 if (sent === 0) return { sent: 0, paths, deleted, changed: [], news: undefined, leftOut, turnedBinary };
217 const items = paths.map((path) => ({
218 path,
219 ...(files.has(path) ? { text: files.get(path) } : {}),
220 ...(modes[path] !== undefined ? { mode: modes[path] } : {}),
221 ...(blobs.has(path) ? { blob: blobs.get(path)?.sha } : {}),
222 }));
223 const batches = batchRecordItems(items);
224 let batchBlobs = new Map<string, BlobToSend>();
225 const uploaded = new Set<string>();
226 const answers = await sendRecordBatches(
227 api,
228 batches,
229 async (batch) => {
230 batchBlobs = new Map(
231 batch.paths.flatMap((path) => {
232 const blob = blobs.get(path);
233 return blob === undefined ? [] : [[path, blob] as const];
234 }),
235 );
236 for (const [path, blob] of batchBlobs) {
237 if (uploaded.has(blob.sha)) continue;
238 await uploadBlobs(api, new Map([[path, blob]]));
239 uploaded.add(blob.sha);
240 }
241 },
242 async (batch, answer) => {
243 const batchFiles = new Map(Object.entries(batch.files));
244 // Commit known state only after this batch is confirmed; earlier successful batches stay committed on later failure.
245 for (const [rel, text] of batchFiles) if (text === null) forgetKnown(root, rel);
246 for (const [rel, text] of batchFiles) if (text !== null) writeKnown(root, rel, text);
247 const knownBlobs = readKnownBlobs(root);
248 if (Object.keys(batch.blobs).length > 0 || batch.paths.some((rel) => knownBlobs.has(rel))) {
249 for (const rel of new Set([...Object.keys(batch.files), ...Object.keys(batch.blobs)])) knownBlobs.delete(rel);
250 for (const [rel, sha] of Object.entries(batch.blobs)) {
251 forgetKnown(root, rel);
252 knownBlobs.set(rel, sha);
253 }
254 writeKnownBlobs(root, knownBlobs);
255 }
256 const gone = Object.entries(batch.files)
257 .filter(([, text]) => text === null)
258 .map(([rel]) => rel);
259 const knownModes = readKnownModes(root);
260 if (Object.keys(batch.modes).length > 0 || gone.some((rel) => knownModes.has(rel))) {
261 foldModes(knownModes, batch.modes, gone);
262 writeKnownModes(root, knownModes);
263 }
264 heard(root, [
265 ...newsLines(answer.news),
266 ...(answer.spelling ?? []).map(spellingText),
267 ...(answer.uncomposed ?? []).map(uncomposedText),
268 ]);
269 },
270 );
271 const changed = answers.flatMap((answer) => (Array.isArray(answer.changed) ? answer.changed : []));
272 const changedCount = answers.some((answer) => typeof answer.changed === "number")
273 ? answers.reduce(
274 (sum, answer) =>
275 sum +
276 (typeof answer.changed === "number"
277 ? answer.changed
278 : Array.isArray(answer.changed)
279 ? answer.changed.length
280 : 0),
281 0,
282 )
283 : changed;
284 const news = answers.flatMap((answer) => newsLines(answer.news));
285 const spelling = answers.flatMap((answer) => answer.spelling ?? []);
286 const uncomposed = answers.flatMap((answer) => answer.uncomposed ?? []);
287 const answer = { changed: changedCount, news, spelling, uncomposed };
288 const longPaths = longPathsOf(
289 root,
290 [...files].filter(([, text]) => text !== null).map(([path]) => path),
291 );
292 const gitMarkers = [...files]
293 .flatMap(([path, text]) => {
294 const line = text === null ? undefined : gitMarkerLine(text);
295 return line === undefined ? [] : [{ path, line }];
296 })
297 .sort((a, b) => (a.path < b.path ? -1 : 1));
298 return {
299 sent,
300 paths,
301 deleted,
302 added,
303 changed: answer.changed,
304 news: answer.news,
305 leftOut,
306 turnedBinary,
307 gitMarkers,
308 longPaths,
309 };
310}
312/** A note per file that holds what looks like a git conflict: abso records it as it is, as text, and does not call it a collision. */
313export function gitMarkerText(list: readonly { path: string; line: number }[] | undefined): string[] {
314 return (list ?? []).map(
315 (m) =>
316 `Note: ${m.path} has lines that look like a git conflict (from line ${m.line}). abso records them as ordinary text and will push them as they are. If a merge was left unfinished, fix the file first.`,
317 );
318}
320/** Windows stops at 260 characters for a whole path, and another agent's folder may sit deeper than this one. */
321const LONG_FULL_PATH = 240;
322const LONG_RELATIVE_PATH = 160;
324/** The sent files whose path will likely fail to write on Windows: the whole path is near its limit here, or the part inside the folder is already long. */
325export function longPathsOf(root: string, paths: Iterable<string>): { path: string; length: number }[] {
326 return [...paths]
327 .map((path) => ({ path, length: absolute(root, path).length }))
328 .filter((p) => p.length >= LONG_FULL_PATH || p.path.length >= LONG_RELATIVE_PATH)
329 .sort((a, b) => (a.path < b.path ? -1 : 1));
330}
332/** A note per long path: abso keeps it, but a Windows agent may not be able to write the file. */
333export function longPathText(list: readonly { path: string; length: number }[] | undefined): string[] {
334 return (list ?? []).map(
335 (p) =>
336 `Note: ${p.path} is ${p.path.length} characters inside the folder (${p.length} with this folder's location). Windows stops at 260 for a whole path, so an agent on Windows may be unable to write it. A shorter path avoids that.`,
337 );
338}
340/** "Recorded 3 files first: a, b, c." (names cut short past 8), or a word that the folder is paused. Empty when nothing was sent. */
341export function recordedFirst(r: Recorded): string[] {
342 if (r.paused) return ["Recording is paused (abso resume): your folder's changes were not sent first."];
343 if (r.sent === 0) return [];
344 return [`Recorded first: ${recordedList(r)}.`, ...gitMarkerText(r.gitMarkers), ...longPathText(r.longPaths)];
345}
347/** "2 changed (a, b), 3 deleted (x, y, z)": deletions said as such (#37: deleted files were read as edits). */
348function recordedList(r: Recorded): string {
349 const names = (list: readonly string[]) =>
350 list.length <= LISTED ? list.join(", ") : `${list.slice(0, LISTED).join(", ")}, and ${list.length - LISTED} more`;
351 const gone = new Set(r.deleted);
352 const fresh = new Set(r.added ?? []);
353 const changed = r.paths.filter((p) => !gone.has(p) && !fresh.has(p));
354 // New files are named in full: they are the ones a script made and nobody remembers (#37).
355 return [
356 ...(fresh.size > 0 ? [`${fresh.size} new (${[...fresh].join(", ")})`] : []),
357 ...(changed.length > 0 ? [`${changed.length} changed (${names(changed)})`] : []),
358 ...(r.deleted.length > 0 ? [`${r.deleted.length} deleted (${names(r.deleted)})`] : []),
359 ].join(", ");
360}
362export const READER_REFUSES =
363 "this folder is a reader: it records and pushes nothing (abso reader off makes it a writer again)";
365/** abso pause: send nothing from the folder (no hook, no record) until abso resume. */
366export async function runPause(_args: Parsed, env: Env): Promise<Output> {
367 const { root } = open(env);
368 const was = isPaused(root);
369 writeFileSync(pausedPath(root), `${new Date().toISOString()}\n`);
370 return {
371 text: `${was ? "Recording was already paused." : "Recording is paused."} The edit hook sends nothing, abso record refuses, and other commands skip recording first. abso run still sends the folder as it is to the box. abso resume ends it.`,
372 json: { paused: true },
373 };
374}
376export async function runResume(_args: Parsed, env: Env): Promise<Output> {
377 const { root } = open(env);
378 const was = isPaused(root);
379 rmSync(pausedPath(root), { force: true });
380 return {
381 text: was
382 ? "Recording again. Changes made while paused go at the next abso record (or push, pull, ...); abso status lists them."
383 : "Recording was not paused.",
384 json: { paused: false },
385 };
386}
388export async function runRecord(args: Parsed, env: Env): Promise<Output> {
389 if (isReader(findRoot(env.cwd) ?? env.cwd)) throw new UsageError(READER_REFUSES);
390 const { root, api } = open(env);
391 if (isPaused(root))
392 return {
393 exit: EXIT.refused,
394 text: "Not recorded: recording is paused. abso resume, then abso record.",
395 json: { paused: true },
396 };
397 const r = await recordFolder(root, api, bool(args, "all"), meantBinary(args));
398 const changed = Array.isArray(r.changed) ? r.changed.length : r.changed;
399 const text =
400 r.sent === 0
401 ? "Nothing to record: the folder matches what the server has."
402 : `Recorded ${recordedList(r)}${changed === undefined ? "" : `; ${changed} changed on the server`}.`;
403 return withLeftOut(
404 {
405 text: [
406 ...turnedBinaryText(r.turnedBinary),
407 text,
408 ...gitMarkerText(r.gitMarkers),
409 ...longPathText(r.longPaths),
410 ...leftOutText(r.leftOut),
411 ].join("\n"),
412 json: {
413 sent: r.sent,
414 changed: r.changed ?? null,
415 news: newsLines(r.news),
416 leftOut: r.leftOut,
417 turnedBinary: r.turnedBinary,
418 gitMarkers: r.gitMarkers ?? [],
419 longPaths: r.longPaths ?? [],
420 },
421 },
422 r.leftOut,
423 );
424}
426// --- writing answers into the folder ---
428/**
429 * Bring the folder to shared and set the agent's base. Writes only files that
430 * still match the known copy (or are new), so unrecorded work is never
431 * overwritten.
432 */
433export async function syncFolder(root: string, api: Api, full = false): Promise<Applied> {
434 return applyAnswer(root, api, await api.sync({ full }));
435}
437/** What writing a sync or switch answer into the folder did. */
438export interface Applied {
439 readonly version: number;
440 readonly written: string[];
441 readonly deleted: string[];
442 readonly kept: string[];
443 readonly dropped: string[];
444 readonly collisions: readonly Collision[];
445 /** Text files the answer deleted and wrote again under a new path, paired as git pairs renames. Each is in `written` and `deleted` too. */
446 readonly renamed: readonly { readonly from: string; readonly to: string }[];
447 /** Paths in the answer that were not touched: outside the folder, into .git/.claude/.avcs, a device, or through a link (safety.ts). */
448 readonly refused: readonly Refused[];
449 /** Lines both sides changed that the server merged item by item. */
450 readonly merged: readonly MergedLine[];
451 /** Files a sync couldn't write here, this one or an earlier one, still stale (#51): path -> when and why. */
452 readonly unwritten: Readonly<Record<string, Unwritten>>;
453}
455/** How many names a summary line shows before "and N more". */
456export const LISTED = 8;
457/** How far back an empty publish looks for this agent's last publish. */
458export const FOLDER_LOG_LIMIT = 200;
460/**
461 * The files a sync or switch changed. A line per kind, with the names cut
462 * short past LISTED (a big sync used to print a line per file); --verbose
463 * gives a line per file.
464 */
465export function changedFilesText(
466 command: string,
467 written: readonly string[],
468 deleted: readonly string[],
469 renamed: readonly { readonly from: string; readonly to: string }[],
470 verbose: boolean,
471): string[] {
472 const moves = renamed.map((r) => `${r.from} -> ${r.to}`);
473 if (verbose)
474 return [
475 ...written.map((f) => ` updated ${f}`),
476 ...deleted.map((f) => ` deleted ${f}`),
477 ...moves.map((m) => ` renamed ${m}`),
478 ];
479 const some = (names: readonly string[]) =>
480 names.length <= LISTED
481 ? names.join(", ")
482 : `${names.slice(0, LISTED).join(", ")}, and ${names.length - LISTED} more`;
483 return [
484 ...(written.length > 0 ? [` updated: ${some(written)}`] : []),
485 ...(deleted.length > 0 ? [` deleted: ${some(deleted)}`] : []),
486 ...(moves.length > 0 ? [` renamed: ${some(moves)}`] : []),
487 ...([written, deleted, moves].some((l) => l.length > LISTED)
488 ? [` (abso ${command} --verbose lists every file)`]
489 : []),
490 ];
491}
493/** A file a sync couldn't write (#51): the server takes the folder to have `version`'s text, so no later sync sends it again. */
494export interface Unwritten {
495 readonly version: number;
496 readonly why: string;
497}
499const UNWRITTEN_FILE = "unwritten.json";
501/** Files earlier syncs couldn't write here, kept in .avcs/unwritten.json until a write of them works. */
502export function readUnwritten(root: string): Record<string, Unwritten> {
503 try {
504 return JSON.parse(readFileSync(join(stateDir(root), UNWRITTEN_FILE), "utf8")) as Record<string, Unwritten>;
505 } catch {
506 return {};
507 }
508}
510/** Status's line for them, and sync's for ones an earlier sync named. */
511export function unwrittenText(
512 unwritten: Readonly<Record<string, Unwritten>>,
513 skip: ReadonlySet<string> = new Set(),
514): string[] {
515 const paths = Object.keys(unwritten)
516 .filter((p) => !skip.has(p))
517 .sort();
518 if (paths.length === 0) return [];
519 const list = paths.map((p) => `${p} (version ${unwritten[p]!.version}: ${unwritten[p]!.why})`).join(", ");
520 return [
521 `Stale here: a pull couldn't write ${paths.length === 1 ? "this file" : "these files"}, and no later pull sends ${paths.length === 1 ? "it" : "them"} again. Close whatever holds ${paths.length === 1 ? "it" : "them"}, then abso pull --full: ${list}`,
522 ];
523}
525/** Write the files a sync or switch answer lists into the folder (the same rules as sync). */
526/** Write a sync's answer into the folder, holding its lock (#51). */
527export async function applyAnswer(root: string, api: Api, unscreened: SyncAnswer): Promise<Applied> {
528 return withFolderLock(root, "pull", () => applyAnswerLocked(root, api, unscreened));
529}
531async function applyAnswerLocked(root: string, api: Api, unscreened: SyncAnswer): Promise<Applied> {
532 // Other agents' paths: nothing outside this folder, in .git/.claude/.avcs, or through a link.
533 const { answer, refused } = screenAnswer(root, unscreened);
534 // A write the disk refuses anyway is named and skipped, so the rest of the sync still lands with its
535 // known copies and modes, rather than stopping partway (git checks every path first).
536 const failed = new Set<string>();
537 // Remembered until a write works (#51): the server won't send these files again.
538 const unwritten = readUnwritten(root);
539 const unwrittenBefore = JSON.stringify(unwritten);
540 const tryWrite = (rel: string, write: () => void): boolean => {
541 try {
542 write();
543 delete unwritten[rel];
544 return true;
545 } catch (e) {
546 failed.add(rel);
547 const code = (e as NodeJS.ErrnoException).code ?? (e as Error).message;
548 refused.push({ path: rel, why: `writing it here failed (${code})` });
549 unwritten[rel] = { version: answer.version, why: code };
550 return false;
551 }
552 };
553 const written: string[] = [];
554 const deleted: string[] = [];
555 const kept: string[] = [];
556 // Text that left one path and arrived at a new one, to tell renames from a delete and an add.
557 const gone: FileChange[] = [];
558 const arrived: FileChange[] = [];
559 // Local-only files (.claude/, ...) the server still holds: never written here,
560 // and sent back as deleted so they leave this agent's view and draft.
561 const dropped = new Set<string>();
562 const knownModes = readKnownModes(root);
563 const knownBlobs = readKnownBlobs(root);
564 const blobsBefore = JSON.stringify([...knownBlobs]);
565 for (const c of answer.collisions ?? [])
566 if (isLocalOnly(c.file) && unsafePath(c.file) === undefined) dropped.add(c.file);
567 // Deletions first: on a case-insensitive disk a rename from a.ts to A.ts is one file, and
568 // writing A.ts before deleting a.ts would delete the new file.
569 const entries = Object.entries(answer.files).sort(([, a], [, b]) => Number(a !== null) - Number(b !== null));
570 // Files new to the folder get the line endings git would give them, asked once for all of them.
571 const fresh = newFileEndings(
572 root,
573 entries
574 .filter(([rel, text]) => text !== null && !isLocalOnly(rel) && !existsSync(absolute(root, rel)))
575 .map(([rel]) => rel),
576 );
577 for (const [rel, text] of entries) {
578 if (isLocalOnly(rel)) {
579 if (text !== null) dropped.add(rel);
580 forgetKnown(root, rel);
581 continue;
582 }
583 const path = absolute(root, rel);
584 // Judged by its mode: a link is "" and is never followed.
585 const now = onDisk(path, knownModes.get(rel) ?? PLAIN);
586 const raw = now?.text;
587 const disk = raw === undefined ? undefined : normalize(raw);
588 const untouched = untouchedOnDisk(root, rel, now, knownBlobs);
589 if (text === null) {
590 if (!untouched) {
591 kept.push(rel);
592 continue;
593 }
594 const was = readKnown(root, rel);
595 if (was !== undefined) gone.push({ path: rel, before: was, after: null });
596 removeFile(path);
597 forgetKnown(root, rel);
598 knownModes.delete(rel);
599 knownBlobs.delete(rel);
600 delete unwritten[rel];
601 deleted.push(rel);
602 } else {
603 if (disk === text) {
604 writeKnown(root, rel, text);
605 knownBlobs.delete(rel);
606 delete unwritten[rel];
607 continue;
608 }
609 if (!untouched) {
610 kept.push(rel);
611 continue;
612 }
613 if (!tryWrite(rel, () => writeFileAtomic(path, withEndingsOf(text, raw, fresh.get(rel))))) continue;
614 if (now === undefined) arrived.push({ path: rel, before: null, after: text });
615 writeKnown(root, rel, text);
616 knownBlobs.delete(rel);
617 written.push(rel);
618 }
619 }
620 // Binary files: fetch the bytes the answer names, with the same care for unrecorded work.
621 for (const [rel, sha] of Object.entries(answer.blobs ?? {})) {
622 if (sha === null || isLocalOnly(rel)) continue;
623 const path = absolute(root, rel);
624 const now = onDisk(path, knownModes.get(rel) ?? PLAIN);
625 const b = now === undefined ? undefined : blobOf(path);
626 // Already this file: the same bytes, or (a file kept whole, #46) the same text with any line endings.
627 if (
628 (b !== undefined && "sha" in b && b.sha === sha) ||
629 (now?.text !== undefined && keptWholeAs(normalize(now.text), sha))
630 ) {
631 forgetKnown(root, rel);
632 knownBlobs.set(rel, sha);
633 delete unwritten[rel];
634 continue;
635 }
636 if (!untouchedOnDisk(root, rel, now, knownBlobs)) {
637 kept.push(rel);
638 continue;
639 }
640 const bytes = await api.getBlob(sha);
641 if (!tryWrite(rel, () => writeFileAtomic(path, bytes))) continue;
642 forgetKnown(root, rel);
643 knownBlobs.set(rel, sha);
644 written.push(rel);
645 }
646 if (JSON.stringify([...knownBlobs]) !== blobsBefore) writeKnownBlobs(root, knownBlobs);
647 // Modes after text: a link replaces the "" just written, and the bit goes on the file as written.
648 for (const [rel, m] of Object.entries(answer.modes ?? {})) {
649 if (isLocalOnly(rel) || kept.includes(rel) || answer.files[rel] === null || failed.has(rel)) continue;
650 const was = knownModes.get(rel) ?? PLAIN;
651 const mode: FullMode = { exec: m.exec ?? was.exec, link: m.link === undefined ? was.link : m.link };
652 if (!tryWrite(rel, () => applyMode(absolute(root, rel), mode))) continue;
653 knownModes.set(rel, mode);
654 if (!written.includes(rel)) written.push(rel);
655 }
656 writeKnownModes(root, knownModes);
657 if (dropped.size > 0) {
658 heard(root, (await api.record(Object.fromEntries([...dropped].map((rel) => [rel, null])))).news);
659 for (const rel of dropped) forgetKnown(root, rel);
660 }
661 const collisions = (answer.collisions ?? []).filter((c) => !isLocalOnly(c.file));
662 const renamed =
663 gone.length > 0 && arrived.length > 0
664 ? pairRenames([...gone, ...arrived])
665 .filter((f) => f.from !== undefined)
666 .map((f) => ({ from: f.from!, to: f.path }))
667 : [];
668 if (JSON.stringify(unwritten) !== unwrittenBefore)
669 writeFileAtomic(join(stateDir(root), UNWRITTEN_FILE), `${JSON.stringify(unwritten, null, 1)}\n`);
670 return {
671 version: answer.version,
672 written,
673 deleted,
674 kept,
675 dropped: [...dropped].sort(),
676 collisions,
677 renamed,
678 refused,
679 merged: answer.merged ?? [],
680 unwritten,
681 };
682}