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