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