-
Notifications
You must be signed in to change notification settings - Fork 20
/
utilities.js
140 lines (87 loc) · 2.93 KB
/
utilities.js
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
import gunzipMaybe from 'gunzip-maybe';
import Progress from 'progress';
import tarFs from 'tar-fs';
import tar from 'tar-stream';
function getFileName(entryName, virtualPath) {
entryName = entryName.replace(/^\/+/, ``);
for (let t = 0; t < virtualPath; ++t) {
let index = entryName.indexOf(`/`);
if (index === -1)
return null;
entryName = entryName.substr(index + 1);
}
return entryName;
}
export async function readFileFromArchive(fileName, buffer, {virtualPath = 0} = {}) {
return new Promise((resolve, reject) => {
let extractor = tar.extract();
extractor.on(`entry`, (header, stream, next) => {
if (getFileName(header.name, virtualPath) === fileName) {
var buffers = [];
stream.on(`data`, data => {
buffers.push(data);
});
stream.on(`error`, error => {
reject(error);
});
stream.on(`end`, () => {
resolve(Buffer.concat(buffers));
});
} else {
stream.on(`end`, () => {
next();
});
}
stream.resume();
});
extractor.on(`error`, error => {
reject(error);
});
extractor.on(`finish`, () => {
reject(new Error(`Couldn't find "${fileName}" inside the archive`));
});
let gunzipper = gunzipMaybe();
gunzipper.pipe(extractor);
gunzipper.on(`error`, error => {
reject(error);
});
gunzipper.write(buffer);
gunzipper.end();
});
}
export async function readPackageJsonFromArchive(packageBuffer) {
return await readFileFromArchive(`package.json`, packageBuffer, {virtualPath: 1});
}
export async function extractArchiveTo(packageBuffer, target, {virtualPath = 0} = {}) {
return new Promise((resolve, reject) => {
function map(header) {
header.name = getFileName(header.name, virtualPath) || header.name;
return header;
}
let gunzipper = gunzipMaybe();
let extractor = tarFs.extract(target, { map });
gunzipper.pipe(extractor);
extractor.on(`error`, error => {
reject(error);
});
extractor.on(`finish`, () => {
resolve();
});
gunzipper.write(packageBuffer);
gunzipper.end();
});
}
export async function extractNpmArchiveTo(packageBuffer, target) {
return await extractArchiveTo(packageBuffer, target, {virtualPath: 1});
}
export async function trackProgress(cb) {
let pace = new Progress(`:bar :current/:total (:elapseds)`, {width: 80, total: 1});
try {
return await cb(pace);
} finally {
if (!pace.complete) {
pace.update(1);
pace.terminate();
}
}
}