Repository navigation
Expand file tree
/
Copy pathkit.ts
More file actions
269 lines (250 loc) · 11.9 KB
/
Copy pathkit.ts
File metadata and controls
269 lines (250 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// The kit: everything catpad runs that is not catpad. One archive per
// platform holds
//
// toolchain/ Lean and Lake, as their release ships them, without the C
// compiler (catpad checks Lean; it does not build programs)
// lib/<pkg>/ Mathlib and the packages it uses, compiled
// draw/ tectonic (TeX) and poppler's pdftocairo, which draw the diagrams
// tex/ the TeX files the diagrams use, so tectonic fetches nothing
// kit.json what is in it: the manifest
//
// The versions are pinned in kit.json at the top of the repository, and
// lean/lake-manifest.json pins every Lean package to a commit. KIT_ID is a
// hash of the two: change a pin and it is a different kit. scripts/kit.ts
// builds the archive; the release workflow puts it inside the AppImage and
// the disk image, and publishes it as the release `kit-<id>`.
//
// Here, the app's side. The kit is unpacked once into DATA/kit/<id>, and
// everything runs from there. Where the archive comes from, in order:
//
// 1. CATPAD_KIT_ARCHIVE, a file
// 2. inside the app: ROOT/kit/catpad-kit-<platform>.tar.zst (the macOS app)
// 3. DATA/kit/<id>.tar.zst, where the AppImage puts it before it starts the app
// 4. the release kit-<id>, downloaded and checked against its SHA-256. This
// is how an app that updated itself gets a newer kit, and how Windows
// gets its first.
//
// Nothing here uses the machine's own tools: Bun decompresses, tar.ts
// unpacks, and the kit's own leantar expands the compiled Lean files.
//
// CATPAD_KIT_DIR use this unpacked kit instead of DATA/kit/<id>
// CATPAD_KIT_ARCHIVE unpack this archive
// CATPAD_KIT_URL download from here instead of the GitHub release
import { spawn } from "bun";
import { createHash } from "crypto";
import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statfsSync, statSync, writeFileSync } from "fs";
import { join } from "path";
import { createZstdDecompress } from "zlib";
import pins from "./kit.json";
import lake from "./lean/lake-manifest.json";
import { DATA, IN_APP, ROOT } from "./paths";
import { untar } from "./tar";
export { pins };
const OS = process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : "linux";
export const PLATFORM = `${OS}-${process.arch}`;
export const EXE = OS === "windows" ? ".exe" : "";
// The Lean packages, each at its commit, as lake-manifest.json locks them.
export const PACKAGES: { name: string; rev: string }[] = (lake as any).packages.map((p: any) => ({ name: p.name, rev: p.rev }));
export const KIT_ID = (() => {
const { about, ...pinned } = pins as any;
return createHash("sha256").update(JSON.stringify([pinned, PACKAGES])).digest("hex").slice(0, 12);
})();
export const ARCHIVE = `catpad-kit-${PLATFORM}.tar.zst`;
const REPO = process.env.CATPAD_UPDATE_REPO || "tlehman/catpad";
const URL_BASE = process.env.CATPAD_KIT_URL || `https://github.com/${REPO}/releases/download/kit-${KIT_ID}`;
const KITS = join(DATA, "kit");
// What an archive says about itself (its kit.json), and its sidecar next to it in a release.
export interface KitManifest {
id: string;
platform: string;
lean: string;
mathlib: { rev: string; commit: string };
tectonic: string;
poppler: string;
packages: { name: string; rev: string }[];
leanPath: string[]; // directories of compiled Lean, relative to the kit
packs: string[]; // leantar files to expand after unpacking, relative to the kit
bytes: number; // on disk, unpacked
built: string;
}
export interface KitSidecar { id: string; platform: string; file: string; bytes: number; sha256: string; unpacked: number }
export interface Kit {
dir: string;
manifest: KitManifest;
sysroot: string;
leanPath: string[];
tectonic: string;
pdftocairo: string;
drawEnv: Record<string, string>;
}
function open(dir: string): Kit | null {
try {
if (!existsSync(join(dir, ".complete"))) return null;
const manifest: KitManifest = JSON.parse(readFileSync(join(dir, "kit.json"), "utf8"));
return {
dir, manifest,
sysroot: join(dir, "toolchain"),
leanPath: manifest.leanPath.map((p) => join(dir, p)),
tectonic: join(dir, "draw", "bin", `tectonic${EXE}`),
pdftocairo: join(dir, "draw", "bin", `pdftocairo${EXE}`),
// tectonic reads its TeX files from the kit, and pdftocairo's fontconfig
// reads a configuration that names no fonts: the PDFs carry their own.
drawEnv: { TECTONIC_CACHE_DIR: join(dir, "tex"), FONTCONFIG_FILE: join(dir, "draw", "fonts.conf"), FONTCONFIG_PATH: join(dir, "draw") },
};
} catch {
return null;
}
}
let found: Kit | null = null;
// The unpacked kit this catpad runs on, or null when it is not there yet.
export function findKit(): Kit | null {
return (found ??= open(process.env.CATPAD_KIT_DIR || join(KITS, KIT_ID)));
}
// ---------- unpacking ----------
type Log = (line: string) => void;
const gb = (n: number) => `${(n / 1e9).toFixed(1)} GB`;
// Says `what: n%` every 5%.
function percent(log: Log, what: string) {
let said = -1;
return (done: number, total: number) => {
const p = total ? Math.min(100, Math.floor((done / total) * 20) * 5) : 0;
if (p !== said) { said = p; log(`${what}: ${p}%`); }
};
}
// Unpacks `archive` into `dir`: the tar, then the compiled Lean files, which
// are packed with leantar (Lean's own packer for them, a quarter of the size
// zstd gets). Throws when the archive is another kit's, or the disk is too small.
export async function unpackKit(archive: string, dir: string, log: Log, expect: { id?: string; platform?: string } = { id: KIT_ID, platform: PLATFORM }): Promise<KitManifest> {
const part = `${dir}.part`;
rmSync(part, { recursive: true, force: true });
mkdirSync(part, { recursive: true });
const total = statSync(archive).size;
const said = percent(log, "Unpacking Lean, Mathlib and the diagram tools (once)");
let read = 0;
const file = createReadStream(archive, { highWaterMark: 1 << 20 });
const zstd = createZstdDecompress();
file.on("data", (c) => { read += c.length; said(read, total); });
file.on("error", (e) => zstd.destroy(e));
let manifest: KitManifest | null = null;
try {
await untar(file.pipe(zstd), part, {
onFile(name) {
if (name !== "kit.json" || manifest) return;
// The manifest is the archive's first file, so a wrong archive stops here.
const m: KitManifest = (manifest = JSON.parse(readFileSync(join(part, "kit.json"), "utf8")));
if (expect.id && m.id !== expect.id) throw new Error(`this archive is kit ${m.id}, and this catpad runs on kit ${expect.id}`);
if (expect.platform && m.platform !== expect.platform) throw new Error(`this archive is for ${m.platform}, and this computer is ${expect.platform}`);
const { bavail, bsize } = statfsSync(part);
const free = Number(bavail) * Number(bsize), need = m.bytes + 5e8;
if (free < need) throw new Error(`there is ${gb(free)} free on this disk, and Lean and Mathlib take ${gb(need)}. Free some space and start catpad again.`);
},
});
const m = manifest as KitManifest | null;
if (!m) throw new Error("the archive has no kit.json, so it is not a catpad kit");
// The compiled Lean files. leantar reads the names of its files from stdin, and uses every core.
const leantar = join(part, "toolchain", "bin", `leantar${EXE}`);
const expanded = percent(log, "Unpacking Mathlib's compiled files (once)");
const BATCH = 500;
for (let i = 0; i < m.packs.length; i += BATCH) {
expanded(i, m.packs.length);
const p = spawn([leantar, "-C", part, "-x", "-f", "-"], { cwd: part, stdin: "pipe", stdout: "ignore", stderr: "pipe" });
p.stdin.write(m.packs.slice(i, i + BATCH).join("\n") + "\n");
await p.stdin.end();
const err = await new Response(p.stderr).text();
if ((await p.exited) !== 0) throw new Error(`leantar could not unpack Mathlib: ${err.trim().split("\n").slice(-3).join(" ")}`);
}
expanded(1, 1);
rmSync(join(part, "packs"), { recursive: true, force: true });
writeFileSync(join(part, ".complete"), new Date().toISOString() + "\n");
rmSync(dir, { recursive: true, force: true });
renameSync(part, dir);
return m;
} catch (e) {
file.destroy();
rmSync(part, { recursive: true, force: true });
throw e;
}
}
// ---------- downloading ----------
async function download(dest: string, log: Log): Promise<void> {
const url = `${URL_BASE}/${ARCHIVE}`;
let side: KitSidecar;
try {
const r = await fetch(`${url}.json`, { redirect: "follow", signal: AbortSignal.timeout(30000) });
if (!r.ok) throw new Error(`HTTP ${r.status}`);
side = (await r.json()) as KitSidecar;
} catch (e: any) {
throw new Error(`kit ${KIT_ID} for ${PLATFORM} could not be found at ${URL_BASE} (${e?.message ?? e}). Check the network, or download catpad again from its releases page: the download carries the kit.`);
}
log(`Downloading Lean, Mathlib and the diagram tools: ${gb(side.bytes)} from ${url}`);
const r = await fetch(url, { redirect: "follow" });
if (!r.ok || !r.body) throw new Error(`could not download ${url} (HTTP ${r.status})`);
const part = `${dest}.part`;
const out = Bun.file(part).writer({ highWaterMark: 1 << 22 });
const hash = createHash("sha256");
const said = percent(log, `Downloading Lean, Mathlib and the diagram tools (${gb(side.bytes)}, once)`);
let got = 0;
try {
for await (const chunk of r.body) {
hash.update(chunk);
out.write(chunk);
got += chunk.length;
const flushed = out.flush();
if (flushed instanceof Promise) await flushed;
said(got, side.bytes);
}
await out.end();
const sum = hash.digest("hex");
if (sum !== side.sha256) throw new Error(`the download is damaged (SHA-256 ${sum}, expected ${side.sha256})`);
renameSync(part, dest);
} catch (e) {
try { await out.end(); } catch {}
rmSync(part, { force: true });
throw e;
}
}
// ---------- installing ----------
// What older catpads fetched into DATA: elan's Lean project with Mathlib, and
// the conda prefix with tectonic and poppler. The kit replaces them.
function removeLegacy(log: Log) {
if (!IN_APP || process.env.CATPAD_LEAN_DIR) return;
for (const d of ["lean", "tools", "micromamba", "bin"]) {
const p = join(DATA, d);
if (!existsSync(p)) continue;
log(`Removing ${p}: an older catpad kept it, and the kit replaces it`);
try { rmSync(p, { recursive: true, force: true }); } catch {}
}
}
// Puts the kit in DATA/kit/<id>, from the first place that has it.
export async function installKit(log: Log): Promise<Kit> {
if (process.env.CATPAD_KIT_DIR) throw new Error(`CATPAD_KIT_DIR is ${process.env.CATPAD_KIT_DIR}, and there is no unpacked kit there`);
mkdirSync(KITS, { recursive: true });
const dir = join(KITS, KIT_ID);
const staged = join(KITS, `${KIT_ID}.tar.zst`);
const local = [process.env.CATPAD_KIT_ARCHIVE, join(ROOT, "kit", ARCHIVE), staged].filter((f): f is string => !!f && existsSync(f));
let done = false;
for (const archive of local) {
try {
log(`Unpacking ${archive}`);
await unpackKit(archive, dir, log);
430F
done = true;
break;
} catch (e: any) {
log(`${archive}: ${e?.message ?? e}`);
// Out of space is the same story from any archive.
if (/free on this disk/.test(String(e?.message))) throw e;
}
}
if (!done) {
await download(staged, log);
await unpackKit(staged, dir, log);
}
// Only this kit stays: an older one, and the archive this one came from.
for (const f of readdirSync(KITS)) if (f !== KIT_ID) try { rmSync(join(KITS, f), { recursive: true, force: true }); } catch {}
removeLegacy(log);
found = null;
const kit = findKit();
if (!kit) throw new Error(`the kit was unpacked into ${dir}, and it is not complete`);
log(`Lean ${kit.manifest.lean}, Mathlib ${kit.manifest.mathlib.rev}, tectonic ${kit.manifest.tectonic} and poppler ${kit.manifest.poppler} are in ${dir}`);
return kit;
}