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?draft=names-only-client&format=json
148 linesFirst import 92% · pinch 5% · infra-split 2% · review 1%Last change pinch in version 1, 1 version 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 { globTest, snapshotAt, snapshotEntries } from "./at.ts";
18import { type Env, 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";
23/** The file an export leaves in its folder: what it holds, and the sign that the folder is one export may replace. */
24export const EXPORT_STAMP = ".abso-export";
25/** Its earlier names: an export made then still counts as one. A .json name drew the project's formatter. */
27/** Where an export may go: outside the abso folder, or in a part of it abso leaves out. Empty, or an earlier export. */
28function checkTarget(root: string, target: string): void {
29 const inside = relativeTo(root, target);
30 if (inside === undefined && (target === root || relativeTo(target, root) !== undefined)) {
31 throw new UsageError(`${target} holds this abso folder; export to a folder of its own`);
32 }
33 if (inside !== undefined && !ignoredHere(loadIgnore(root), inside, true)) {
34 throw new UsageError(
35 `${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`,
36 );
37 }
38 if (!existsSync(target)) return;
39 if (!statSync(target).isDirectory()) throw new UsageError(`${target} is a file; export to a folder`);
40 if (readdirSync(target).length > 0 && !existsSync(join(target, EXPORT_STAMP))) {
41 throw new UsageError(
42 `${target} has files in it; export to an empty folder (an export replaces only a folder an earlier export made)`,
43 );
44 }
47/**
48 * Empties an earlier export for the next, except what `keep` names: node_modules
49 * always (abso never exports it, and an install takes a while), and --keep's
50 * globs. Returns the kept paths, the top-most of each.
51 */
52function clearExport(dir: string, keep: (rel: string) => boolean, rel = ""): string[] {
53 const kept: string[] = [];
54 for (const e of readdirSync(join(dir, ...rel.split("/").filter(Boolean)), { withFileTypes: true })) {
55 const path = rel === "" ? e.name : `${rel}/${e.name}`;
56 const full = join(dir, ...path.split("/"));
57 if (e.name === "node_modules" || keep(path)) {
58 kept.push(path);
59 continue;
60 }
61 if (e.isDirectory() && !e.isSymbolicLink()) {
62 const inner = clearExport(dir, keep, path);
63 kept.push(...inner);
64 if (inner.length > 0) continue;
65 }
66 rmSync(full, { recursive: true, force: true });
67 }
68 return kept;
71export async function runExport(args: Parsed, env: Env): Promise<Output> {
72 if (args.positionals.length !== 1)
73 throw new UsageError("export takes the folder to write: abso export <dir> [--version <N>]");
74 const { root, config, api } = open(env);
75 const target = resolve(env.cwd, args.positionals[0]!);
76 checkTarget(root, target);
77 const rawVersion = str(args, "version");
78 if (rawVersion !== undefined && !/^\d+$/.test(rawVersion))
79 throw new UsageError(`--version is a version number (got ${JSON.stringify(rawVersion)})`);
80 const diff = await api.diff();
81 const where: Where = { draft: diff.draft };
82 // The listing names the version (the newest by default) and every file it holds; a server from before it answers 404.
83 const listing = await api
84 .filesAt(diff.draft, rawVersion === undefined ? undefined : Number(rawVersion))
85 .catch(() => undefined);
86 const version =
87 rawVersion !== undefined ? Number(rawVersion) : (listing?.version ?? (await api.log(where, 1)).version);
88 const snap = await snapshotAt(root, api, version);
89 const skipped: Refused[] = [];
90 if (listing !== undefined) {
91 const holds = new Set(listing.files);
92 for (const rel of [...snap.files.keys()]) if (!holds.has(rel)) snap.files.delete(rel);
93 // Files the known copies lack (a folder that missed some, #37): asked for one by one.
94 for (const rel of listing.files) {
95 if (snap.files.has(rel)) continue;
96 const file = await api.fileAt(rel, version, where);
97 if (file.text !== null) snap.files.set(rel, { text: file.text });
98 else
99 skipped.push({
100 path: rel,
101 why: "a binary file this folder has no copy of; abso sync --full, then export again",
102 });
103 }
104 }
105 const entries = await snapshotEntries(api, snap);
106 // Built before anything is removed, so a failed export leaves an earlier one whole.
107 const keepGlob = str(args, "keep");
108 const kept = existsSync(target) ? clearExport(target, keepGlob === undefined ? () => false : globTest(keepGlob)) : [];
109 mkdirSync(target, { recursive: true });
110 let written = 0;
111 for (const e of entries) {
112 const why = unsafePath(e.path) ?? (e.link !== undefined ? "it is a link; export makes none" : undefined);
113 if (why !== undefined) {
114 skipped.push({ path: e.path, why });
115 continue;
116 }
117 const path = join(target, ...e.path.split("/"));
118 mkdirSync(dirname(path), { recursive: true });
119 writeFileSync(path, e.data);
120 if (e.mode !== undefined) {
121 try {
122 chmodSync(path, e.mode);
123 } catch {
124 // The bit is a convenience here.
125 }
126 }
127 written++;
128 }
129 const space = diff.draft === null ? "shared" : `draft ${diff.draft}`;
130 const stamp = {
131 project: config.project,
132 space: diff.draft ?? "shared",
133 version,
134 files: written,
135 exportedAt: new Date().toISOString(),
136 };
137 writeFileSync(join(target, EXPORT_STAMP), `${JSON.stringify(stamp)}\n`);
138 return {
139 text: [
140 `Exported version ${version} of ${space} to ${target}: ${plural(written, "file")}. ${EXPORT_STAMP} there names the version; abso export to the same folder replaces it.`,
141 ...(kept.length > 0 ? [`Kept from the earlier export: ${kept.join(", ")}.`] : []),
142 ...(skipped.length > 0
143 ? [`Not exported (${skipped.length}):`, ...skipped.map((s) => ` ${s.path}: ${s.why}`)]
144 : []),
145 ].join("\n"),
146 json: { ...stamp, dir: target, kept, skipped },
147 };