Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
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=84&format=json
642 linesFirst import 85% · review 15% · infra-split 1%Last change pinch in version 78, 6 versions changed it

You're reading version 84. The newest is 318, and 3 versions since then changed this file. Go to the newestCompare with 318

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