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