-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
externalTerminalService.ts
372 lines (313 loc) · 12.8 KB
/
externalTerminalService.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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as cp from 'child_process';
import { memoize } from 'vs/base/common/decorators';
import { FileAccess } from 'vs/base/common/network';
import * as path from 'vs/base/common/path';
import * as env from 'vs/base/common/platform';
import { sanitizeProcessEnvironment } from 'vs/base/common/processes';
import * as pfs from 'vs/base/node/pfs';
import * as processes from 'vs/base/node/processes';
import * as nls from 'vs/nls';
import { DEFAULT_TERMINAL_OSX, IExternalTerminalService, IExternalTerminalSettings, ITerminalForPlatform } from 'vs/platform/externalTerminal/common/externalTerminal';
import { ITerminalEnvironment } from 'vs/platform/terminal/common/terminal';
const TERMINAL_TITLE = nls.localize('console.title', "VS Code Console");
abstract class ExternalTerminalService {
public _serviceBrand: undefined;
async getDefaultTerminalForPlatforms(): Promise<ITerminalForPlatform> {
return {
windows: WindowsExternalTerminalService.getDefaultTerminalWindows(),
linux: await LinuxExternalTerminalService.getDefaultTerminalLinuxReady(),
osx: 'xterm'
};
}
}
export class WindowsExternalTerminalService extends ExternalTerminalService implements IExternalTerminalService {
private static readonly CMD = 'cmd.exe';
private static _DEFAULT_TERMINAL_WINDOWS: string;
public openTerminal(configuration: IExternalTerminalSettings, cwd?: string): Promise<void> {
return this.spawnTerminal(cp, configuration, processes.getWindowsShell(), cwd);
}
public spawnTerminal(spawner: typeof cp, configuration: IExternalTerminalSettings, command: string, cwd?: string): Promise<void> {
const exec = configuration.windowsExec || WindowsExternalTerminalService.getDefaultTerminalWindows();
// Make the drive letter uppercase on Windows (see #9448)
if (cwd && cwd[1] === ':') {
cwd = cwd[0].toUpperCase() + cwd.substr(1);
}
// cmder ignores the environment cwd and instead opts to always open in %USERPROFILE%
// unless otherwise specified
const basename = path.basename(exec, '.exe').toLowerCase();
if (basename === 'cmder') {
spawner.spawn(exec, cwd ? [cwd] : undefined);
return Promise.resolve(undefined);
}
const cmdArgs = ['/c', 'start', '/wait'];
if (exec.indexOf(' ') >= 0) {
// The "" argument is the window title. Without this, exec doesn't work when the path
// contains spaces. #6590
// Title is Execution Path. #220129
cmdArgs.push(exec);
}
cmdArgs.push(exec);
// Add starting directory parameter for Windows Terminal (see #90734)
if (basename === 'wt') {
cmdArgs.push('-d .');
}
return new Promise<void>((c, e) => {
const env = getSanitizedEnvironment(process);
const child = spawner.spawn(command, cmdArgs, { cwd, env, detached: true });
child.on('error', e);
child.on('exit', () => c());
});
}
public async runInTerminal(title: string, dir: string, args: string[], envVars: ITerminalEnvironment, settings: IExternalTerminalSettings): Promise<number | undefined> {
const exec = 'windowsExec' in settings && settings.windowsExec ? settings.windowsExec : WindowsExternalTerminalService.getDefaultTerminalWindows();
const wt = await WindowsExternalTerminalService.getWtExePath();
return new Promise<number | undefined>((resolve, reject) => {
const title = `"${dir} - ${TERMINAL_TITLE}"`;
const command = `"${args.join('" "')}" & pause`; // use '|' to only pause on non-zero exit code
// merge environment variables into a copy of the process.env
const env = Object.assign({}, getSanitizedEnvironment(process), envVars);
// delete environment variables that have a null value
Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]);
const options: any = {
cwd: dir,
env: env,
windowsVerbatimArguments: true
};
let spawnExec: string;
let cmdArgs: string[];
if (path.basename(exec, '.exe') === 'wt') {
// Handle Windows Terminal specially; -d to set the cwd and run a cmd.exe instance
// inside it
spawnExec = exec;
cmdArgs = ['-d', '.', WindowsExternalTerminalService.CMD, '/c', command];
} else if (wt) {
// prefer to use the window terminal to spawn if it's available instead
// of start, since that allows ctrl+c handling (#81322)
spawnExec = wt;
cmdArgs = ['-d', '.', exec, '/c', command];
} else {
spawnExec = WindowsExternalTerminalService.CMD;
cmdArgs = ['/c', 'start', title, '/wait', exec, '/c', `"${command}"`];
}
const cmd = cp.spawn(spawnExec, cmdArgs, options);
cmd.on('error', err => {
reject(improveError(err));
});
resolve(undefined);
});
}
public static getDefaultTerminalWindows(): string {
if (!WindowsExternalTerminalService._DEFAULT_TERMINAL_WINDOWS) {
const isWoW64 = !!process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
WindowsExternalTerminalService._DEFAULT_TERMINAL_WINDOWS = `${process.env.windir ? process.env.windir : 'C:\\Windows'}\\${isWoW64 ? 'Sysnative' : 'System32'}\\cmd.exe`;
}
return WindowsExternalTerminalService._DEFAULT_TERMINAL_WINDOWS;
}
@memoize
private static async getWtExePath() {
try {
const wtPath = await processes.win32.findExecutable('wt');
return await pfs.Promises.exists(wtPath) ? wtPath : undefined;
} catch {
return undefined;
}
}
}
export class MacExternalTerminalService extends ExternalTerminalService implements IExternalTerminalService {
private static readonly OSASCRIPT = '/usr/bin/osascript'; // osascript is the AppleScript interpreter on OS X
public openTerminal(configuration: IExternalTerminalSettings, cwd?: string): Promise<void> {
return this.spawnTerminal(cp, configuration, cwd);
}
public runInTerminal(title: string, dir: string, args: string[], envVars: ITerminalEnvironment, settings: IExternalTerminalSettings): Promise<number | undefined> {
const terminalApp = settings.osxExec || DEFAULT_TERMINAL_OSX;
return new Promise<number | undefined>((resolve, reject) => {
if (terminalApp === DEFAULT_TERMINAL_OSX || terminalApp === 'iTerm.app') {
// On OS X we launch an AppleScript that creates (or reuses) a Terminal window
// and then launches the program inside that window.
const script = terminalApp === DEFAULT_TERMINAL_OSX ? 'TerminalHelper' : 'iTermHelper';
const scriptpath = FileAccess.asFileUri(`vs/workbench/contrib/externalTerminal/node/${script}.scpt`).fsPath;
const osaArgs = [
scriptpath,
'-t', title || TERMINAL_TITLE,
'-w', dir,
];
for (const a of args) {
osaArgs.push('-a');
osaArgs.push(a);
}
if (envVars) {
// merge environment variables into a copy of the process.env
const env = Object.assign({}, getSanitizedEnvironment(process), envVars);
for (const key in env) {
const value = env[key];
if (value === null) {
osaArgs.push('-u');
osaArgs.push(key);
} else {
osaArgs.push('-e');
osaArgs.push(`${key}=${value}`);
}
}
}
let stderr = '';
const osa = cp.spawn(MacExternalTerminalService.OSASCRIPT, osaArgs);
osa.on('error', err => {
reject(improveError(err));
});
osa.stderr.on('data', (data) => {
stderr += data.toString();
});
osa.on('exit', (code: number) => {
if (code === 0) { // OK
resolve(undefined);
} else {
if (stderr) {
const lines = stderr.split('\n', 1);
reject(new Error(lines[0]));
} else {
reject(new Error(nls.localize('mac.terminal.script.failed', "Script '{0}' failed with exit code {1}", script, code)));
}
}
});
} else {
reject(new Error(nls.localize('mac.terminal.type.not.supported', "'{0}' not supported", terminalApp)));
}
});
}
spawnTerminal(spawner: typeof cp, configuration: IExternalTerminalSettings, cwd?: string): Promise<void> {
const terminalApp = configuration.osxExec || DEFAULT_TERMINAL_OSX;
return new Promise<void>((c, e) => {
const args = ['-a', terminalApp];
if (cwd) {
args.push(cwd);
}
const env = getSanitizedEnvironment(process);
const child = spawner.spawn('/usr/bin/open', args, { cwd, env });
child.on('error', e);
child.on('exit', () => c());
});
}
}
export class LinuxExternalTerminalService extends ExternalTerminalService implements IExternalTerminalService {
private static readonly WAIT_MESSAGE = nls.localize('press.any.key', "Press any key to continue...");
public openTerminal(configuration: IExternalTerminalSettings, cwd?: string): Promise<void> {
return this.spawnTerminal(cp, configuration, cwd);
}
public runInTerminal(title: string, dir: string, args: string[], envVars: ITerminalEnvironment, settings: IExternalTerminalSettings): Promise<number | undefined> {
const execPromise = settings.linuxExec ? Promise.resolve(settings.linuxExec) : LinuxExternalTerminalService.getDefaultTerminalLinuxReady();
return new Promise<number | undefined>((resolve, reject) => {
const termArgs: string[] = [];
//termArgs.push('--title');
//termArgs.push(`"${TERMINAL_TITLE}"`);
execPromise.then(exec => {
if (exec.indexOf('gnome-terminal') >= 0) {
termArgs.push('-x');
} else {
termArgs.push('-e');
}
termArgs.push('bash');
termArgs.push('-c');
const bashCommand = `${quote(args)}; echo; read -p "${LinuxExternalTerminalService.WAIT_MESSAGE}" -n1;`;
termArgs.push(`''${bashCommand}''`); // wrapping argument in two sets of ' because node is so "friendly" that it removes one set...
// merge environment variables into a copy of the process.env
const env = Object.assign({}, getSanitizedEnvironment(process), envVars);
// delete environment variables that have a null value
Object.keys(env).filter(v => env[v] === null).forEach(key => delete env[key]);
const options: any = {
cwd: dir,
env: env
};
let stderr = '';
const cmd = cp.spawn(exec, termArgs, options);
cmd.on('error', err => {
reject(improveError(err));
});
cmd.stderr.on('data', (data) => {
stderr += data.toString();
});
cmd.on('exit', (code: number) => {
if (code === 0) { // OK
resolve(undefined);
} else {
if (stderr) {
const lines = stderr.split('\n', 1);
reject(new Error(lines[0]));
} else {
reject(new Error(nls.localize('linux.term.failed', "'{0}' failed with exit code {1}", exec, code)));
}
}
});
});
});
}
private static _DEFAULT_TERMINAL_LINUX_READY: Promise<string>;
public static async getDefaultTerminalLinuxReady(): Promise<string> {
if (!LinuxExternalTerminalService._DEFAULT_TERMINAL_LINUX_READY) {
if (!env.isLinux) {
LinuxExternalTerminalService._DEFAULT_TERMINAL_LINUX_READY = Promise.resolve('xterm');
} else {
const isDebian = await pfs.Promises.exists('/etc/debian_version');
LinuxExternalTerminalService._DEFAULT_TERMINAL_LINUX_READY = new Promise<string>(r => {
if (isDebian) {
r('x-terminal-emulator');
} else if (process.env.DESKTOP_SESSION === 'gnome' || process.env.DESKTOP_SESSION === 'gnome-classic') {
r('gnome-terminal');
} else if (process.env.DESKTOP_SESSION === 'kde-plasma') {
r('konsole');
} else if (process.env.COLORTERM) {
r(process.env.COLORTERM);
} else if (process.env.TERM) {
r(process.env.TERM);
} else {
r('xterm');
}
});
}
}
return LinuxExternalTerminalService._DEFAULT_TERMINAL_LINUX_READY;
}
spawnTerminal(spawner: typeof cp, configuration: IExternalTerminalSettings, cwd?: string): Promise<void> {
const execPromise = configuration.linuxExec ? Promise.resolve(configuration.linuxExec) : LinuxExternalTerminalService.getDefaultTerminalLinuxReady();
return new Promise<void>((c, e) => {
execPromise.then(exec => {
const env = getSanitizedEnvironment(process);
const child = spawner.spawn(exec, [], { cwd, env });
child.on('error', e);
child.on('exit', () => c());
});
});
}
}
function getSanitizedEnvironment(process: NodeJS.Process) {
const env = { ...process.env };
sanitizeProcessEnvironment(env);
return env;
}
/**
* tries to turn OS errors into more meaningful error messages
*/
function improveError(err: Error & { errno?: string; path?: string }): Error {
if ('errno' in err && err['errno'] === 'ENOENT' && 'path' in err && typeof err['path'] === 'string') {
return new Error(nls.localize('ext.term.app.not.found', "can't find terminal application '{0}'", err['path']));
}
return err;
}
/**
* Quote args if necessary and combine into a space separated string.
*/
function quote(args: string[]): string {
let r = '';
for (const a of args) {
if (a.indexOf(' ') >= 0) {
r += '"' + a + '"';
} else {
r += a;
}
r += ' ';
}
return r;
}