-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathrunWithoutDebuggingAdapter.ts
More file actions
308 lines (269 loc) · 12.6 KB
/
runWithoutDebuggingAdapter.ts
File metadata and controls
308 lines (269 loc) · 12.6 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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import * as cp from 'child_process';
import * as os from 'os';
import * as path from 'path';
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { sessionIsWsl } from '../common';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize = nls.loadMessageBundle();
/**
* A minimal inline Debug Adapter that runs the target program directly without a debug adapter
* when the user invokes "Run Without Debugging".
*/
export class RunWithoutDebuggingAdapter implements vscode.DebugAdapter {
private readonly sendMessageEmitter = new vscode.EventEmitter<vscode.DebugProtocolMessage>();
public readonly onDidSendMessage: vscode.Event<vscode.DebugProtocolMessage> = this.sendMessageEmitter.event;
private readonly terminalListeners: vscode.Disposable[] = [];
private seq: number = 1;
private childProcess?: cp.ChildProcess;
private terminal?: vscode.Terminal;
private terminalExecution?: vscode.TerminalShellExecution;
private hasTerminated: boolean = false;
public handleMessage(message: vscode.DebugProtocolMessage): void {
const msg = message as { type: string; command: string; seq: number; arguments?: any; };
if (msg.type === 'request') {
void this.handleRequest(msg);
}
}
private async handleRequest(request: { command: string; seq: number; arguments?: any; }): Promise<void> {
switch (request.command) {
case 'initialize':
this.sendResponse(request, {});
this.sendEvent('initialized');
break;
case 'launch':
await this.launch(request);
break;
case 'configurationDone':
this.sendResponse(request, {});
break;
case 'disconnect':
case 'terminate':
this.sendResponse(request, {});
break;
default:
this.sendResponse(request, {});
break;
}
}
private async launch(request: { command: string; seq: number; arguments?: any; }): Promise<void> {
const config = request.arguments as {
program?: string;
args?: string[];
cwd?: string;
environment?: { name: string; value: string; }[];
console?: string;
externalConsole?: boolean;
};
const program: string = config.program ?? '';
const args: string[] = config.args ?? [];
const cwd: string | undefined = config.cwd;
const environment: { name: string; value: string; }[] = config.environment ?? [];
const consoleMode: string = config.console ?? (config.externalConsole ? 'externalTerminal' : 'integratedTerminal');
// Merge the launch config's environment variables on top of the inherited process environment.
const env: NodeJS.ProcessEnv = { ...process.env };
for (const e of environment) {
env[e.name] = e.value;
}
this.sendResponse(request, {});
if (consoleMode === 'integratedTerminal') {
await this.launchIntegratedTerminal(program, args, cwd, env);
} else if (consoleMode === 'externalTerminal') {
this.launchExternalTerminal(program, args, cwd, env);
} else {
this.launchInternalConsole(program, args, cwd, env);
}
}
/**
* Launch the program in a VS Code integrated terminal.
* The terminal will remain open after the program exits and be reused for the next session, if applicable.
*/
private async launchIntegratedTerminal(program: string, args: string[], cwd: string | undefined, env: NodeJS.ProcessEnv): Promise<void> {
const terminalName = path.normalize(program);
const existingTerminal = vscode.window.terminals.find(t => t.name === terminalName);
this.terminal = existingTerminal ?? vscode.window.createTerminal({
name: terminalName,
cwd,
env: env as Record<string, string>
});
this.terminal.show(true);
const shellIntegration: vscode.TerminalShellIntegration | undefined =
this.terminal.shellIntegration ?? await this.waitForShellIntegration(this.terminal, 3000);
// Not all terminals support shell integration. If it's not available, we'll just send the command as text though we won't be able to monitor its execution.
if (shellIntegration) {
this.monitorIntegratedTerminal(this.terminal);
this.terminalExecution = shellIntegration.executeCommand(program, args);
} else {
const shellArgs: string[] = [program, ...args].map(a => this.quoteArg(a));
this.terminal.sendText(shellArgs.join(' '));
// The terminal manages its own lifecycle; notify VS Code the "debug" session is done.
this.sendEvent('terminated');
}
}
/**
* Launch the program in an external terminal. We do not keep track of this terminal or the spawned process.
*/
private launchExternalTerminal(program: string, args: string[], cwd: string | undefined, env: NodeJS.ProcessEnv): void {
const quotedArgs: string[] = [program, ...args].map(a => this.quoteArg(a));
const cmdLine: string = quotedArgs.join(' ');
const platform: string = os.platform();
if (platform === 'win32') {
cp.spawn('cmd.exe', ['/c', 'start', 'cmd.exe', '/K', cmdLine], { cwd, env, detached: true, stdio: 'ignore' }).unref();
} else if (platform === 'darwin') {
cp.spawn('osascript', ['-e', `tell application "Terminal" to do script "${this.escapeQuotes(cmdLine)}"`], { cwd, env, detached: true, stdio: 'ignore' }).unref();
} else if (platform === 'linux' && sessionIsWsl()) {
cp.spawn('/mnt/c/Windows/System32/cmd.exe', ['/c', 'start', 'bash', '-c', `${cmdLine};read -p 'Press enter to continue...'`], { env, detached: true, stdio: 'ignore' }).unref();
} else { // platform === 'linux'
this.launchLinuxExternalTerminal(cmdLine, cwd, env);
}
this.sendEvent('terminated');
}
/**
* On Linux, find and launch an available terminal emulator to run the command.
*/
private launchLinuxExternalTerminal(cmdLine: string, cwd: string | undefined, env: NodeJS.ProcessEnv): void {
const bashCmd = `${cmdLine}; echo; read -p 'Press enter to continue...'`;
const bashArgs = ['bash', '-c', bashCmd];
// Terminal emulators in order of preference, with the correct flag style for each.
const candidates: { cmd: string; buildArgs(): string[] }[] = [
{ cmd: 'x-terminal-emulator', buildArgs: () => ['-e', ...bashArgs] },
{ cmd: 'gnome-terminal', buildArgs: () => ['-e', ...bashArgs] },
{ cmd: 'konsole', buildArgs: () => ['-e', ...bashArgs] },
{ cmd: 'xterm', buildArgs: () => ['-e', ...bashArgs] }
];
// Honor the $TERMINAL environment variable if set.
const terminalEnv = process.env['TERMINAL'];
if (terminalEnv) {
candidates.unshift({ cmd: terminalEnv, buildArgs: () => ['-e', ...bashArgs] });
}
for (const candidate of candidates) {
try {
const result = cp.spawnSync('which', [candidate.cmd], { stdio: 'pipe' });
if (result.status === 0) {
cp.spawn(candidate.cmd, candidate.buildArgs(), { cwd, env, detached: true, stdio: 'ignore' }).unref();
return;
}
} catch {
continue;
}
}
const message = localize('no.terminal.emulator', 'No terminal emulator found. Please set the $TERMINAL environment variable to your terminal emulator of choice, or install one of the following: x-terminal-emulator, gnome-terminal, konsole, xterm.');
vscode.window.showErrorMessage(message);
}
/**
* Spawn the process and forward stdout/stderr as DAP output events.
*/
private launchInternalConsole(program: string, args: string[], cwd: string | undefined, env: NodeJS.ProcessEnv) {
this.childProcess = cp.spawn(program, args, { cwd, env });
this.childProcess.stdout?.on('data', (data: Buffer) => {
this.sendEvent('output', { category: 'stdout', output: data.toString() });
});
this.childProcess.stderr?.on('data', (data: Buffer) => {
this.sendEvent('output', { category: 'stderr', output: data.toString() });
});
this.childProcess.on('error', (err: Error) => {
this.sendEvent('output', { category: 'stderr', output: `${err.message}\n` });
this.sendEvent('exited', { exitCode: 1 });
this.sendEvent('terminated');
});
this.childProcess.on('exit', (code: number | null) => {
this.sendEvent('exited', { exitCode: code ?? 0 });
this.sendEvent('terminated');
});
}
private escapeQuotes(arg: string): string {
return arg.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
private quoteArg(arg: string): string {
return /\s/.test(arg) ? `"${this.escapeQuotes(arg)}"` : arg;
}
private waitForShellIntegration(terminal: vscode.Terminal, timeoutMs: number): Promise<vscode.TerminalShellIntegration | undefined> {
return new Promise(resolve => {
let resolved: boolean = false;
const done = (shellIntegration: vscode.TerminalShellIntegration | undefined): void => {
if (resolved) {
return;
}
resolved = true;
clearTimeout(timeout);
shellIntegrationChanged.dispose();
terminalClosed.dispose();
resolve(shellIntegration);
};
const timeout = setTimeout(() => done(undefined), timeoutMs);
const shellIntegrationChanged = vscode.window.onDidChangeTerminalShellIntegration(event => {
if (event.terminal === terminal) {
done(event.shellIntegration);
}
});
const terminalClosed = vscode.window.onDidCloseTerminal(closedTerminal => {
if (closedTerminal === terminal) {
done(undefined);
}
});
});
}
private monitorIntegratedTerminal(terminal: vscode.Terminal): void {
this.disposeTerminalListeners();
this.terminalListeners.push(
vscode.window.onDidEndTerminalShellExecution(event => {
if (event.terminal !== terminal || event.execution !== this.terminalExecution || this.hasTerminated) {
return;
}
if (event.exitCode !== undefined) {
this.sendEvent('exited', { exitCode: event.exitCode });
}
this.sendEvent('terminated');
}),
vscode.window.onDidCloseTerminal(closedTerminal => {
if (closedTerminal !== terminal || this.hasTerminated) {
return;
}
this.sendEvent('terminated');
})
);
}
private disposeTerminalListeners(): void {
while (this.terminalListeners.length > 0) {
this.terminalListeners.pop()?.dispose();
}
}
private sendResponse(request: { command: string; seq: number; }, body: object): void {
this.sendMessageEmitter.fire({
type: 'response',
seq: this.seq++,
request_seq: request.seq,
success: true,
command: request.command,
body
} as vscode.DebugProtocolMessage);
}
private sendEvent(event: string, body?: object): void {
if (event === 'terminated') {
if (this.hasTerminated) {
return;
}
this.hasTerminated = true;
this.disposeTerminalListeners();
}
this.sendMessageEmitter.fire({
type: 'event',
seq: this.seq++,
event,
body
} as vscode.DebugProtocolMessage);
}
public dispose(): void {
this.terminateProcess();
this.disposeTerminalListeners();
this.sendMessageEmitter.dispose();
}
private terminateProcess(): void {
this.childProcess?.kill();
this.childProcess = undefined;
}
}