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/changes.ts?version=33&format=json
592 linesFirst import 98% · pinch 2% · engine 1% · review 1%Last change pinch in version 26, 4 versions changed it

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

1// abso diff, log, show and restore: the everyday commands of #27.
2//
3// diff and restore work on this agent's unpublished changes. log, show and
4// diff between versions read the published versions of the space this folder
5// is in (shared or a named draft) unless --draft names another.
6
7import { existsSync, statSync } from "node:fs";
8import { relative, resolve } from "node:path";
9import type { Api, FileChange, LogAnswer, LogEntry, Where } from "./api.ts";
10import { bool, type Parsed, str, UsageError } from "./args.ts";
11import { globTest } from "./at.ts";
12import { readKnownBlobs, writeKnownBlobs } from "./blobs.ts";
13import { ciMarkText } from "./ci.ts";
14import { type Env, EXIT, missingHere, type Output, open, plural, recordedFirst, recordFolder } from "./commands.ts";
15import { editScript, linesOf, normalize, withEndingsOf } from "./core.ts";
16import { lineCounts, pairRenames, unifiedDiff } from "./diff.ts";
17import {
18 absolute,
19 forgetKnown,
20 newFileEndings,
21 readText,
22 removeFile,
23 unrecorded,
24 writeFileAtomic,
25 writeKnown,
26} from "./folder.ts";
27import { fileArg, when } from "./history.ts";
28import { byWhom } from "./history-answers.ts";
29import { applyMode, PLAIN, readKnownModes, writeKnownModes } from "./modes.ts";
30import { refusedText, screenAnswer } from "./safety.ts";
32/** The space to read: --draft (where "shared" means shared), else the one this agent is in. */
33function space(args: Parsed, agent: string): Where {
34 const named = str(args, "draft");
35 if (named === undefined) return { agent };
36 return { draft: named === "shared" ? null : named };
39function spaceName(draft: string | null): string {
40 return draft === null ? "shared" : `draft ${draft}`;
43/** How to name a space in a sentence when only the request says which it is. */
44function whereName(where: Where): string {
45 return "agent" in where ? "your space" : spaceName(where.draft);
48function version(raw: string, what = "a version"): number {
49 const n = Number(raw);
50 if (!/^\d+$/.test(raw) || !Number.isSafeInteger(n))
51 throw new UsageError(`${what} is a version number (got ${JSON.stringify(raw)})`);
52 return n;
55/**
56 * abso files [glob...] [--draft <name>] [--version N]: the files a view holds
57 * (#37). Without flags, this agent's view, what the folder should hold, with
58 * any the folder lacks marked; with --draft or --version, that space at that
59 * version as published.
60 */
61export async function runFiles(args: Parsed, env: Env): Promise<Output> {
62 const { root, config, api } = open(env);
63 const rawVersion = str(args, "version");
64 const at = rawVersion === undefined ? undefined : version(rawVersion, "--version");
65 const where = space(args, config.agent);
66 const mine = "agent" in where && at === undefined;
67 // --version alone reads the space this agent is in, which only its view names.
68 const answer = mine
69 ? await api.viewFiles()
70 : await api.filesAt("agent" in where ? (await api.viewFiles()).draft : where.draft, at);
71 const match = args.positionals.length === 0 ? () => true : globTest(args.positionals.join(","));
72 const files = answer.files.filter((f) => match(f));
73 const pending = mine ? unrecorded(root) : undefined;
74 const missing = new Set(
75 pending
76 ? missingHere(
77 root,
78 files,
79 new Set([...pending.files.keys(), ...pending.blobs.keys(), ...Object.keys(pending.modes)]),
80 )
81 : [],
82 );
83 const what =
84 args.positionals.length === 0
85 ? plural(files.length, "file")
86 : `${plural(files.length, "file")} matching ${args.positionals.join(", ")}`;
87 return {
88 text: [
89 mine
90 ? `Your view holds ${what}: ${spaceName(answer.draft)} at version ${answer.version}, with your unpublished changes.${missing.size > 0 ? ` ${missing.size} of them ${missing.size === 1 ? "is" : "are"} missing from this folder (abso sync --full writes them).` : ""}`
91 : `${spaceName(answer.draft)} at version ${answer.version} holds ${what}.`,
92 ...files.map((f) => (missing.has(f) ? `${f} (missing from this folder)` : f)),
93 ].join("\n"),
94 json: { version: answer.version, draft: answer.draft, files, ...(mine ? { missing: [...missing] } : {}) },
95 };
98/** The diffs, and a JSON form that carries each file's diff text and line counts. */
99function diffs(files: readonly FileChange[]): { text: string[]; json: unknown[] } {
100 const text: string[] = [];
101 const json: unknown[] = [];
102 for (const f of files) {
103 const diff = unifiedDiff(f);
104 text.push(diff);
105 json.push({ ...f, ...lineCounts(f), diff });
106 }
107 return { text, json };
110function totals(files: readonly FileChange[]): string {
111 let added = 0;
112 let removed = 0;
113 for (const f of files) {
114 const c = lineCounts(f);
115 added += c.added;
116 removed += c.removed;
117 }
118 const renamed = files.filter((f) => f.from !== undefined).length;
119 return `${plural(files.length, "file")}${renamed > 0 ? ` (${renamed} renamed)` : ""}, ${plural(added, "line")} added, ${removed} removed`;
122/** Whether a change is to `p` (a file or a folder): a renamed file counts under its old path and its new one. */
123function touches(f: FileChange, p: string): boolean {
124 return under(f.path, p) || (f.from !== undefined && under(f.from, p));
127export async function runDiff(args: Parsed, env: Env): Promise<Output> {
128 const { root, config, api } = open(env);
129 const words = args.positionals;
130 const between = words.length >= 2 && /^\d+$/.test(words[0]!) && /^\d+$/.test(words[1]!);
131 const only = (between ? words.slice(2) : words).map((w) => pathArg(root, env.cwd, w));
132 // Renames are paired over every file first, so a path picks the whole rename.
133 const pick = (files: readonly FileChange[]) => {
134 const all = pairRenames(files);
135 return only.length === 0 ? all : all.filter((f) => only.some((p) => touches(f, p)));
136 };
137 // Each path that matched nothing gets a line of its own, saying whether it is even there.
138 const unmatched = (files: readonly FileChange[]) => only.filter((p) => !files.some((f) => touches(f, p)));
139 const notes = (files: readonly FileChange[]) =>
140 unmatched(files)
141 .filter((p) => only.length > 1 || !existsHere(root, p))
142 .map((p) => nothingAt(root, p));
144 if (between) {
145 const from = version(words[0]!);
146 const to = version(words[1]!);
147 const where = space(args, config.agent);
148 const answer = await api.compare(from, to, where);
149 const files = pick(answer.files);
150 const d = diffs(files);
151 const head =
152 files.length === 0
153 ? `No differences between versions ${from} and ${to} of ${whereName(where)}${inPaths(only)}.`
154 : `From version ${from} to ${to} of ${whereName(where)}${inPaths(only)}: ${totals(files)}.`;
155 return {
156 text: [head, ...notes(files), ...d.text].join("\n"),
157 json: { ...where, from, to, files: d.json, unmatched: unmatched(files) },
158 };
159 }
161 if (str(args, "draft") !== undefined)
162 throw new UsageError(
163 "--draft goes with two versions (abso diff <from> <to>); abso diff alone shows your own unpublished changes",
164 );
165 // Folder-only edits count as unpublished changes too.
166 const recorded = await recordFolder(root, api);
167 const answer = await api.diff();
168 const files = pick(answer.files);
169 const d = diffs(files);
170 const where = `${spaceName(answer.draft)}${answer.base === null ? "" : ` (on version ${answer.base})`}`;
171 const head =
172 files.length === 0
173 ? `No unpublished changes${inPaths(only, "to")} in ${where}.`
174 : `Your unpublished changes${inPaths(only, "to")} in ${where}: ${totals(files)}.`;
175 const pre = recordedFirst(recorded);
176 return {
177 text: [...pre, head, ...notes(files), ...d.text].join("\n"),
178 json: {
179 draft: answer.draft,
180 base: answer.base,
181 files: d.json,
182 recorded: recorded.sent,
183 unmatched: unmatched(files),
184 },
185 };
188const LOG_FILES = 8;
189/** How far back `abso log <folder>` looks, since the client filters it. */
190const FOLDER_LOG = 1000;
192/** A path as typed, folder-relative: "" for the whole folder. A folder stands for every file under it. */
193function pathArg(root: string, cwd: string, typed: string): string {
194 if (relative(root, resolve(cwd, typed)) === "") return "";
195 return fileArg(root, cwd, typed);
198/** Whether `path` is `p`, or under the folder `p` ("" is everything). */
199function under(path: string, p: string): boolean {
200 return p === "" || path === p || path.startsWith(`${p}/`);
203function isFolder(root: string, p: string): boolean {
204 try {
205 return statSync(absolute(root, p)).isDirectory();
206 } catch {
207 return false;
208 }
211function existsHere(root: string, p: string): boolean {
212 return p === "" || existsSync(absolute(root, p));
215/** The line for a path that matched no changed file. */
216function nothingAt(root: string, p: string): string {
217 if (!existsHere(root, p))
218 return ` ${p}: no such file or folder here now (paths are relative to where you run abso).`;
219 return ` ${p === "" ? "the whole folder" : `${p}${isFolder(root, p) ? "/" : ""}`}: no changes there.`;
222/** " in a.ts, harness" (or " to ...") for the paths a command was limited to. */
223function inPaths(only: readonly string[], word = "in"): string {
224 return only.length === 0 ? "" : ` ${word} ${only.map((p) => (p === "" ? "the whole folder" : p)).join(", ")}`;
227/** How many renames `abso log <file>` follows back. */
228const FOLLOW_RENAMES = 20;
230type FollowedEntry = LogEntry & { readonly renamedFrom?: string };
232/**
233 * A file's log that goes on past a rename, like `git log --follow`: where the
234 * oldest version found is the one that renamed the file into being, the
235 * versions before it come from the old path's log.
236 */
237async function followRenames(
238 api: Api,
239 where: Where,
240 path: string,
241 first: LogAnswer,
242 limit: number | undefined,
243): Promise<FollowedEntry[]> {
244 const versions: FollowedEntry[] = [...first.versions];
245 let current = path;
246 for (let hops = 0; hops < FOLLOW_RENAMES; hops++) {
247 if (limit !== undefined && versions.length >= limit) break;
248 const oldest = versions[versions.length - 1];
249 if (oldest === undefined || oldest.version === 0) break;
250 const renamed = pairRenames((await api.show(oldest.version, where)).diff).find(
251 (f) => f.path === current && f.from !== undefined,
252 );
253 if (renamed === undefined) break;
254 versions[versions.length - 1] = { ...oldest, renamedFrom: renamed.from! };
255 const earlier = (await api.log(where, FOLDER_LOG, renamed.from)).versions.filter((v) => v.version < oldest.version);
256 versions.push(...earlier.slice(0, limit === undefined ? 50 : limit - versions.length));
257 current = renamed.from!;
258 }
259 return versions;
262/** What else a version says: its labels, what it dropped or what dropped it, and its first message when amended. */
263function notes(v: FollowedEntry): string[] {
264 const out: string[] = [];
265 if (v.renamedFrom !== undefined)
266 out.push(` renamed from ${v.renamedFrom}; the versions below are its history under that name`);
267 if (v.labels && v.labels.length > 0) out.push(` labels: ${v.labels.join(", ")}`);
268 if (v.drops && v.drops.length > 0)
269 out.push(` drops ${v.drops.length === 1 ? "version" : "versions"} ${v.drops.join(", ")}`);
270 if (v.droppedIn !== undefined) out.push(` dropped in version ${v.droppedIn}: shared no longer has these changes`);
271 if (v.originalMessage !== undefined) out.push(` amended; first published as: ${v.originalMessage}`);
272 return out;
275/**
276 * --since: a version number (the versions after it), a span back from now
277 * (30m, 2h, 1d), or a date and time Date.parse reads (2026-10-05T17:00).
278 */
279export function sinceTest(raw: string, now: number): (v: LogEntry) => boolean {
280 if (/^\d+$/.test(raw)) {
281 const n = Number(raw);
282 return (v) => v.version > n;
283 }
284 const span = /^(\d+)\s*(m|min|h|d)$/.exec(raw);
285 // A bare clock time (20:00) is today's, local; yesterday's when today's hasn't come yet (#37, Reporter).
286 const clock = /^(\d{1,2}):(\d{2})$/.exec(raw);
287 const today = (h: number, m: number) => {
288 const d = new Date(now);
289 d.setHours(h, m, 0, 0);
290 return d.getTime() > now ? d.getTime() - 86_400_000 : d.getTime();
291 };
292 const at = span
293 ? now -
294 Number(span[1]) * { m: 60_000, min: 60_000, h: 3_600_000, d: 86_400_000 }[span[2] as "m" | "min" | "h" | "d"]
295 : clock && Number(clock[1]) < 24 && Number(clock[2]) < 60
296 ? today(Number(clock[1]), Number(clock[2]))
297 : Date.parse(raw);
298 if (Number.isNaN(at))
299 throw new UsageError(
300 `--since takes a version (400), a span back from now (30m, 2h, 1d), a clock time today (20:00), or a date and time (2026-10-05T17:00); got ${JSON.stringify(raw)}`,
301 );
302 return (v) => v.time >= at;
305export async function runLog(args: Parsed, env: Env): Promise<Output> {
306 if (args.positionals.length > 1)
307 throw new UsageError("log takes at most one file: abso log [file] [-n <count>] [--draft <name>]");
308 const { root, config, api } = open(env);
309 const typed = args.positionals[0];
310 const path = typed === undefined ? undefined : pathArg(root, env.cwd, typed);
311 const rawLimit = str(args, "limit");
312 const limit = rawLimit === undefined ? undefined : version(rawLimit, "-n");
313 if (limit === 0) throw new UsageError("-n is how many versions to show; give 1 or more");
314 const rawBefore = str(args, "before");
315 const before = rawBefore === undefined ? undefined : version(rawBefore, "--before");
316 // The server filters by one file; a folder (or the whole folder) is filtered here, from a longer log.
317 const folder = path !== undefined && (path === "" || /[/]$/.test(typed!) || isFolder(root, path));
318 // --since, --by and --count (#37, Reporter's progress reports) filter here, from a longer log.
319 const since = str(args, "since");
320 const by = str(args, "by");
321 const count = bool(args, "count");
322 const filtering = since !== undefined || by !== undefined || count;
323 const keep = since === undefined ? () => true : sinceTest(since, Date.now());
324 const agents =
325 by === undefined
326 ? undefined
327 : new Set(
328 by
329 .split(",")
330 .map((a) => a.trim())
331 .filter((a) => a !== ""),
332 );
333 const raw = await api.log(
334 space(args, config.agent),
335 folder || filtering ? FOLDER_LOG : limit,
336 folder ? undefined : path,
337 before,
338 );
339 const found = folder
340 ? {
341 ...raw,
342 versions: raw.versions
343 .filter((v) => v.files.some((f) => under(f, path!)))
344 .slice(0, filtering ? FOLDER_LOG : (limit ?? 50)),
345 }
346 : path !== undefined
347 ? {
348 ...raw,
349 versions: await followRenames(api, space(args, config.agent), path, raw, filtering ? FOLDER_LOG : limit),
350 }
351 : raw;
352 const answer = filtering
353 ? {
354 ...found,
355 versions: found.versions
356 .filter((v) => keep(v) && (agents === undefined || agents.has(v.agent)))
357 .slice(0, limit ?? FOLDER_LOG),
358 }
359 : found;
360 if (count) {
361 // Versions and files per agent, most first.
362 const per = new Map<string, { versions: number; files: Set<string> }>();
363 for (const v of answer.versions) {
364 const a = per.get(v.agent) ?? { versions: 0, files: new Set<string>() };
365 a.versions++;
366 for (const f of v.files) a.files.add(f);
367 per.set(v.agent, a);
368 }
369 const rows = [...per].sort(([a, x], [b, y]) => y.versions - x.versions || a.localeCompare(b));
370 const scope = [
371 since === undefined ? "" : /^\d+$/.test(since) ? ` since version ${since}` : ` since ${since}`,
372 agents === undefined ? "" : ` by ${[...agents].join(", ")}`,
373 ].join("");
374 return {
375 text: [
376 `${spaceName(answer.draft)} is at version ${answer.version}. ${plural(answer.versions.length, "version")}${scope}${answer.versions.length > 0 ? ", per agent:" : "."}`,
377 ...rows.map(([agent, a]) => ` ${agent}: ${plural(a.versions, "version")}, ${plural(a.files.size, "file")}`),
378 ].join("\n"),
379 json: {
380 draft: answer.draft,
381 version: answer.version,
382 versions: answer.versions.length,
383 agents: Object.fromEntries(rows.map(([agent, a]) => [agent, { versions: a.versions, files: a.files.size }])),
384 },
385 };
386 }
387 const named = path === undefined ? "" : path === "" ? "the whole folder" : folder ? `${path}/` : path;
388 const lines = [
389 `${spaceName(answer.draft)} is at version ${answer.version}.${path === undefined ? "" : answer.versions.length === 0 ? ` No version changed ${named}.` : ` The versions that changed ${named}, newest first:`}`,
390 ...(path !== undefined && answer.versions.length === 0 && !existsHere(root, path) ? [nothingAt(root, path)] : []),
391 ...answer.versions.flatMap((v) => [
392 `version ${v.version} by ${byWhom(v)}, ${when(v.time)}${answer.draft === null ? ciMarkText(v.ci) : ""}: ${v.message}`,
393 ` ${plural(v.files.length, "file")}: ${v.files.slice(0, LOG_FILES).join(", ")}${v.files.length > LOG_FILES ? `, and ${v.files.length - LOG_FILES} more` : ""}`,
394 ...notes(v),
395 ]),
396 ];
397 const oldest = answer.versions[answer.versions.length - 1];
398 if (!filtering && !folder && raw.next !== undefined && oldest !== undefined)
399 lines.push(`Older versions: abso log${typed === undefined ? "" : ` ${typed}`} --before ${oldest.version}`);
400 if (filtering && answer.versions.length === 0) lines.push("No version matches.");
401 // A filter or a folder reads the newest FOLDER_LOG versions; say so when older ones were left unread.
402 if ((filtering || folder) && raw.next !== undefined)
403 lines.push(
404 `Only the newest ${FOLDER_LOG} versions${before === undefined ? "" : ` below ${before}`} were read; --before ${raw.next} reads older ones.`,
405 );
406 return { text: lines.join("\n"), json: { ...answer } };
409export async function runShow(args: Parsed, env: Env): Promise<Output> {
410 if (args.positionals.length !== 1)
411 throw new UsageError("show takes one version: abso show <version> or abso show <version>:<file>");
412 const { root, config, api } = open(env);
413 const word = args.positionals[0]!;
414 const colon = word.indexOf(":");
415 const where = space(args, config.agent);
417 if (colon >= 0) {
418 const v = version(word.slice(0, colon));
419 const path = fileArg(root, env.cwd, word.slice(colon + 1));
420 const answer = await api.fileAt(path, v, where);
421 if (answer.text === null)
422 return {
423 exit: EXIT.error,
424 text: `${path} did not exist at version ${v} of ${whereName(where)}.`,
425 json: { ...answer, ...where },
426 };
427 return { text: answer.text, json: { ...answer, ...where } };
428 }
430 const answer = await api.show(version(word), where);
431 const changed = pairRenames(answer.diff);
432 const d = diffs(changed);
433 const lines = [
434 `version ${answer.version} of ${spaceName(answer.draft)} by ${byWhom(answer)}, ${when(answer.time)}: ${answer.message}`,
435 ...notes(answer),
436 changed.length === 0 ? "It changed no files." : `${totals(changed)}.`,
437 ...d.text,
438 ];
439 return { text: lines.join("\n"), json: { ...answer, diff: d.json } };
442/**
443 * A file's text with the draft's hunks that touch lines `from`-`to` (of the
444 * file as it is now, as abso diff numbers them) put back as they were at the
445 * base; the other hunks stay (#37, Builder 2: drop my copy of a teammate's
446 * half and keep the rest). A hunk that only deleted lines touches the line
447 * where they were.
448 */
449export function restoreLines(before: string, after: string, from: number, to: number): { text: string; hunks: number } {
450 const ops = editScript(linesOf(before), linesOf(after));
451 const out: string[] = [];
452 let hunks = 0;
453 let line = 1; // the next line of the file as it is now
454 for (let i = 0; i < ops.length; ) {
455 if (ops[i]!.kind === " ") {
456 out.push(ops[i]!.line);
457 line++;
458 i++;
459 continue;
460 }
461 // One hunk: the run of - and + ops.
462 let j = i;
463 while (j < ops.length && ops[j]!.kind !== " ") j++;
464 const run = ops.slice(i, j);
465 const added = run.filter((o) => o.kind === "+").length;
466 const first = line;
467 const last = added > 0 ? line + added - 1 : line;
468 const touched = added > 0 ? first <= to && last >= from : first >= from && first <= to + 1;
469 if (touched) {
470 out.push(...run.filter((o) => o.kind === "-").map((o) => o.line));
471 hunks++;
472 } else {
473 out.push(...run.filter((o) => o.kind === "+").map((o) => o.line));
474 }
475 line += added;
476 i = j;
477 }
478 return { text: out.length === 0 ? "" : `${out.join("\n")}\n`, hunks };
481/** file:12 or file:12-30, as typed; not a Windows drive letter (C:...). */
482const LINES = /^(.+?):(\d+)(?:-(\d+))?$/;
484export async function runRestore(args: Parsed, env: Env): Promise<Output> {
485 const all = bool(args, "all");
486 if (all === args.positionals.length > 0)
487 throw new UsageError(
488 "restore takes files, or --all: abso restore <file...> | abso restore <file>:<lines> | abso restore --all",
489 );
490 const { root, api } = open(env);
491 const ranged = args.positionals
492 .map((w) => LINES.exec(w))
493 .filter((m): m is RegExpExecArray => m !== null && !/^[A-Za-z]$/.test(m[1]!))
494 .map((m) => ({ file: fileArg(root, env.cwd, m[1]!), from: Number(m[2]), to: Number(m[3] ?? m[2]), typed: m[0] }));
495 const asked = args.positionals
496 .filter((w) => !ranged.some((r) => r.typed === w))
497 .map((w) => fileArg(root, env.cwd, w));
498 // Folder-only edits go to the server first, so they are discarded with the rest.
499 await recordFolder(root, api);
500 if (ranged.length > 0) {
501 // Some lines of a file: put those hunks back here, then record the file (#37, Builder 2).
502 const diff = await api.diff();
503 const lines: string[] = [];
504 for (const r of ranged) {
505 if (r.to < r.from) throw new UsageError(`${r.typed}: the range runs backwards`);
506 const change = diff.files.find((f) => f.path === r.file);
507 if (change === undefined || change.before === null || change.after === null || change.blob !== undefined) {
508 throw new UsageError(
509 `${r.file} has no line changes in your draft to restore (abso diff ${r.file} shows what it has)`,
510 );
511 }
512 const back = restoreLines(change.before, change.after, r.from, r.to);
513 if (back.hunks === 0)
514 throw new UsageError(
515 `none of your changes to ${r.file} touch lines ${r.from}-${r.to} (abso diff ${r.file} shows where they are)`,
516 );
517 const path = absolute(root, r.file);
518 writeFileAtomic(path, withEndingsOf(back.text, readText(path), undefined));
519 lines.push(
520 `Restored ${plural(back.hunks, "hunk")} of ${r.file} at ${r.from === r.to ? `line ${r.from}` : `lines ${r.from}-${r.to}`} to how ${diff.base === null ? "shared" : `version ${diff.base}`} has ${back.hunks === 1 ? "it" : "them"}; your other changes to it stay.`,
521 );
522 }
523 await recordFolder(root, api);
524 if (asked.length === 0)
525 return {
526 text: lines.join("\n"),
527 json: { restoredLines: ranged.map((r) => ({ file: r.file, from: r.from, to: r.to })) },
528 };
529 }
530 // The server's own paths, screened as a sync's are (safety.ts).
531 const { answer, refused } = screenAnswer(root, await api.restore(all ? null : asked));
532 const restored: string[] = [];
533 const deleted: string[] = [];
534 const fresh = newFileEndings(
535 root,
536 Object.entries(answer.files)
537 .filter(([rel, text]) => text !== null && !existsSync(absolute(root, rel)))
538 .map(([rel]) => rel),
539 );
540 for (const [rel, text] of Object.entries(answer.files).sort(
541 ([, a], [, b]) => Number(a !== null) - Number(b !== null),
542 )) {
543 const path = absolute(root, rel);
544 if (text === null) {
545 removeFile(path);
546 forgetKnown(root, rel);
547 deleted.push(rel);
548 } else {
549 const raw = readText(path);
550 writeFileAtomic(path, withEndingsOf(text, raw, fresh.get(rel)));
551 writeKnown(root, rel, normalize(text));
552 restored.push(rel);
553 }
554 }
555 const knownModes = readKnownModes(root);
556 for (const rel of deleted) knownModes.delete(rel);
557 for (const [rel, m] of Object.entries(answer.modes ?? {})) {
558 if (answer.files[rel] === null) continue;
559 const was = knownModes.get(rel) ?? PLAIN;
560 const mode = { exec: m.exec ?? was.exec, link: m.link === undefined ? was.link : m.link };
561 applyMode(absolute(root, rel), mode);
562 knownModes.set(rel, mode);
563 if (!restored.includes(rel)) restored.push(rel);
564 }
565 writeKnownModes(root, knownModes);
566 // Binary files go back to the bytes the server has.
567 const knownBlobs = readKnownBlobs(root);
568 for (const rel of [...deleted, ...Object.keys(answer.files)]) knownBlobs.delete(rel);
569 for (const [rel, sha] of Object.entries(answer.blobs ?? {})) {
570 if (sha === null) continue;
571 writeFileAtomic(absolute(root, rel), await api.getBlob(sha));
572 forgetKnown(root, rel);
573 knownBlobs.set(rel, sha);
574 if (!restored.includes(rel)) restored.push(rel);
575 }
576 writeKnownBlobs(root, knownBlobs);
577 const untouched = asked.filter(
578 (rel) => !(rel in answer.files) && !(rel in (answer.modes ?? {})) && !(rel in (answer.blobs ?? {})),
579 );
580 const lines = [
581 restored.length + deleted.length === 0
582 ? "Nothing to restore: no unpublished changes there."
583 : `Discarded your unpublished changes to ${plural(restored.length + deleted.length, "file")}:`,
584 ...restored.map((f) => ` restored ${f}`),
585 ...deleted.map((f) => ` deleted ${f} (it is new in your draft)`),
586 ...(untouched.length > 0 && restored.length + deleted.length > 0
587 ? [`No unpublished changes to: ${untouched.join(", ")}`]
588 : []),
589 ...refusedText(refused),
590 ];
591 return { text: lines.join("\n"), json: { restored, deleted, untouched, dropped: answer.dropped, refused } };