- 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=76&format=json
611 linesFirst import 94% · pinch 5% · engine 1% · infra-split 1% · review 1%Last change pinch in version 52, 6 versions changed it
You're reading version 76. The newest is 318, and 3 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 { 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 };
37}
39function spaceName(draft: string | null): string {
40 return draft === null ? "shared" : `draft ${draft}`;
41}
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);
46}
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;
53}
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 };
96}
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 };
108}
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`;
120}
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));
125}
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 // --agent: someone else's draft, to review it. What they've recorded, not their folder; nothing here is recorded.
145 const other = str(args, "agent");
146 if (other !== undefined) {
147 if (between || str(args, "draft") !== undefined)
148 throw new UsageError("--agent shows that agent's unpublished changes: abso diff [file...] --agent <name>");
149 const answer = await api.diffOf(other);
150 const files = pick(answer.files);
151 const d = diffs(files);
152 const where = `${spaceName(answer.draft)}${answer.base === null ? "" : ` (on version ${answer.base})`}`;
153 const head =
154 files.length === 0
155 ? `${other} has no recorded, unpublished changes${inPaths(only, "to")} in ${where}.`
156 : `${other}'s recorded, unpublished changes${inPaths(only, "to")} in ${where}: ${totals(files)}.`;
157 return {
158 text: [head, ...d.text].join("\n"),
159 json: { agent: other, draft: answer.draft, base: answer.base, files: d.json, unmatched: unmatched(files) },
160 };
161 }
163 if (between) {
164 const from = version(words[0]!);
165 const to = version(words[1]!);
166 const where = space(args, config.agent);
167 const answer = await api.compare(from, to, where);
168 const files = pick(answer.files);
169 const d = diffs(files);
170 const head =
171 files.length === 0
172 ? `No differences between versions ${from} and ${to} of ${whereName(where)}${inPaths(only)}.`
173 : `From version ${from} to ${to} of ${whereName(where)}${inPaths(only)}: ${totals(files)}.`;
174 return {
175 text: [head, ...notes(files), ...d.text].join("\n"),
176 json: { ...where, from, to, files: d.json, unmatched: unmatched(files) },
177 };
178 }
180 if (str(args, "draft") !== undefined)
181 throw new UsageError(
182 "--draft goes with two versions (abso diff <from> <to>); abso diff alone shows your own unpublished changes",
183 );
184 // Folder-only edits count as unpublished changes too.
185 const recorded = await recordFolder(root, api);
186 const answer = await api.diff();
187 const files = pick(answer.files);
188 const d = diffs(files);
189 const where = `${spaceName(answer.draft)}${answer.base === null ? "" : ` (on version ${answer.base})`}`;
190 const head =
191 files.length === 0
192 ? `No unpublished changes${inPaths(only, "to")} in ${where}.`
193 : `Your unpublished changes${inPaths(only, "to")} in ${where}: ${totals(files)}.`;
194 const pre = recordedFirst(recorded);
195 return {
196 text: [...pre, head, ...notes(files), ...d.text].join("\n"),
197 json: {
198 draft: answer.draft,
199 base: answer.base,
200 files: d.json,
201 recorded: recorded.sent,
202 unmatched: unmatched(files),
203 },
204 };
205}
207const LOG_FILES = 8;
208/** How far back `abso log <folder>` looks, since the client filters it. */
209const FOLDER_LOG = 1000;
211/** A path as typed, folder-relative: "" for the whole folder. A folder stands for every file under it. */
212function pathArg(root: string, cwd: string, typed: string): string {
213 if (relative(root, resolve(cwd, typed)) === "") return "";
214 return fileArg(root, cwd, typed);
215}
217/** Whether `path` is `p`, or under the folder `p` ("" is everything). */
218function under(path: string, p: string): boolean {
219 return p === "" || path === p || path.startsWith(`${p}/`);
220}
222function isFolder(root: string, p: string): boolean {
223 try {
224 return statSync(absolute(root, p)).isDirectory();
225 } catch {
226 return false;
227 }
228}
230function existsHere(root: string, p: string): boolean {
231 return p === "" || existsSync(absolute(root, p));
232}
234/** The line for a path that matched no changed file. */
235function nothingAt(root: string, p: string): string {
236 if (!existsHere(root, p))
237 return ` ${p}: no such file or folder here now (paths are relative to where you run abso).`;
238 return ` ${p === "" ? "the whole folder" : `${p}${isFolder(root, p) ? "/" : ""}`}: no changes there.`;
239}
241/** " in a.ts, harness" (or " to ...") for the paths a command was limited to. */
242function inPaths(only: readonly string[], word = "in"): string {
243 return only.length === 0 ? "" : ` ${word} ${only.map((p) => (p === "" ? "the whole folder" : p)).join(", ")}`;
244}
246/** How many renames `abso log <file>` follows back. */
247const FOLLOW_RENAMES = 20;
249type FollowedEntry = LogEntry & { readonly renamedFrom?: string };
251/**
252 * A file's log that goes on past a rename, like `git log --follow`: where the
253 * oldest version found is the one that renamed the file into being, the
254 * versions before it come from the old path's log.
255 */
256async function followRenames(
257 api: Api,
258 where: Where,
259 path: string,
260 first: LogAnswer,
261 limit: number | undefined,
262): Promise<FollowedEntry[]> {
263 const versions: FollowedEntry[] = [...first.versions];
264 let current = path;
265 for (let hops = 0; hops < FOLLOW_RENAMES; hops++) {
266 if (limit !== undefined && versions.length >= limit) break;
267 const oldest = versions[versions.length - 1];
268 if (oldest === undefined || oldest.version === 0) break;
269 const renamed = pairRenames((await api.show(oldest.version, where)).diff).find(
270 (f) => f.path === current && f.from !== undefined,
271 );
272 if (renamed === undefined) break;
273 versions[versions.length - 1] = { ...oldest, renamedFrom: renamed.from! };
274 const earlier = (await api.log(where, FOLDER_LOG, renamed.from)).versions.filter((v) => v.version < oldest.version);
275 versions.push(...earlier.slice(0, limit === undefined ? 50 : limit - versions.length));
276 current = renamed.from!;
277 }
278 return versions;
279}
281/** What else a version says: its labels, what it dropped or what dropped it, and its first message when amended. */
282function notes(v: FollowedEntry): string[] {
283 const out: string[] = [];
284 if (v.renamedFrom !== undefined)
285 out.push(` renamed from ${v.renamedFrom}; the versions below are its history under that name`);
286 if (v.labels && v.labels.length > 0) out.push(` labels: ${v.labels.join(", ")}`);
287 if (v.drops && v.drops.length > 0)
288 out.push(` drops ${v.drops.length === 1 ? "version" : "versions"} ${v.drops.join(", ")}`);
289 if (v.droppedIn !== undefined) out.push(` dropped in version ${v.droppedIn}: shared no longer has these changes`);
290 if (v.originalMessage !== undefined) out.push(` amended; first published as: ${v.originalMessage}`);
291 return out;
292}
294/**
295 * --since: a version number (the versions after it), a span back from now
296 * (30m, 2h, 1d), or a date and time Date.parse reads (2026-10-05T17:00).
297 */
298export function sinceTest(raw: string, now: number): (v: LogEntry) => boolean {
299 if (/^\d+$/.test(raw)) {
300 const n = Number(raw);
301 return (v) => v.version > n;
302 }
303 const span = /^(\d+)\s*(m|min|h|d)$/.exec(raw);
304 // A bare clock time (20:00) is today's, local; yesterday's when today's hasn't come yet (#37, Reporter).
305 const clock = /^(\d{1,2}):(\d{2})$/.exec(raw);
306 const today = (h: number, m: number) => {
307 const d = new Date(now);
308 d.setHours(h, m, 0, 0);
309 return d.getTime() > now ? d.getTime() - 86_400_000 : d.getTime();
310 };
311 const at = span
312 ? now -
313 Number(span[1]) * { m: 60_000, min: 60_000, h: 3_600_000, d: 86_400_000 }[span[2] as "m" | "min" | "h" | "d"]
314 : clock && Number(clock[1]) < 24 && Number(clock[2]) < 60
315 ? today(Number(clock[1]), Number(clock[2]))
316 : Date.parse(raw);
317 if (Number.isNaN(at))
318 throw new UsageError(
319 `--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)}`,
320 );
321 return (v) => v.time >= at;
322}
324export async function runLog(args: Parsed, env: Env): Promise<Output> {
325 if (args.positionals.length > 1)
326 throw new UsageError("log takes at most one file: abso log [file] [-n <count>] [--draft <name>]");
327 const { root, config, api } = open(env);
328 const typed = args.positionals[0];
329 const path = typed === undefined ? undefined : pathArg(root, env.cwd, typed);
330 const rawLimit = str(args, "limit");
331 const limit = rawLimit === undefined ? undefined : version(rawLimit, "-n");
332 if (limit === 0) throw new UsageError("-n is how many versions to show; give 1 or more");
333 const rawBefore = str(args, "before");
334 const before = rawBefore === undefined ? undefined : version(rawBefore, "--before");
335 // The server filters by one file; a folder (or the whole folder) is filtered here, from a longer log.
336 const folder = path !== undefined && (path === "" || /[/]$/.test(typed!) || isFolder(root, path));
337 // --since, --by and --count (#37, Reporter's progress reports) filter here, from a longer log.
338 const since = str(args, "since");
339 const by = str(args, "by");
340 const count = bool(args, "count");
341 const filtering = since !== undefined || by !== undefined || count;
342 const keep = since === undefined ? () => true : sinceTest(since, Date.now());
343 const agents =
344 by === undefined
345 ? undefined
346 : new Set(
347 by
348 .split(",")
349 .map((a) => a.trim())
350 .filter((a) => a !== ""),
351 );
352 const raw = await api.log(
353 space(args, config.agent),
354 folder || filtering ? FOLDER_LOG : limit,
355 folder ? undefined : path,
356 before,
357 );
358 const found = folder
359 ? {
360 ...raw,
361 versions: raw.versions
362 .filter((v) => v.files.some((f) => under(f, path!)))
363 .slice(0, filtering ? FOLDER_LOG : (limit ?? 50)),
364 }
365 : path !== undefined
366 ? {
367 ...raw,
368 versions: await followRenames(api, space(args, config.agent), path, raw, filtering ? FOLDER_LOG : limit),
369 }
370 : raw;
371 const answer = filtering
372 ? {
373 ...found,
374 versions: found.versions
375 .filter((v) => keep(v) && (agents === undefined || agents.has(v.agent)))
376 .slice(0, limit ?? FOLDER_LOG),
377 }
378 : found;
379 if (count) {
380 // Versions and files per agent, most first.
381 const per = new Map<string, { versions: number; files: Set<string> }>();
382 for (const v of answer.versions) {
383 const a = per.get(v.agent) ?? { versions: 0, files: new Set<string>() };
384 a.versions++;
385 for (const f of v.files) a.files.add(f);
386 per.set(v.agent, a);
387 }
388 const rows = [...per].sort(([a, x], [b, y]) => y.versions - x.versions || a.localeCompare(b));
389 const scope = [
390 since === undefined ? "" : /^\d+$/.test(since) ? ` since version ${since}` : ` since ${since}`,
391 agents === undefined ? "" : ` by ${[...agents].join(", ")}`,
392 ].join("");
393 return {
394 text: [
395 `${spaceName(answer.draft)} is at version ${answer.version}. ${plural(answer.versions.length, "version")}${scope}${answer.versions.length > 0 ? ", per agent:" : "."}`,
396 ...rows.map(([agent, a]) => ` ${agent}: ${plural(a.versions, "version")}, ${plural(a.files.size, "file")}`),
397 ].join("\n"),
398 json: {
399 draft: answer.draft,
400 version: answer.version,
401 versions: answer.versions.length,
402 agents: Object.fromEntries(rows.map(([agent, a]) => [agent, { versions: a.versions, files: a.files.size }])),
403 },
404 };
405 }
406 const named = path === undefined ? "" : path === "" ? "the whole folder" : folder ? `${path}/` : path;
407 const lines = [
408 `${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:`}`,
409 ...(path !== undefined && answer.versions.length === 0 && !existsHere(root, path) ? [nothingAt(root, path)] : []),
410 ...answer.versions.flatMap((v) => [
411 `version ${v.version} by ${byWhom(v)}, ${when(v.time)}${answer.draft === null ? ciMarkText(v.ci) : ""}: ${v.message}`,
412 ` ${plural(v.files.length, "file")}: ${v.files.slice(0, LOG_FILES).join(", ")}${v.files.length > LOG_FILES ? `, and ${v.files.length - LOG_FILES} more` : ""}`,
413 ...notes(v),
414 ]),
415 ];
416 const oldest = answer.versions[answer.versions.length - 1];
417 if (!filtering && !folder && raw.next !== undefined && oldest !== undefined)
418 lines.push(`Older versions: abso log${typed === undefined ? "" : ` ${typed}`} --before ${oldest.version}`);
419 if (filtering && answer.versions.length === 0) lines.push("No version matches.");
420 // A filter or a folder reads the newest FOLDER_LOG versions; say so when older ones were left unread.
421 if ((filtering || folder) && raw.next !== undefined)
422 lines.push(
423 `Only the newest ${FOLDER_LOG} versions${before === undefined ? "" : ` below ${before}`} were read; --before ${raw.next} reads older ones.`,
424 );
425 return { text: lines.join("\n"), json: { ...answer } };
426}
428export async function runShow(args: Parsed, env: Env): Promise<Output> {
429 if (args.positionals.length !== 1)
430 throw new UsageError("show takes one version: abso show <version> or abso show <version>:<file>");
431 const { root, config, api } = open(env);
432 const word = args.positionals[0]!;
433 const colon = word.indexOf(":");
434 const where = space(args, config.agent);
436 if (colon >= 0) {
437 const v = version(word.slice(0, colon));
438 const path = fileArg(root, env.cwd, word.slice(colon + 1));
439 const answer = await api.fileAt(path, v, where);
440 if (answer.text === null)
441 return {
442 exit: EXIT.error,
443 text: `${path} did not exist at version ${v} of ${whereName(where)}.`,
444 json: { ...answer, ...where },
445 };
446 return { text: answer.text, json: { ...answer, ...where } };
447 }
449 const answer = await api.show(version(word), where);
450 const changed = pairRenames(answer.diff);
451 const d = diffs(changed);
452 const lines = [
453 `version ${answer.version} of ${spaceName(answer.draft)} by ${byWhom(answer)}, ${when(answer.time)}: ${answer.message}`,
454 ...notes(answer),
455 changed.length === 0 ? "It changed no files." : `${totals(changed)}.`,
456 ...d.text,
457 ];
458 return { text: lines.join("\n"), json: { ...answer, diff: d.json } };
459}
461/**
462 * A file's text with the draft's hunks that touch lines `from`-`to` (of the
463 * file as it is now, as abso diff numbers them) put back as they were at the
464 * base; the other hunks stay (#37: drop my copy of a teammate's
465 * half and keep the rest). A hunk that only deleted lines touches the line
466 * where they were.
467 */
468export function restoreLines(before: string, after: string, from: number, to: number): { text: string; hunks: number } {
469 const ops = editScript(linesOf(before), linesOf(after));
470 const out: string[] = [];
471 let hunks = 0;
472 let line = 1; // the next line of the file as it is now
473 for (let i = 0; i < ops.length; ) {
474 if (ops[i]!.kind === " ") {
475 out.push(ops[i]!.line);
476 line++;
477 i++;
478 continue;
479 }
480 // One hunk: the run of - and + ops.
481 let j = i;
482 while (j < ops.length && ops[j]!.kind !== " ") j++;
483 const run = ops.slice(i, j);
484 const added = run.filter((o) => o.kind === "+").length;
485 const first = line;
486 const last = added > 0 ? line + added - 1 : line;
487 const touched = added > 0 ? first <= to && last >= from : first >= from && first <= to + 1;
488 if (touched) {
489 out.push(...run.filter((o) => o.kind === "-").map((o) => o.line));
490 hunks++;
491 } else {
492 out.push(...run.filter((o) => o.kind === "+").map((o) => o.line));
493 }
494 line += added;
495 i = j;
496 }
497 return { text: out.length === 0 ? "" : `${out.join("\n")}\n`, hunks };
498}
500/** file:12 or file:12-30, as typed; not a Windows drive letter (C:...). */
501const LINES = /^(.+?):(\d+)(?:-(\d+))?$/;
503export async function runRestore(args: Parsed, env: Env): Promise<Output> {
504 const all = bool(args, "all");
505 if (all === args.positionals.length > 0)
506 throw new UsageError(
507 "restore takes files, or --all: abso restore <file...> | abso restore <file>:<lines> | abso restore --all",
508 );
509 const { root, api } = open(env);
510 const ranged = args.positionals
511 .map((w) => LINES.exec(w))
512 .filter((m): m is RegExpExecArray => m !== null && !/^[A-Za-z]$/.test(m[1]!))
513 .map((m) => ({ file: fileArg(root, env.cwd, m[1]!), from: Number(m[2]), to: Number(m[3] ?? m[2]), typed: m[0] }));
514 const asked = args.positionals
515 .filter((w) => !ranged.some((r) => r.typed === w))
516 .map((w) => fileArg(root, env.cwd, w));
517 // Folder-only edits go to the server first, so they are discarded with the rest.
518 await recordFolder(root, api);
519 if (ranged.length > 0) {
520 // Some lines of a file: put those hunks back here, then record the file (#37).
521 const diff = await api.diff();
522 const lines: string[] = [];
523 for (const r of ranged) {
524 if (r.to < r.from) throw new UsageError(`${r.typed}: the range runs backwards`);
525 const change = diff.files.find((f) => f.path === r.file);
526 if (change === undefined || change.before === null || change.after === null || change.blob !== undefined) {
527 throw new UsageError(
528 `${r.file} has no line changes in your draft to restore (abso diff ${r.file} shows what it has)`,
529 );
530 }
531 const back = restoreLines(change.before, change.after, r.from, r.to);
532 if (back.hunks === 0)
533 throw new UsageError(
534 `none of your changes to ${r.file} touch lines ${r.from}-${r.to} (abso diff ${r.file} shows where they are)`,
535 );
536 const path = absolute(root, r.file);
537 writeFileAtomic(path, withEndingsOf(back.text, readText(path), undefined));
538 lines.push(
539 `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.`,
540 );
541 }
542 await recordFolder(root, api);
543 if (asked.length === 0)
544 return {
545 text: lines.join("\n"),
546 json: { restoredLines: ranged.map((r) => ({ file: r.file, from: r.from, to: r.to })) },
547 };
548 }
549 // The server's own paths, screened as a sync's are (safety.ts).
550 const { answer, refused } = screenAnswer(root, await api.restore(all ? null : asked));
551 const restored: string[] = [];
552 const deleted: string[] = [];
553 const fresh = newFileEndings(
554 root,
555 Object.entries(answer.files)
556 .filter(([rel, text]) => text !== null && !existsSync(absolute(root, rel)))
557 .map(([rel]) => rel),
558 );
559 for (const [rel, text] of Object.entries(answer.files).sort(
560 ([, a], [, b]) => Number(a !== null) - Number(b !== null),
561 )) {
562 const path = absolute(root, rel);
563 if (text === null) {
564 removeFile(path);
565 forgetKnown(root, rel);
566 deleted.push(rel);
567 } else {
568 const raw = readText(path);
569 writeFileAtomic(path, withEndingsOf(text, raw, fresh.get(rel)));
570 writeKnown(root, rel, normalize(text));
571 restored.push(rel);
572 }
573 }
574 const knownModes = readKnownModes(root);
575 for (const rel of deleted) knownModes.delete(rel);
576 for (const [rel, m] of Object.entries(answer.modes ?? {})) {
577 if (answer.files[rel] === null) continue;
578 const was = knownModes.get(rel) ?? PLAIN;
579 const mode = { exec: m.exec ?? was.exec, link: m.link === undefined ? was.link : m.link };
580 applyMode(absolute(root, rel), mode);
581 knownModes.set(rel, mode);
582 if (!restored.includes(rel)) restored.push(rel);
583 }
584 writeKnownModes(root, knownModes);
585 // Binary files go back to the bytes the server has.
586 const knownBlobs = readKnownBlobs(root);
587 for (const rel of [...deleted, ...Object.keys(answer.files)]) knownBlobs.delete(rel);
588 for (const [rel, sha] of Object.entries(answer.blobs ?? {})) {
589 if (sha === null) continue;
590 writeFileAtomic(absolute(root, rel), await api.getBlob(sha));
591 forgetKnown(root, rel);
592 knownBlobs.set(rel, sha);
593 if (!restored.includes(rel)) restored.push(rel);
594 }
595 writeKnownBlobs(root, knownBlobs);
596 const untouched = asked.filter(
597 (rel) => !(rel in answer.files) && !(rel in (answer.modes ?? {})) && !(rel in (answer.blobs ?? {})),
598 );
599 const lines = [
600 restored.length + deleted.length === 0
601 ? "Nothing to restore: no unpublished changes there."
602 : `Discarded your unpublished changes to ${plural(restored.length + deleted.length, "file")}:`,
603 ...restored.map((f) => ` restored ${f}`),
604 ...deleted.map((f) => ` deleted ${f} (it is new in your draft)`),
605 ...(untouched.length > 0 && restored.length + deleted.length > 0
606 ? [`No unpublished changes to: ${untouched.join(", ")}`]
607 : []),
608 ...refusedText(refused),
609 ];
610 return { text: lines.join("\n"), json: { restored, deleted, untouched, dropped: answer.dropped, refused } };
611}