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