forked from LeetCode-OpenSource/vscode-leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpUtils.ts
71 lines (60 loc) · 2.54 KB
/
cpUtils.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
// Copyright (c) jdneo. All rights reserved.
// Licensed under the MIT license.
import * as cp from "child_process";
import * as vscode from "vscode";
import { leetCodeChannel } from "../leetCodeChannel";
interface IExecError extends Error {
result?: string;
}
export async function executeCommand(command: string, args: string[], options: cp.SpawnOptions = { shell: true }): Promise<string> {
return new Promise((resolve: (res: string) => void, reject: (e: Error) => void): void => {
let result: string = "";
const childProc: cp.ChildProcess = cp.spawn(command, args, { ...options, env: createEnvOption() });
childProc.stdout?.on("data", (data: string | Buffer) => {
data = data.toString();
result = result.concat(data);
leetCodeChannel.append(data);
});
childProc.stderr?.on("data", (data: string | Buffer) => leetCodeChannel.append(data.toString()));
childProc.on("error", reject);
childProc.on("close", (code: number) => {
if (code !== 0 || result.indexOf("ERROR") > -1) {
const error: IExecError = new Error(`Command "${command} ${args.toString()}" failed with exit code "${code}".`);
if (result) {
error.result = result; // leetcode-cli may print useful content by exit with error code
}
reject(error);
} else {
resolve(result);
}
});
});
}
export async function executeCommandWithProgress(message: string, command: string, args: string[], options: cp.SpawnOptions = { shell: true }): Promise<string> {
let result: string = "";
await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification }, async (p: vscode.Progress<{}>) => {
return new Promise<void>(async (resolve: () => void, reject: (e: Error) => void): Promise<void> => {
p.report({ message });
try {
result = await executeCommand(command, args, options);
resolve();
} catch (e) {
reject(e);
}
});
});
return result;
}
// clone process.env and add http proxy
export function createEnvOption(): {} {
const proxy: string | undefined = getHttpAgent();
if (proxy) {
const env: any = Object.create(process.env);
env.http_proxy = proxy;
return env;
}
return process.env;
}
function getHttpAgent(): string | undefined {
return vscode.workspace.getConfiguration("http").get<string>("proxy");
}