Repository navigation
Expand file tree
/
Copy pathtar.ts
More file actions
217 lines (199 loc) · 9.4 KB
/
Copy pathtar.ts
File metadata and controls
217 lines (199 loc) · 9.4 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
// Tar, read and written as a stream, so catpad unpacks its kit (kit.ts) and
// the Lean and tectonic releases (scripts/kit.ts) without asking the machine
// for a `tar` or a `zstd`: Bun decompresses, and this does the rest.
//
// Written: ustar headers, with GNU long names ('L', 'K') for paths over 100
// bytes. Read: those, plus pax headers ('x'), which is what the tars of the
// Lean and tectonic releases use between them.
import { chmodSync, closeSync, copyFileSync, createReadStream, existsSync, linkSync, lstatSync, mkdirSync, openSync, readlinkSync, rmSync, statSync, symlinkSync, writeSync } from "fs";
import { dirname, join, resolve } from "path";
const BLOCK = 512;
const enc = new TextEncoder();
const dec = new TextDecoder();
const WIN = process.platform === "win32";
type Sink = (chunk: Uint8Array) => Promise<void> | void;
function header(name: Uint8Array, size: number, mode: number, type: string, link: Uint8Array): Uint8Array {
const h = new Uint8Array(BLOCK);
const put = (text: string | Uint8Array, at: number, len: number) => h.set((typeof text === "string" ? enc.encode(text) : text).subarray(0, len), at);
const octal = (n: number, len: number) => n.toString(8).padStart(len - 1, "0") + "\0";
put(name, 0, 100);
put(octal(mode & 0o7777, 8), 100, 8);
put(
F784
octal(0, 8), 108, 8);
put(octal(0, 8), 116, 8);
put(octal(size, 12), 124, 12);
put(octal(0, 12), 136, 12); // no times: the same files make the same archive
put(" ", 148, 8);
put(type, 156, 1);
put(link, 157, 100);
put("ustar\0" + "00", 257, 8);
let sum = 0;
for (const b of h) sum += b;
put(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8);
return h;
}
const padding = (size: number) => new Uint8Array((BLOCK - (size % BLOCK)) % BLOCK);
export class TarWriter {
files = 0;
bytes = 0;
constructor(private out: Sink) {}
private async head(name: string, size: number, mode: number, type: string, link = "") {
const n = enc.encode(name), l = enc.encode(link);
for (const [long, kind] of [[l, "K"], [n, "L"]] as const) {
if (long.length <= 100) continue;
await this.out(header(enc.encode("././@LongLink"), long.length + 1, 0o644, kind, new Uint8Array(0)));
const data = new Uint8Array(long.length + 1);
data.set(long);
await this.out(data);
await this.out(padding(data.length));
}
await this.out(header(n, size, mode, type, l));
}
async data(name: string, bytes: Uint8Array | string, mode = 0o644) {
const b = typeof bytes === "string" ? enc.encode(bytes) : bytes;
await this.head(name, b.length, mode, "0");
await this.out(b);
await this.out(padding(b.length));
this.files++; this.bytes += b.length;
}
// The file at `path`, as `name`. A symbolic link stays one.
async file(name: string, path: string) {
const st = lstatSync(path);
if (st.isSymbolicLink()) { await this.head(name, 0, 0o777, "2", readlinkSync(path)); return; }
if (st.isDirectory()) { await this.head(name.replace(/\/?$/, "/"), 0, 0o755, "5"); return; }
await this.head(name, st.size, st.mode & 0o111 ? 0o755 : 0o644, "0");
let sent = 0;
for await (const chunk of createReadStream(path, { highWaterMark: 1 << 20 })) { sent += chunk.length; await this.out(chunk as Uint8Array); }
if (sent !== st.size) throw new Error(`${path} changed size while it was being packed`);
await this.out(padding(st.size));
this.files++; this.bytes += st.size;
}
async end() { await this.out(new Uint8Array(2 * BLOCK)); }
}
export interface UntarOptions {
// How many leading directories of every path to drop (the `lean-4.x-linux/` of a release).
strip?: number;
// Says which paths (after `strip`) to write. The rest is read past.
filter?: (name: string) => boolean;
// After each file is written: its path under `dest`, and the bytes written so far.
onFile?: (name: string, bytes: number) => void;
}
// An entry whose data is being read: a file being written (`fd`), or a long
// name or a pax header being collected (`meta`).
interface Reading { left: number; pad: number; fd: number | null; path: string | null; name: string; mode: number; meta: Uint8Array[] | null; kind: string }
const text = (b: Uint8Array) => { const end = b.indexOf(0); return dec.decode(end < 0 ? b : b.subarray(0, end)); };
function number(b: Uint8Array): number {
// GNU's base-256 for sizes that octal cannot hold.
if (b[0] & 0x80) { let n = 0; for (let i = 1; i < b.length; i++) n = n * 256 + b[i]; return n; }
return parseInt(text(b).trim() || "0", 8) || 0;
}
// A path inside the archive as one under `dest`, or null when it is nothing to write.
function place(name: string, strip: number): string | null {
const parts = name.split(/[\\/]+/).filter((p) => p && p !== ".");
if (parts.includes("..")) throw new Error(`the archive has a path that leaves it: ${name}`);
const kept = parts.slice(strip);
return kept.length ? kept.join("/") : null;
}
// Unpacks the tar that `source` streams into `dest`.
export async function untar(source: AsyncIterable<Uint8Array>, dest: string, opts: UntarOptions = {}): Promise<{ files: number; bytes: number }> {
const strip = opts.strip ?? 0;
const made = new Set<string>();
const mkdir = (d: string) => { if (!made.has(d)) { mkdirSync(d, { recursive: true }); made.add(d); } };
const links: { path: string; target: string }[] = []; // links that could not be made (Windows), copied at the end
let files = 0, bytes = 0;
let longName: string | null = null, longLink: string | null = null;
let pax: Record<string, string> = {};
let cur: Reading | null = null;
let rest: Uint8Array = new Uint8Array(0);
const finish = () => {
const c = cur!;
if (c.fd != null) {
closeSync(c.fd);
if (!WIN && c.mode & 0o111) chmodSync(c.path!, 0o755);
files++;
opts.onFile?.(c.name, bytes);
}
if (c.meta) {
const all = Buffer.concat(c.meta);
if (c.kind === "L") longName = text(all);
else if (c.kind === "K") longLink = text(all);
else if (c.kind === "x") {
// Records of "<length> <key>=<value>\n".
for (let o = 0; o < all.length; ) {
const sp = all.indexOf(32, o);
if (sp < 0) break;
const len = parseInt(dec.decode(all.subarray(o, sp)), 10);
if (!len) break;
const rec = dec.decode(all.subarray(sp + 1, o + len - 1));
const eq = rec.indexOf("=");
if (eq > 0) pax[rec.slice(0, eq)] = rec.slice(eq + 1);
o += len;
}
}
}
cur = null;
};
const open = (h: Uint8Array) => {
const kind = String.fromCharCode(h[156] || 48);
let size = number(h.subarray(124, 136));
if (kind === "L" || kind === "K" || kind === "x") { cur = { left: size, pad: padding(size).length, fd: null, path: null, name: "", mode: 0, meta: [], kind }; return; }
if (kind === "g") { cur = { left: size, pad: padding(size).length, fd: null, path: null, name: "", mode: 0, meta: null, kind }; return; }
const prefix = text(h.subarray(345, 500));
const raw = pax.path ?? longName ?? (prefix ? `${prefix}/${text(h.subarray(0, 100))}` : text(h.subarray(0, 100)));
const target = pax.linkpath ?? longLink ?? text(h.subarray(157, 257));
if (pax.size != null) size = Number(pax.size);
longName = longLink = null; pax = {};
const mode = number(h.subarray(100, 108));
const name = place(raw, strip);
const want = name != null && (!opts.filter || opts.filter(name));
const path = want ? join(dest, name!) : null;
cur = { left: 0, pad: 0, fd: null, path, name: name ?? "", mode, meta: null, kind };
if (kind === "0" || kind === "7") {
cur.left = size; cur.pad = padding(size).length;
if (path) { mkdir(dirname(path)); cur.fd = openSync(path, "w", 0o644); }
} else if (path && kind === "5") mkdir(path);
else if (path && kind === "2") {
mkdir(dirname(path));
try { rmSync(path, { force: true }); symlinkSync(target, path); } catch { links.push({ path, target: resolve(dirname(path), target) }); }
} else if (path && kind === "1") {
const from = place(target, strip);
mkdir(dirname(path));
if (from) try { linkSync(join(dest, from), path); } catch { links.push({ path, target: join(dest, from) }); }
}
};
mkdir(dest);
let ended = false;
for await (const chunk of source) {
let c: Uint8Array = rest.length ? Buffer.concat([rest, chunk]) : chunk;
let o = 0;
for (;;) {
if (cur) {
const e: Reading = cur;
if (e.left > 0) {
const n = Math.min(e.left, c.length - o);
if (!n) break;
const part = c.subarray(o, o + n);
if (e.fd != null) { for (let w = 0; w < n; ) w += writeSync(e.fd, part, w, n - w); bytes += n; }
else if (e.meta) e.meta.push(part.slice());
o += n; e.left -= n;
if (e.left) break;
}
if (e.pad > 0) {
const n = Math.min(e.pad, c.length - o);
o += n; e.pad -= n;
if (e.pad) break;
}
finish();
}
if (c.length - o < BLOCK) break;
const h = c.subarray(o, o + BLOCK);
o += BLOCK;
if (h.every((b) => b === 0)) { ended = true; continue; }
open(h);
}
rest = o < c.length ? c.slice(o) : new Uint8Array(0);
}
if (cur) throw new Error("the archive ends in the middle of a file");
if (!ended && !files) throw new Error("this is not a tar archive");
for (const l of links) if (existsSync(l.target) && statSync(l.target).isFile()) copyFileSync(l.target, l.path);
return { files, bytes };
}