-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy pathinstall.ts
213 lines (192 loc) · 8.22 KB
/
install.ts
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
import { ExtensionContext, window, OutputChannel, Uri, extensions, env, ProgressLocation } from 'vscode';
import * as zip from 'yauzl';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { Writable } from 'stream';
import * as async from './novsc/async';
import { isRosetta } from './novsc/adapter';
const MaxRedirects = 10;
let activeInstallation: Promise<boolean> = null;
export async function ensurePlatformPackage(context: ExtensionContext, output: OutputChannel, modal: boolean): Promise<boolean> {
if (await async.fs.exists(path.join(context.extensionPath, 'platform.ok')))
return true;
// Just wait if installation is already in progress.
if (activeInstallation != null)
return activeInstallation;
activeInstallation = doEnsurePlatformPackage(context, output, modal);
let result = await activeInstallation;
activeInstallation = null;
return result;
}
async function doEnsurePlatformPackage(context: ExtensionContext, output: OutputChannel, modal: boolean): Promise<boolean> {
let packageUrl = await getPlatformPackageUrl();
output.appendLine(`Installing platform package from ${packageUrl}`);
try {
await window.withProgress(
{
location: ProgressLocation.Notification,
cancellable: false,
title: 'Acquiring CodeLLDB platform package'
},
async (progress) => {
let lastPercentage = 0;
let reportProgress = (downloaded: number, contentLength: number) => {
let percentage = Math.round(downloaded / contentLength * 100);
progress.report({
message: `${percentage}%`,
increment: percentage - lastPercentage
});
lastPercentage = percentage;
};
let downloadTarget = path.join(os.tmpdir(), `codelldb-${process.pid}-${getRandomInt()}.vsix`);
if (packageUrl.scheme != 'file') {
await download(packageUrl, downloadTarget, reportProgress);
} else {
// Simulate download
await async.fs.copyFile(packageUrl.fsPath, downloadTarget);
for (var i = 0; i <= 100; ++i) {
await async.sleep(10);
reportProgress(i, 100);
}
}
progress.report({
message: 'installing',
increment: 100 - lastPercentage,
});
await installVsix(context, downloadTarget);
await async.fs.unlink(downloadTarget);
}
);
} catch (err) {
output.append(`Error: ${err}`);
output.show();
// Show error message, but don't block on it.
window.showErrorMessage(
`Platform package installation failed: ${err}.\n\n` +
'You can try downloading the package manually.\n' +
'Once done, use "Install from VSIX..." command to install.',
{ modal: modal },
`Open download URL in a browser`
).then(choice => {
if (choice != undefined)
env.openExternal(packageUrl);
});
return false;
}
output.appendLine('Done')
return true;
}
async function getPlatformPackageUrl(): Promise<Uri> {
let pkg = extensions.getExtension('vadimcn.vscode-lldb').packageJSON;
let pp = pkg.config.platformPackages;
let platform = os.platform();
let arch = os.arch();
if (await isRosetta()) {
arch = 'arm64';
}
let id = `${platform}-${arch}`;
let platformPackage = pp.platforms[id];
if (platformPackage == undefined) {
throw new Error(`This platform (${id}) is not suported.`);
}
return Uri.parse(pp.url.replace('${version}', pkg.version).replace('${platformPackage}', platformPackage));
}
async function download(srcUrl: Uri, destPath: string,
progress?: (downloaded: number, contentLength?: number) => void) {
let url = srcUrl.toString(true);
for (let i = 0; i < MaxRedirects; ++i) {
let response = await async.https.get(url);
if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
url = response.headers.location;
} else {
return new Promise(async (resolve, reject) => {
if (response.statusCode < 200 || response.statusCode >= 300) {
reject(new Error(`HTTP status ${response.statusCode} : ${response.statusMessage}`));
}
if (response.headers['content-type'] != 'application/octet-stream') {
reject(new Error('HTTP response does not contain an octet stream'));
} else {
let stm = fs.createWriteStream(destPath, { mode: 0o600 });
let pipeStm = response.pipe(stm);
if (progress) {
let contentLength = response.headers['content-length'] ? Number.parseInt(response.headers['content-length']) : null;
let downloaded = 0;
response.on('data', (chunk) => {
downloaded += chunk.length;
progress(downloaded, contentLength);
})
}
pipeStm.on('finish', resolve);
pipeStm.on('error', reject);
response.on('error', reject);
}
});
}
}
}
async function installVsix(context: ExtensionContext, vsixPath: string) {
let destDir = context.extensionPath;
await extractZip(vsixPath, async (entry) => {
if (!entry.fileName.startsWith('extension/'))
return null; // Skip metadata files.
if (entry.fileName.endsWith('/platform.ok'))
return null; // Skip success indicator, we'll create it at the end.
let destPath = path.join(destDir, entry.fileName.substr(10));
await ensureDirectory(path.dirname(destPath));
let stream = fs.createWriteStream(destPath);
stream.on('finish', () => {
let attrs = (entry.externalFileAttributes >> 16) & 0o7777;
fs.chmod(destPath, attrs, (err) => { });
});
return stream;
});
await async.fs.writeFile(path.join(destDir, 'platform.ok'), '');
}
function extractZip(zipPath: string, callback: (entry: zip.Entry) => Promise<Writable> | null): Promise<void> {
return new Promise((resolve, reject) =>
zip.open(zipPath, { lazyEntries: true }, (err, zipfile) => {
if (err) {
reject(err);
} else {
zipfile.readEntry();
zipfile.on('entry', (entry: zip.Entry) => {
callback(entry).then(outstream => {
if (outstream != null) {
zipfile.openReadStream(entry, (err, zipstream) => {
if (err) {
reject(err);
} else {
outstream.on('error', reject);
zipstream.on('error', reject);
zipstream.on('end', () => zipfile.readEntry());
zipstream.pipe(outstream);
}
});
} else {
zipfile.readEntry();
}
});
});
zipfile.on('end', () => {
zipfile.close();
resolve();
});
zipfile.on('error', reject);
}
})
);
}
async function ensureDirectory(dir: string) {
let exists = await new Promise(resolve => fs.exists(dir, exists => resolve(exists)));
if (!exists) {
await ensureDirectory(path.dirname(dir));
await new Promise<void>((resolve, reject) => fs.mkdir(dir, err => {
if (err) reject(err);
else resolve();
}));
}
}
function getRandomInt(): number {
return Math.floor(Math.random() * 1e10)
}