Repository navigation
Expand file tree
/
Copy pathruby-install.ts
More file actions
80 lines (70 loc) · 2.93 KB
/
Copy pathruby-install.ts
File metadata and controls
80 lines (70 loc) · 2.93 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
import { ZipReader } from "@zip.js/zip.js"
import * as tar from "tar-stream"
export type IFs = {
mkdirSync(path: string, options?: any): void
writeFileSync(path: string, data: any, options?: any): void
}
export class RubyInstall {
private stripComponents: number
private setStatus: ((status: string) => void)
constructor(options: { stripComponents: number | null, setStatus: ((status: string) => void) | null }) {
this.stripComponents = options.stripComponents ?? 0
this.setStatus = options.setStatus ?? (() => { })
}
async installZip(fs: IFs, zipResponse: Response) {
const zipReader = new ZipReader(zipResponse.body);
const entries = await zipReader.getEntries()
const installTarGz = entries.find((entry) => entry.filename === "install.tar.gz")
if (installTarGz == null) {
throw new Error("No install.tar.gz!?")
}
await this.installTarGz(fs, (writable) => installTarGz.getData(writable))
}
async installTarGz(fs: IFs, pipe: (writable: WritableStream) => void) {
const gzipDecompress = new DecompressionStream("gzip")
pipe(gzipDecompress.writable)
await this.installTar(fs, gzipDecompress.readable)
}
async installTar(fs: IFs, tarStream: ReadableStream) {
const tarExtract = tar.extract()
this.setStatus("Downloading, unzipping, and untarring...")
// TODO: Figure out proper way to bridge Node.js's stream and Web Streams API
const buffer = await new Response(tarStream).arrayBuffer()
tarExtract.write(Buffer.from(buffer))
tarExtract.end()
this.setStatus("Installing...")
const dataWorks = []
for await (const entry of tarExtract) {
const header = entry.header;
let path = header.name
if (this.stripComponents > 0) {
const parts = path.split("/")
path = parts.slice(this.stripComponents).join("/")
}
if (header.type === "directory") {
fs.mkdirSync(path, { recursive: true })
} else if (header.type === "file") {
const dataWork = new Promise<void>((resolve, reject) => {
const chunks: Uint8Array[] = []
entry.on("data", (chunk) => {
chunks.push(chunk)
})
entry.on("end", () => {
const data = Buffer.concat(chunks)
fs.writeFileSync(path, data)
resolve()
})
entry.on("error", (err) => {
reject(err)
})
})
dataWorks.push(dataWork)
} else {
throw new Error(`Unknown entry type ${header.type}`)
}
entry.resume()
}
await Promise.all(dataWorks)
this.setStatus("Installed")
}
}