forked from PowerShell/vscode-powershell
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDebugSession.ts
318 lines (262 loc) · 11.7 KB
/
DebugSession.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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import vscode = require('vscode');
import utils = require('../utils');
import { IFeature } from '../feature';
import { SessionManager } from '../session';
import { LanguageClient, RequestType, NotificationType } from 'vscode-languageclient';
export namespace StartDebuggerNotification {
export const type = new NotificationType<void, void>('powerShell/startDebugger');
}
export class DebugSessionFeature implements IFeature {
private command: vscode.Disposable;
private examplesPath: string;
constructor(private sessionManager: SessionManager) {
this.command = vscode.commands.registerCommand(
'PowerShell.StartDebugSession',
config => { this.startDebugSession(config); });
}
public setLanguageClient(languageClient: LanguageClient) {
languageClient.onNotification(
StartDebuggerNotification.type,
none => this.startDebugSession({
request: 'launch',
type: 'PowerShell',
name: 'PowerShell Interactive Session'
}));
}
public dispose() {
this.command.dispose();
}
private startDebugSession(config: any) {
let currentDocument = vscode.window.activeTextEditor.document;
let debugCurrentScript = (config.script === "${file}") || !config.request;
let generateLaunchConfig = !config.request;
if (generateLaunchConfig) {
// No launch.json, create the default configuration for both unsaved (Untitled) and saved documents.
config.type = 'PowerShell';
config.name = 'PowerShell Launch Current File';
config.request = 'launch';
config.args = [];
config.script =
currentDocument.isUntitled
? currentDocument.uri.toString()
: currentDocument.fileName;
// For a folder-less workspace, vscode.workspace.rootPath will be undefined.
// PSES will convert that undefined to a reasonable working dir.
config.cwd =
currentDocument.isUntitled
? vscode.workspace.rootPath
: currentDocument.fileName;
}
if (config.request === 'launch') {
// For debug launch of "current script" (saved or unsaved), warn before starting the debugger if either
// A) the unsaved document's language type is not PowerShell or
// B) the saved document's extension is a type that PowerShell can't debug.
if (debugCurrentScript) {
if (currentDocument.isUntitled) {
if (currentDocument.languageId === 'powershell') {
if (!generateLaunchConfig) {
// Cover the case of existing launch.json but unsaved (Untitled) document.
// In this case, vscode.workspace.rootPath will not be undefined.
config.script = currentDocument.uri.toString();
config.cwd = vscode.workspace.rootPath
}
}
else {
let msg = "To debug '" + currentDocument.fileName +
"', change the document's language mode to PowerShell or save the file with a PowerShell extension.";
vscode.window.showErrorMessage(msg);
return;
}
}
else {
let isValidExtension = false;
let extIndex = currentDocument.fileName.lastIndexOf('.');
if (extIndex !== -1) {
let ext = currentDocument.fileName.substr(extIndex + 1).toUpperCase();
isValidExtension = (ext === "PS1" || ext === "PSM1");
}
if ((currentDocument.languageId !== 'powershell') || !isValidExtension) {
let path = currentDocument.fileName;
let workspaceRootPath = vscode.workspace.rootPath;
if (currentDocument.fileName.startsWith(workspaceRootPath)) {
path = currentDocument.fileName.substring(vscode.workspace.rootPath.length + 1);
}
let msg = "'" + path + "' is a file type that cannot be debugged by the PowerShell debugger.";
vscode.window.showErrorMessage(msg);
return;
}
}
}
}
// Prevent the Debug Console from opening
config.internalConsoleOptions = "neverOpen";
// Create or show the interactive console
// TODO #367: Check if "newSession" mode is configured
vscode.commands.executeCommand('PowerShell.ShowSessionConsole', true);
// Write out temporary debug session file
utils.writeSessionFile(
utils.getDebugSessionFilePath(),
this.sessionManager.getSessionDetails());
vscode.commands.executeCommand('vscode.startDebug', config);
}
}
export class SpecifyScriptArgsFeature implements IFeature {
private command: vscode.Disposable;
private languageClient: LanguageClient;
private context: vscode.ExtensionContext;
private emptyInputBoxBugFixed: boolean;
constructor(context: vscode.ExtensionContext) {
this.context = context;
let vscodeVersionArray = vscode.version.split('.');
let editorVersion = {
major: Number(vscodeVersionArray[0]),
minor: Number(vscodeVersionArray[1]),
}
this.emptyInputBoxBugFixed =
((editorVersion.major > 1) ||
((editorVersion.major == 1) && (editorVersion.minor > 12)));
this.command =
vscode.commands.registerCommand('PowerShell.SpecifyScriptArgs', () => {
return this.specifyScriptArguments();
});
}
public setLanguageClient(languageclient: LanguageClient) {
this.languageClient = languageclient;
}
public dispose() {
this.command.dispose();
}
private specifyScriptArguments(): Thenable<string[]> {
const powerShellDbgScriptArgsKey = 'powerShellDebugScriptArgs';
let options: vscode.InputBoxOptions = {
ignoreFocusOut: true,
placeHolder: "Enter script arguments or leave empty to pass no args"
}
if (this.emptyInputBoxBugFixed) {
let prevArgs = this.context.workspaceState.get(powerShellDbgScriptArgsKey, '');
if (prevArgs.length > 0) {
options.value = prevArgs;
}
}
return vscode.window.showInputBox(options).then(text => {
// When user cancel's the input box (by pressing Esc), the text value is undefined.
if (text !== undefined) {
if (this.emptyInputBoxBugFixed) {
this.context.workspaceState.update(powerShellDbgScriptArgsKey, text);
}
return new Array(text);
}
return text;
});
}
}
interface ProcessItem extends vscode.QuickPickItem {
pid: string; // payload for the QuickPick UI
}
interface PSHostProcessInfo {
processName: string;
processId: string;
appDomainName: string;
mainWindowTitle: string;
}
namespace GetPSHostProcessesRequest {
export const type =
new RequestType<any, GetPSHostProcessesResponseBody, string, void>('powerShell/getPSHostProcesses');
}
interface GetPSHostProcessesResponseBody {
hostProcesses: PSHostProcessInfo[];
}
export class PickPSHostProcessFeature implements IFeature {
private command: vscode.Disposable;
private languageClient: LanguageClient;
private waitingForClientToken: vscode.CancellationTokenSource;
private getLanguageClientResolve: (value?: LanguageClient | Thenable<LanguageClient>) => void;
constructor() {
this.command =
vscode.commands.registerCommand('PowerShell.PickPSHostProcess', () => {
return this.getLanguageClient()
.then(_ => this.pickPSHostProcess(), _ => undefined);
});
}
public setLanguageClient(languageClient: LanguageClient) {
this.languageClient = languageClient;
if (this.waitingForClientToken) {
this.getLanguageClientResolve(this.languageClient);
this.clearWaitingToken();
}
}
public dispose() {
this.command.dispose();
}
private getLanguageClient(): Thenable<LanguageClient> {
if (this.languageClient) {
return Promise.resolve(this.languageClient);
}
else {
// If PowerShell isn't finished loading yet, show a loading message
// until the LanguageClient is passed on to us
this.waitingForClientToken = new vscode.CancellationTokenSource();
return new Promise<LanguageClient>(
(resolve, reject) => {
this.getLanguageClientResolve = resolve;
vscode.window
.showQuickPick(
["Cancel"],
{ placeHolder: "Attach to PowerShell host process: Please wait, starting PowerShell..." },
this.waitingForClientToken.token)
.then(response => {
if (response === "Cancel") {
this.clearWaitingToken();
reject();
}
});
// Cancel the loading prompt after 60 seconds
setTimeout(() => {
if (this.waitingForClientToken) {
this.clearWaitingToken();
reject();
vscode.window.showErrorMessage(
"Attach to PowerShell host process: PowerShell session took too long to start.");
}
}, 60000);
}
);
}
}
private pickPSHostProcess(): Thenable<string> {
return this.languageClient.sendRequest(GetPSHostProcessesRequest.type, null).then(hostProcesses => {
var items: ProcessItem[] = [];
for (var p in hostProcesses) {
var windowTitle = "";
if (hostProcesses[p].mainWindowTitle) {
windowTitle = `, Title: ${hostProcesses[p].mainWindowTitle}`;
}
items.push({
label: hostProcesses[p].processName,
description: `PID: ${hostProcesses[p].processId.toString()}${windowTitle}`,
pid: hostProcesses[p].processId
});
};
if (items.length === 0) {
return Promise.reject("There are no PowerShell host processes to attach to.");
}
let options : vscode.QuickPickOptions = {
placeHolder: "Select a PowerShell host process to attach to",
matchOnDescription: true,
matchOnDetail: true
};
return vscode.window.showQuickPick(items, options).then(item => {
return item ? item.pid : "";
});
});
}
private clearWaitingToken() {
if (this.waitingForClientToken) {
this.waitingForClientToken.dispose();
this.waitingForClientToken = undefined;
}
}
}