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/export.ts?format=json
169 linesFirst import 78% · candidates 12% · pinch 5% · review 2% · infra-split 2% · rename 1%Last change candidates in version 186, 6 versions changed it
1// abso export <dir> [--version N]: one published version of this folder's
2// space, written to a folder of its own, for a build that doesn't move while
3// shared does (#37). The folder gets .abso-export naming the
4// version, to stamp the build with: JSON on one line, in a file with no
5// extension, so the exported project's own formatter and linter pass it by.
6// Exporting again replaces the folder, keeping node_modules (and what --keep
7// names) so a build needs no new install.
8//
9// The version is rebuilt as `abso run --at` rebuilds it (at.ts), from the
10// known copies and one compare; the server's listing of that version (#37)
11// then checks that no file is left out.
13import { chmodSync, existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
14import { dirname, join, resolve } from "node:path";
15import type { Where } from "./api.ts";
16import { type Parsed, str, UsageError } from "./args.ts";
17import { applySide, globTest, snapshotAt, snapshotEntries } from "./at.ts";
18import { type Env, EXIT, type Output, open, plural } from "./commands.ts";
19import { ignoredHere } from "./fetch.ts";
20import { loadIgnore, relativeTo } from "./folder.ts";
21import { type Refused, unsafePath } from "./safety.ts";
22import { refusalText, versionsText, withoutArg } from "./without.ts";
24/** The file an export leaves in its folder: what it holds, and the sign that the folder is one export may replace. */
25export const EXPORT_STAMP = ".abso-export";
26/** Its earlier names: an export made then still counts as one. A .json name drew the project's formatter. */
27const OLD_EXPORT_STAMPS = [".abso-export.json", ".avcs-export.json"];
29/** Where an export may go: outside the abso folder, or in a part of it abso leaves out. Empty, or an earlier export. */
30function checkTarget(root: string, target: string): void {
31 const inside = relativeTo(root, target);
32 if (inside === undefined && (target === root || relativeTo(target, root) !== undefined)) {
33 throw new UsageError(`${target} holds this abso folder; export to a folder of its own`);
34 }
35 if (inside !== undefined && !ignoredHere(loadIgnore(root), inside, true)) {
36 throw new UsageError(
37 `${inside} is inside this abso folder, so abso would record the export as your edits. Export outside the folder, or into a folder .absoignore leaves out`,
38 );
39 }
40 if (!existsSync(target)) return;
41 if (!statSync(target).isDirectory()) throw new UsageError(`${target} is a file; export to a folder`);
42 if (
43 readdirSync(target).length > 0 &&
44 ![EXPORT_STAMP, ...OLD_EXPORT_STAMPS].some((n) => existsSync(join(target, n)))
45 ) {
46 throw new UsageError(
47 `${target} has files in it; export to an empty folder (an export replaces only a folder an earlier export made)`,
48 );
49 }
52/**
53 * Empties an earlier export for the next, except what `keep` names: node_modules
54 * always (abso never exports it, and an install takes a while), and --keep's
55 * globs. Returns the kept paths, the top-most of each.
56 */
57function clearExport(dir: string, keep: (rel: string) => boolean, rel = ""): string[] {
58 const kept: string[] = [];
59 for (const e of readdirSync(join(dir, ...rel.split("/").filter(Boolean)), { withFileTypes: true })) {
60 const path = rel === "" ? e.name : `${rel}/${e.name}`;
61 const full = join(dir, ...path.split("/"));
62 if (e.name === "node_modules" || keep(path)) {
63 kept.push(path);
64 continue;
65 }
66 if (e.isDirectory() && !e.isSymbolicLink()) {
67 const inner = clearExport(dir, keep, path);
68 kept.push(...inner);
69 if (inner.length > 0) continue;
70 }
71 rmSync(full, { recursive: true, force: true });
72 }
73 return kept;
76export async function runExport(args: Parsed, env: Env): Promise<Output> {
77 if (args.positionals.length !== 1)
78 throw new UsageError("export takes the folder to write: abso export <dir> [--version <N>]");
79 const { root, config, api } = open(env);
80 const target = resolve(env.cwd, args.positionals[0]!);
81 checkTarget(root, target);
82 const rawVersion = str(args, "version");
83 if (rawVersion !== undefined && !/^\d+$/.test(rawVersion))
84 throw new UsageError(`--version is a version number (got ${JSON.stringify(rawVersion)})`);
85 const leave = withoutArg(args);
86 const diff = await api.diff();
87 const where: Where = { draft: diff.draft };
88 if (leave !== undefined && diff.draft !== null)
89 throw new UsageError(`--without reads shared, and this folder is on draft ${diff.draft}`);
90 // The listing names the version (the newest by default) and every file it holds; a server from before it answers 404.
91 const listing = await api
92 .filesAt(diff.draft, rawVersion === undefined ? undefined : Number(rawVersion))
93 .catch(() => undefined);
94 const version =
95 rawVersion !== undefined ? Number(rawVersion) : (listing?.version ?? (await api.log(where, 1)).version);
96 const snap = await snapshotAt(root, api, version);
97 const skipped: Refused[] = [];
98 if (listing !== undefined) {
99 const holds = new Set(listing.files);
100 for (const rel of [...snap.files.keys()]) if (!holds.has(rel)) snap.files.delete(rel);
101 // Files the known copies lack (a folder that missed some, #37): asked for one by one.
102 for (const rel of listing.files) {
103 if (snap.files.has(rel)) continue;
104 const file = await api.fileAt(rel, version, where);
105 if (file.text !== null) snap.files.set(rel, { text: file.text });
106 else
107 skipped.push({
108 path: rel,
109 why: "a binary file this folder has no copy of; abso pull --full, then export again",
110 });
111 }
112 }
113 // Without some versions: the server says what differs from this version, as it is without them.
114 const without = leave === undefined ? undefined : await api.without(version, leave);
115 if (without !== undefined && !without.ok)
116 return {
117 exit: EXIT.refused,
118 text: refusalText(
119 without,
120 (vs) => `abso export ${args.positionals[0]} --version ${version} --without ${vs.join(",")}`,
121 ),
122 json: { ...without },
123 };
124 if (without !== undefined) applySide(snap, without.files, "after");
125 const entries = await snapshotEntries(api, snap);
126 // Built before anything is removed, so a failed export leaves an earlier one whole.
127 const keepGlob = str(args, "keep");
128 const kept = existsSync(target) ? clearExport(target, keepGlob === undefined ? () => false : globTest(keepGlob)) : [];
129 mkdirSync(target, { recursive: true });
130 let written = 0;
131 for (const e of entries) {
132 const why = unsafePath(e.path) ?? (e.link !== undefined ? "it is a link; export makes none" : undefined);
133 if (why !== undefined) {
134 skipped.push({ path: e.path, why });
135 continue;
136 }
137 const path = join(target, ...e.path.split("/"));
138 mkdirSync(dirname(path), { recursive: true });
139 writeFileSync(path, e.data);
140 if (e.mode !== undefined) {
141 try {
142 chmodSync(path, e.mode);
143 } catch {
144 // The bit is a convenience here.
145 }
146 }
147 written++;
148 }
149 const space = diff.draft === null ? "shared" : `draft ${diff.draft}`;
150 const stamp = {
151 project: config.project,
152 space: diff.draft ?? "shared",
153 version,
154 ...(without !== undefined ? { without: without.without.map((w) => w.version), tree: without.tree } : {}),
155 files: written,
156 exportedAt: new Date().toISOString(),
157 };
158 writeFileSync(join(target, EXPORT_STAMP), `${JSON.stringify(stamp)}\n`);
159 return {
160 text: [
161 `Exported version ${version} of ${space}${without !== undefined ? ` without ${versionsText(without.without.map((w) => w.version))}` : ""} to ${target}: ${plural(written, "file")}. ${EXPORT_STAMP} there names the version; abso export to the same folder replaces it.`,
162 ...(kept.length > 0 ? [`Kept from the earlier export: ${kept.join(", ")}.`] : []),
163 ...(skipped.length > 0
164 ? [`Not exported (${skipped.length}):`, ...skipped.map((s) => ` ${s.path}: ${s.why}`)]
165 : []),
166 ].join("\n"),
167 json: { ...stamp, dir: target, kept, skipped },
168 };