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?draft=names-only-client&format=json
643 linesFirst import 84% · review 15% · pinch 1% · infra-split 1%Last change pinch in version 1, 1 version changed it
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 MAX_TEXT_BYTES,
32 newFileEndings,
33 normalize,
34 pausedPath,
35 readKnown,
36 removeFile,
37 unrecorded,
38 withEndingsOf,
39 writeFileAtomic,
40 writeKnown,
41} from "./folder.ts";
42import { withFolderLock } from "./lock.ts";
43import type { OnDisk } from "./modes.ts";
44import { applyMode, type FullMode, foldModes, onDisk, PLAIN, readKnownModes, writeKnownModes } from "./modes.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 abso: 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 }[];
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 );
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 );
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 ];
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 };
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 }
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;
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));
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 await uploadBlobs(api, blobs);
218 const answer = await api.record(
219 Object.fromEntries(files),
220 {},
221 modes,
222 Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
223 );
224 if (!answer.ok) throw new Error(`the server refused the record: ${answer.reason ?? "no reason given"}`);
225 // Forget before writing: after a rename that changes only case, known/a.ts and known/A.ts are one file on Windows and macOS.
226 for (const [rel, text] of files) if (text === null) forgetKnown(root, rel);
227 for (const [rel, text] of files) if (text !== null) writeKnown(root, rel, text);
228 const knownBlobs = readKnownBlobs(root);
229 if (blobs.size > 0 || [...files.keys()].some((rel) => knownBlobs.has(rel))) {
230 for (const rel of files.keys()) knownBlobs.delete(rel);
231 for (const [rel, b] of blobs) {
232 forgetKnown(root, rel);
233 knownBlobs.set(rel, b.sha);
234 }
235 writeKnownBlobs(root, knownBlobs);
236 }
237 const gone = [...files].filter(([, text]) => text === null).map(([rel]) => rel);
238 const knownModes = readKnownModes(root);
239 if (Object.keys(modes).length > 0 || gone.some((rel) => knownModes.has(rel))) {
240 foldModes(knownModes, modes, gone);
241 writeKnownModes(root, knownModes);
242 }
243 // Another spelling of an existing file went in as that file (#49); a new name not in composed form gets a gentle word.
244 heard(root, [
245 ...newsLines(answer.news),
246 ...(answer.spelling ?? []).map(spellingText),
247 ...(answer.uncomposed ?? []).map(uncomposedText),
248 ]);
249 const longPaths = longPathsOf(
250 root,
251 [...files].filter(([, text]) => text !== null).map(([path]) => path),
252 );
253 const gitMarkers = [...files]
254 .flatMap(([path, text]) => {
255 const line = text === null ? undefined : gitMarkerLine(text);
256 return line === undefined ? [] : [{ path, line }];
257 })
258 .sort((a, b) => (a.path < b.path ? -1 : 1));
259 return {
260 sent,
261 paths,
262 deleted,
263 added,
264 changed: answer.changed,
265 news: answer.news,
266 leftOut,
267 turnedBinary,
268 gitMarkers,
269 longPaths,
270 };
273/** 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. */
274export function gitMarkerText(list: readonly { path: string; line: number }[] | undefined): string[] {
275 return (list ?? []).map(
276 (m) =>
277 `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.`,
278 );
281/** Windows stops at 260 characters for a whole path, and another agent's folder may sit deeper than this one. */
282const LONG_FULL_PATH = 240;
283const LONG_RELATIVE_PATH = 160;
285/** 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. */
286export function longPathsOf(root: string, paths: Iterable<string>): { path: string; length: number }[] {
287 return [...paths]
288 .map((path) => ({ path, length: absolute(root, path).length }))
289 .filter((p) => p.length >= LONG_FULL_PATH || p.path.length >= LONG_RELATIVE_PATH)
290 .sort((a, b) => (a.path < b.path ? -1 : 1));
293/** A note per long path: abso keeps it, but a Windows agent may not be able to write the file. */
294export function longPathText(list: readonly { path: string; length: number }[] | undefined): string[] {
295 return (list ?? []).map(
296 (p) =>
297 `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.`,
298 );
301/** "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. */
302export function recordedFirst(r: Recorded): string[] {
303 if (r.paused) return ["Recording is paused (abso resume): your folder's changes were not sent first."];
304 if (r.sent === 0) return [];
305 return [`Recorded first: ${recordedList(r)}.`, ...gitMarkerText(r.gitMarkers), ...longPathText(r.longPaths)];
308/** "2 changed (a, b), 3 deleted (x, y, z)": deletions said as such (#37: deleted files were read as edits). */
309function recordedList(r: Recorded): string {
310 const names = (list: readonly string[]) =>
311 list.length <= LISTED ? list.join(", ") : `${list.slice(0, LISTED).join(", ")}, and ${list.length - LISTED} more`;
312 const gone = new Set(r.deleted);
313 const fresh = new Set(r.added ?? []);
314 const changed = r.paths.filter((p) => !gone.has(p) && !fresh.has(p));
315 // New files are named in full: they are the ones a script made and nobody remembers (#37).
316 return [
317 ...(fresh.size > 0 ? [`${fresh.size} new (${[...fresh].join(", ")})`] : []),
318 ...(changed.length > 0 ? [`${changed.length} changed (${names(changed)})`] : []),
319 ...(r.deleted.length > 0 ? [`${r.deleted.length} deleted (${names(r.deleted)})`] : []),
320 ].join(", ");
323export const READER_REFUSES =
324 "this folder is a reader: it records and publishes nothing (abso reader off makes it a writer again)";
326/** abso pause: send nothing from the folder (no hook, no record) until abso resume. */
327export async function runPause(_args: Parsed, env: Env): Promise<Output> {
328 const { root } = open(env);
329 const was = isPaused(root);
330 writeFileSync(pausedPath(root), `${new Date().toISOString()}\n`);
331 return {
332 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.`,
333 json: { paused: true },
334 };
337export async function runResume(_args: Parsed, env: Env): Promise<Output> {
338 const { root } = open(env);
339 const was = isPaused(root);
340 rmSync(pausedPath(root), { force: true });
341 return {
342 text: was
343 ? "Recording again. Changes made while paused go at the next abso record (or publish, sync, ...); abso status lists them."
344 : "Recording was not paused.",
345 json: { paused: false },
346 };
349export async function runRecord(args: Parsed, env: Env): Promise<Output> {
350 if (isReader(findRoot(env.cwd) ?? env.cwd)) throw new UsageError(READER_REFUSES);
351 const { root, api } = open(env);
352 if (isPaused(root))
353 return {
354 exit: EXIT.refused,
355 text: "Not recorded: recording is paused. abso resume, then abso record.",
356 json: { paused: true },
357 };
358 const r = await recordFolder(root, api, bool(args, "all"), meantBinary(args));
359 const changed = Array.isArray(r.changed) ? r.changed.length : r.changed;
360 const text =
361 r.sent === 0
362 ? "Nothing to record: the folder matches what the server has."
363 : `Recorded ${recordedList(r)}${changed === undefined ? "" : `; ${changed} changed on the server`}.`;
364 return withLeftOut(
365 {
366 text: [
367 ...turnedBinaryText(r.turnedBinary),
368 text,
369 ...gitMarkerText(r.gitMarkers),
370 ...longPathText(r.longPaths),
371 ...leftOutText(r.leftOut),
372 ].join("\n"),
373 json: {
374 sent: r.sent,
375 changed: r.changed ?? null,
376 news: newsLines(r.news),
377 leftOut: r.leftOut,
378 turnedBinary: r.turnedBinary,
379 gitMarkers: r.gitMarkers ?? [],
380 longPaths: r.longPaths ?? [],
381 },
382 },
383 r.leftOut,
384 );
387// --- writing answers into the folder ---
389/**
390 * Bring the folder to shared and set the agent's base. Writes only files that
391 * still match the known copy (or are new), so unrecorded work is never
392 * overwritten.
393 */
394export async function syncFolder(root: string, api: Api, full = false): Promise<Applied> {
395 return applyAnswer(root, api, await api.sync({ full }));
398/** What writing a sync or switch answer into the folder did. */
399export interface Applied {
400 readonly version: number;
401 readonly written: string[];
402 readonly deleted: string[];
403 readonly kept: string[];
404 readonly dropped: string[];
405 readonly collisions: readonly Collision[];
406 /** Text files the answer deleted and wrote again under a new path, paired as git pairs renames. Each is in `written` and `deleted` too. */
407 readonly renamed: readonly { readonly from: string; readonly to: string }[];
408 /** Paths in the answer that were not touched: outside the folder, into .git/.claude/.abso, a device, or through a link (safety.ts). */
409 readonly refused: readonly Refused[];
410 /** Lines both sides changed that the server merged item by item. */
411 readonly merged: readonly MergedLine[];
412 /** Files a sync couldn't write here, this one or an earlier one, still stale (#51): path -> when and why. */
413 readonly unwritten: Readonly<Record<string, Unwritten>>;
416/** How many names a summary line shows before "and N more". */
417export const LISTED = 8;
418/** How far back an empty publish looks for this agent's last publish. */
419export const FOLDER_LOG_LIMIT = 200;
421/**
422 * The files a sync or switch changed. A line per kind, with the names cut
423 * short past LISTED (a big sync used to print a line per file); --verbose
424 * gives a line per file.
425 */
426export function changedFilesText(
427 command: string,
428 written: readonly string[],
429 deleted: readonly string[],
430 renamed: readonly { readonly from: string; readonly to: string }[],
431 verbose: boolean,
432): string[] {
433 const moves = renamed.map((r) => `${r.from} -> ${r.to}`);
434 if (verbose)
435 return [
436 ...written.map((f) => ` updated ${f}`),
437 ...deleted.map((f) => ` deleted ${f}`),
438 ...moves.map((m) => ` renamed ${m}`),
439 ];
440 const some = (names: readonly string[]) =>
441 names.length <= LISTED
442 ? names.join(", ")
443 : `${names.slice(0, LISTED).join(", ")}, and ${names.length - LISTED} more`;
444 return [
445 ...(written.length > 0 ? [` updated: ${some(written)}`] : []),
446 ...(deleted.length > 0 ? [` deleted: ${some(deleted)}`] : []),
447 ...(moves.length > 0 ? [` renamed: ${some(moves)}`] : []),
448 ...([written, deleted, moves].some((l) => l.length > LISTED)
449 ? [` (abso ${command} --verbose lists every file)`]
450 : []),
451 ];
454/** 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. */
455export interface Unwritten {
456 readonly version: number;
457 readonly why: string;
460const UNWRITTEN_FILE = "unwritten.json";
462/** Files earlier syncs couldn't write here, kept in .abso/unwritten.json until a write of them works. */
463export function readUnwritten(root: string): Record<string, Unwritten> {
464 try {
465 return JSON.parse(readFileSync(join(stateDir(root), UNWRITTEN_FILE), "utf8")) as Record<string, Unwritten>;
466 } catch {
467 return {};
468 }
471/** Status's line for them, and sync's for ones an earlier sync named. */
472export function unwrittenText(
473 unwritten: Readonly<Record<string, Unwritten>>,
474 skip: ReadonlySet<string> = new Set(),
475): string[] {
476 const paths = Object.keys(unwritten)
477 .filter((p) => !skip.has(p))
478 .sort();
479 if (paths.length === 0) return [];
480 const list = paths.map((p) => `${p} (version ${unwritten[p]!.version}: ${unwritten[p]!.why})`).join(", ");
481 return [
482 `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}`,
483 ];
486/** Write the files a sync or switch answer lists into the folder (the same rules as sync). */
487/** Write a sync's answer into the folder, holding its lock (#51). */
488export async function applyAnswer(root: string, api: Api, unscreened: SyncAnswer): Promise<Applied> {
489 return withFolderLock(root, "sync", () => applyAnswerLocked(root, api, unscreened));
492async function applyAnswerLocked(root: string, api: Api, unscreened: SyncAnswer): Promise<Applied> {
493 // Other agents' paths: nothing outside this folder, in .git/.claude/.abso, or through a link.
494 const { answer, refused } = screenAnswer(root, unscreened);
495 // A write the disk refuses anyway is named and skipped, so the rest of the sync still lands with its
496 // known copies and modes, rather than stopping partway (git checks every path first).
497 const failed = new Set<string>();
498 // Remembered until a write works (#51): the server won't send these files again.
499 const unwritten = readUnwritten(root);
500 const unwrittenBefore = JSON.stringify(unwritten);
501 const tryWrite = (rel: string, write: () => void): boolean => {
502 try {
503 write();
504 delete unwritten[rel];
505 return true;
506 } catch (e) {
507 failed.add(rel);
508 const code = (e as NodeJS.ErrnoException).code ?? (e as Error).message;
509 refused.push({ path: rel, why: `writing it here failed (${code})` });
510 unwritten[rel] = { version: answer.version, why: code };
511 return false;
512 }
513 };
514 const written: string[] = [];
515 const deleted: string[] = [];
516 const kept: string[] = [];
517 // Text that left one path and arrived at a new one, to tell renames from a delete and an add.
518 const gone: FileChange[] = [];
519 const arrived: FileChange[] = [];
520 // Local-only files (.claude/, ...) the server still holds: never written here,
521 // and sent back as deleted so they leave this agent's view and draft.
522 const dropped = new Set<string>();
523 const knownModes = readKnownModes(root);
524 const knownBlobs = readKnownBlobs(root);
525 const blobsBefore = JSON.stringify([...knownBlobs]);
526 for (const c of answer.collisions ?? [])
527 if (isLocalOnly(c.file) && unsafePath(c.file) === undefined) dropped.add(c.file);
528 // Deletions first: on a case-insensitive disk a rename from a.ts to A.ts is one file, and
529 // writing A.ts before deleting a.ts would delete the new file.
530 const entries = Object.entries(answer.files).sort(([, a], [, b]) => Number(a !== null) - Number(b !== null));
531 // Files new to the folder get the line endings git would give them, asked once for all of them.
532 const fresh = newFileEndings(
533 root,
534 entries
535 .filter(([rel, text]) => text !== null && !isLocalOnly(rel) && !existsSync(absolute(root, rel)))
536 .map(([rel]) => rel),
537 );
538 for (const [rel, text] of entries) {
539 if (isLocalOnly(rel)) {
540 if (text !== null) dropped.add(rel);
541 forgetKnown(root, rel);
542 continue;
543 }
544 const path = absolute(root, rel);
545 // Judged by its mode: a link is "" and is never followed.
546 const now = onDisk(path, knownModes.get(rel) ?? PLAIN);
547 const raw = now?.text;
548 const disk = raw === undefined ? undefined : normalize(raw);
549 const untouched = untouchedOnDisk(root, rel, now, knownBlobs);
550 if (text === null) {
551 if (!untouched) {
552 kept.push(rel);
553 continue;
554 }
555 const was = readKnown(root, rel);
556 if (was !== undefined) gone.push({ path: rel, before: was, after: null });
557 removeFile(path);
558 forgetKnown(root, rel);
559 knownModes.delete(rel);
560 knownBlobs.delete(rel);
561 delete unwritten[rel];
562 deleted.push(rel);
563 } else {
564 if (disk === text) {
565 writeKnown(root, rel, text);
566 knownBlobs.delete(rel);
567 delete unwritten[rel];
568 continue;
569 }
570 if (!untouched) {
571 kept.push(rel);
572 continue;
573 }
574 if (!tryWrite(rel, () => writeFileAtomic(path, withEndingsOf(text, raw, fresh.get(rel))))) continue;
575 if (now === undefined) arrived.push({ path: rel, before: null, after: text });
576 writeKnown(root, rel, text);
577 knownBlobs.delete(rel);
578 written.push(rel);
579 }
580 }
581 // Binary files: fetch the bytes the answer names, with the same care for unrecorded work.
582 for (const [rel, sha] of Object.entries(answer.blobs ?? {})) {
583 if (sha === null || isLocalOnly(rel)) continue;
584 const path = absolute(root, rel);
585 const now = onDisk(path, knownModes.get(rel) ?? PLAIN);
586 const b = now === undefined ? undefined : blobOf(path);
587 // Already this file: the same bytes, or (a file kept whole, #46) the same text with any line endings.
588 if (
589 (b !== undefined && "sha" in b && b.sha === sha) ||
590 (now?.text !== undefined && keptWholeAs(normalize(now.text), sha))
591 ) {
592 forgetKnown(root, rel);
593 knownBlobs.set(rel, sha);
594 delete unwritten[rel];
595 continue;
596 }
597 if (!untouchedOnDisk(root, rel, now, knownBlobs)) {
598 kept.push(rel);
599 continue;
600 }
601 const bytes = await api.getBlob(sha);
602 if (!tryWrite(rel, () => writeFileAtomic(path, bytes))) continue;
603 forgetKnown(root, rel);
604 knownBlobs.set(rel, sha);
605 written.push(rel);
606 }
607 if (JSON.stringify([...knownBlobs]) !== blobsBefore) writeKnownBlobs(root, knownBlobs);
608 // Modes after text: a link replaces the "" just written, and the bit goes on the file as written.
609 for (const [rel, m] of Object.entries(answer.modes ?? {})) {
610 if (isLocalOnly(rel) || kept.includes(rel) || answer.files[rel] === null || failed.has(rel)) continue;
611 const was = knownModes.get(rel) ?? PLAIN;
612 const mode: FullMode = { exec: m.exec ?? was.exec, link: m.link === undefined ? was.link : m.link };
613 if (!tryWrite(rel, () => applyMode(absolute(root, rel), mode))) continue;
614 knownModes.set(rel, mode);
615 if (!written.includes(rel)) written.push(rel);
616 }
617 writeKnownModes(root, knownModes);
618 if (dropped.size > 0) {
619 heard(root, (await api.record(Object.fromEntries([...dropped].map((rel) => [rel, null])))).news);
620 for (const rel of dropped) forgetKnown(root, rel);
621 }
622 const collisions = (answer.collisions ?? []).filter((c) => !isLocalOnly(c.file));
623 const renamed =
624 gone.length > 0 && arrived.length > 0
625 ? pairRenames([...gone, ...arrived])
626 .filter((f) => f.from !== undefined)
627 .map((f) => ({ from: f.from!, to: f.path }))
628 : [];
629 if (JSON.stringify(unwritten) !== unwrittenBefore)
630 writeFileAtomic(join(stateDir(root), UNWRITTEN_FILE), `${JSON.stringify(unwritten, null, 1)}\n`);
631 return {
632 version: answer.version,
633 written,
634 deleted,
635 kept,
636 dropped: [...dropped].sort(),
637 collisions,
638 renamed,
639 refused,
640 merged: answer.merged ?? [],
641 unwritten,
642 };