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=310&format=json
657 linesFirst import 86% · candidates 7% · pinch 4% · rename 2% · engine 1% · infra-split 1% · review 1%Last change candidates in version 186, 9 versions changed it

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