forked from oracle/javavscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
344 lines (315 loc) · 9.49 KB
/
utils.ts
File metadata and controls
344 lines (315 loc) · 9.49 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import * as vscode from 'vscode';
import * as https from 'https';
import * as fs from 'fs';
import { promisify } from "util";
import * as crypto from 'crypto';
import { l10n } from './localiser';
import { extConstants } from './constants';
class InputFlowAction {
static back = new InputFlowAction();
static cancel = new InputFlowAction();
static resume = new InputFlowAction();
}
export type InputStep = (input: MultiStepInput) => Thenable<InputStep | void>;
interface QuickPickParameters<T extends vscode.QuickPickItem> {
title: string | undefined;
step: number;
totalSteps: number;
items: T[];
placeholder: string;
canSelectMany?: boolean;
selectedItems?: readonly T[];
buttons?: vscode.QuickInputButton[];
shouldResume?: () => Thenable<boolean>;
}
interface InputBoxParameters {
title: string | undefined;
step: number;
totalSteps: number;
value: string;
prompt: string;
validate: (value: string) => Promise<string | undefined>;
password?: boolean;
buttons?: vscode.QuickInputButton[];
shouldResume?: () => Thenable<boolean>;
}
export class MultiStepInput {
static async run(start: InputStep) {
const input = new MultiStepInput();
return input.stepThrough(start);
}
private current?: vscode.QuickInput;
private steps: InputStep[] = [];
private async stepThrough(start: InputStep) {
let step: InputStep | void = start;
while (step) {
this.steps.push(step);
if (this.current) {
this.current.enabled = false;
this.current.busy = true;
}
try {
step = await step(this);
} catch (err) {
if (err === InputFlowAction.back) {
this.steps.pop();
step = this.steps.pop();
} else if (err === InputFlowAction.resume) {
step = this.steps.pop();
} else if (err === InputFlowAction.cancel) {
step = undefined;
} else {
throw err;
}
}
}
if (this.current) {
this.current.dispose();
}
}
async showQuickPick<T extends vscode.QuickPickItem, P extends QuickPickParameters<T>>({ title, step, totalSteps, items, selectedItems, placeholder, canSelectMany, buttons, shouldResume }: P) {
const disposables: vscode.Disposable[] = [];
try {
return await new Promise<readonly T[] | (P extends { buttons: (infer I)[] } ? I : never)>((resolve, reject) => {
const input = vscode.window.createQuickPick<T>();
input.title = title;
input.step = step;
input.totalSteps = totalSteps;
input.placeholder = placeholder;
input.items = items;
if (canSelectMany) {
input.canSelectMany = canSelectMany;
}
if (selectedItems) {
input.selectedItems = selectedItems;
}
input.buttons = [
...(this.steps.length > 1 ? [vscode.QuickInputButtons.Back] : []),
...(buttons || [])
];
input.ignoreFocusOut = true;
disposables.push(
input.onDidTriggerButton(item => {
if (item === vscode.QuickInputButtons.Back) {
reject(InputFlowAction.back);
} else {
resolve(<any>item);
}
}),
input.onDidAccept(() => {
resolve(input.selectedItems);
}),
input.onDidHide(() => {
(async () => {
reject(shouldResume && await shouldResume() ? InputFlowAction.resume : InputFlowAction.cancel);
})()
.catch(reject);
})
);
if (this.current) {
this.current.dispose();
}
this.current = input;
this.current.show();
});
} finally {
disposables.forEach(d => d.dispose());
}
}
async showInputBox<P extends InputBoxParameters>({ title, step, totalSteps, value, prompt, validate, password, buttons, shouldResume }: P) {
const disposables: vscode.Disposable[] = [];
try {
return await new Promise<string | (P extends { buttons: (infer I)[] } ? I : never)>((resolve, reject) => {
const input = vscode.window.createInputBox();
input.title = title;
input.step = step;
input.totalSteps = totalSteps;
input.value = value || '';
input.prompt = prompt;
if (password) {
input.password = password;
}
input.buttons = [
...(this.steps.length > 1 ? [vscode.QuickInputButtons.Back] : []),
...(buttons || [])
];
input.ignoreFocusOut = true;
// let validating = validate('');
disposables.push(
input.onDidTriggerButton(item => {
if (item === vscode.QuickInputButtons.Back) {
reject(InputFlowAction.back);
} else {
resolve(<any>item);
}
}),
input.onDidAccept(async () => {
const value = input.value;
input.enabled = false;
input.busy = true;
const validationMessage = await validate(value);
if (validationMessage) {
input.validationMessage = validationMessage;
} else {
resolve(value);
}
input.enabled = true;
input.busy = false;
}),
input.onDidHide(() => {
(async () => {
reject(shouldResume && await shouldResume() ? InputFlowAction.resume : InputFlowAction.cancel);
})()
.catch(reject);
})
);
if (this.current) {
this.current.dispose();
}
this.current = input;
this.current.show();
});
} finally {
disposables.forEach(d => d.dispose());
}
}
}
export function httpsGet(url: string) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
if (res.statusCode !== 200) {
return reject(new Error(l10n.value("jdk.extension.utils.error_message.failedHttpsRequest", {
url,
statusCode: res.statusCode
})));
}
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data);
});
}).on('error', (e) => {
reject(e);
});
});
}
export function downloadFileWithProgressBar(downloadUrl: string, downloadLocation: string, message: string) {
return vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, cancellable: false }, p => {
return new Promise<void>((resolve, reject) => {
const file = fs.createWriteStream(downloadLocation);
https.get(downloadUrl, (response) => {
if (response.statusCode !== 200) {
return reject(new Error(l10n.value("jdk.extension.utils.error_message.failedHttpsRequest", {
url: downloadUrl,
statusCode: response.statusCode
})));
}
const totalSize = parseInt(response.headers['content-length'] || '0');
let downloadedSize = 0;
response.pipe(file);
response.on('data', (chunk) => {
downloadedSize += chunk.length;
if (totalSize) {
const increment = parseFloat(((chunk.length / totalSize) * 100).toFixed(2));
const progress = parseFloat(((downloadedSize / totalSize) * 100).toFixed(2));
p.report({ increment, message: `${message}: ${progress} %` });
}
});
file.on('finish', () => {
file.close();
resolve();
});
}).on('error', (err) => {
fs.unlink(downloadLocation, () => reject(err));
});
});
});
}
export const calculateChecksum = async (filePath: string, algorithm: string = 'sha256'): Promise<string> => {
const hash = crypto.createHash(algorithm);
const pipeline = promisify(require('stream').pipeline);
const readStream = fs.createReadStream(filePath);
await pipeline(
readStream,
hash
);
const checksum = hash.digest('hex');
return checksum;
}
export const appendPrefixToCommand = (command: string) => `${extConstants.COMMAND_PREFIX}.${command}`;
export function isString(obj: unknown): obj is string {
return typeof obj === 'string';
}
export function isError(obj: unknown): obj is Error {
return obj instanceof Error;
}
export const isObject = (value: any) => value !== null && typeof value === 'object' && !Array.isArray(value);
export async function initializeRunConfiguration(): Promise<boolean> {
if (vscode.workspace.name || vscode.workspace.workspaceFile) {
const java = await vscode.workspace.findFiles('**/*.java', '**/node_modules/**', 1);
if (java?.length > 0) {
return true;
}
} else {
for (let doc of vscode.workspace.textDocuments) {
if (doc.fileName?.endsWith(".java")) {
return true;
}
}
}
return false;
}
const isQuotes = (c: string): boolean => {
return c === "'" || c === '"';
}
export const parseArguments = (input: string): string[] => {
const result: string[] = [];
let current = "";
if (input.search(/['"]/) < 0) return input.split(/\s+/);
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (char === " ") {
result.push(current);
current = "";
} else if (isQuotes(char)) {
const quoteType = char;
current += char;
i++;
let f = true;
while (i < input.length && f) {
current += input[i];
const isEscapingSomethingElse = (i > 1 && input[i - 1] == "\\" && input[i - 2] == "\\");
if (input[i] === quoteType && input[i - 1] != "\\" && !isEscapingSomethingElse)
f = false;
else
i++;
}
} else {
current += char;
}
}
if (current) {
result.push(current);
}
return result;
}