-
Notifications
You must be signed in to change notification settings - Fork 30k
/
Copy pathextension.ts
400 lines (343 loc) · 12.7 KB
/
extension.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { promises as fs } from 'fs';
import { createServer, Server } from 'net';
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
const TEXT_STATUSBAR_LABEL = {
[State.Disabled]: localize('status.text.auto.attach.disabled', 'Auto Attach: Disabled'),
[State.Always]: localize('status.text.auto.attach.always', 'Auto Attach: Always'),
[State.Smart]: localize('status.text.auto.attach.smart', 'Auto Attach: Smart'),
[State.OnlyWithFlag]: localize('status.text.auto.attach.withFlag', 'Auto Attach: With Flag'),
};
const TEXT_STATE_LABEL = {
[State.Disabled]: localize('debug.javascript.autoAttach.disabled.label', 'Disabled'),
[State.Always]: localize('debug.javascript.autoAttach.always.label', 'Always'),
[State.Smart]: localize('debug.javascript.autoAttach.smart.label', 'Smart'),
[State.OnlyWithFlag]: localize(
'debug.javascript.autoAttach.onlyWithFlag.label',
'Only With Flag',
),
};
const TEXT_STATE_DESCRIPTION = {
[State.Disabled]: localize(
'debug.javascript.autoAttach.disabled.description',
'Auto attach is disabled and not shown in status bar',
),
[State.Always]: localize(
'debug.javascript.autoAttach.always.description',
'Auto attach to every Node.js process launched in the terminal',
),
[State.Smart]: localize(
'debug.javascript.autoAttach.smart.description',
"Auto attach when running scripts that aren't in a node_modules folder",
),
[State.OnlyWithFlag]: localize(
'debug.javascript.autoAttach.onlyWithFlag.description',
'Only auto attach when the `--inspect` flag is given',
),
};
const TEXT_TOGGLE_WORKSPACE = localize('scope.workspace', 'Toggle auto attach in this workspace');
const TEXT_TOGGLE_GLOBAL = localize('scope.global', 'Toggle auto attach on this machine');
const TEXT_TEMP_DISABLE = localize('tempDisable.disable', 'Temporarily disable auto attach in this session');
const TEXT_TEMP_ENABLE = localize('tempDisable.enable', 'Re-enable auto attach');
const TEXT_TEMP_DISABLE_LABEL = localize('tempDisable.suffix', 'Auto Attach: Disabled');
const TOGGLE_COMMAND = 'extension.node-debug.toggleAutoAttach';
const STORAGE_IPC = 'jsDebugIpcState';
const SETTING_SECTION = 'debug.javascript';
const SETTING_STATE = 'autoAttachFilter';
/**
* settings that, when changed, should cause us to refresh the state vars
*/
const SETTINGS_CAUSE_REFRESH = new Set(
['autoAttachSmartPattern', SETTING_STATE].map(s => `${SETTING_SECTION}.${s}`),
);
const enum State {
Disabled = 'disabled',
OnlyWithFlag = 'onlyWithFlag',
Smart = 'smart',
Always = 'always',
}
let currentState: Promise<{ context: vscode.ExtensionContext; state: State | null }>;
let statusItem: vscode.StatusBarItem | undefined; // and there is no status bar item
let server: Promise<Server | undefined> | undefined; // auto attach server
let isTemporarilyDisabled = false; // whether the auto attach server is disabled temporarily, reset whenever the state changes
export function activate(context: vscode.ExtensionContext): void {
currentState = Promise.resolve({ context, state: null });
context.subscriptions.push(
vscode.commands.registerCommand(TOGGLE_COMMAND, toggleAutoAttachSetting.bind(null, context)),
);
context.subscriptions.push(
vscode.workspace.onDidChangeConfiguration(e => {
// Whenever a setting is changed, disable auto attach, and re-enable
// it (if necessary) to refresh variables.
if (
e.affectsConfiguration(`${SETTING_SECTION}.${SETTING_STATE}`) ||
[...SETTINGS_CAUSE_REFRESH].some(setting => e.affectsConfiguration(setting))
) {
updateAutoAttach(State.Disabled);
updateAutoAttach(readCurrentState());
}
}),
);
updateAutoAttach(readCurrentState());
}
export async function deactivate(): Promise<void> {
await destroyAttachServer();
}
function getDefaultScope(info: ReturnType<vscode.WorkspaceConfiguration['inspect']>) {
if (!info) {
return vscode.ConfigurationTarget.Global;
} else if (info.workspaceFolderValue) {
return vscode.ConfigurationTarget.WorkspaceFolder;
} else if (info.workspaceValue) {
return vscode.ConfigurationTarget.Workspace;
} else if (info.globalValue) {
return vscode.ConfigurationTarget.Global;
}
return vscode.ConfigurationTarget.Global;
}
type PickResult = { state: State } | { setTempDisabled: boolean } | { scope: vscode.ConfigurationTarget } | undefined;
type PickItem = vscode.QuickPickItem & ({ state: State } | { setTempDisabled: boolean });
async function toggleAutoAttachSetting(context: vscode.ExtensionContext, scope?: vscode.ConfigurationTarget): Promise<void> {
const section = vscode.workspace.getConfiguration(SETTING_SECTION);
scope = scope || getDefaultScope(section.inspect(SETTING_STATE));
const isGlobalScope = scope === vscode.ConfigurationTarget.Global;
const quickPick = vscode.window.createQuickPick<PickItem>();
const current = readCurrentState();
const items: PickItem[] = [State.Always, State.Smart, State.OnlyWithFlag, State.Disabled].map(state => ({
state,
label: TEXT_STATE_LABEL[state],
description: TEXT_STATE_DESCRIPTION[state],
alwaysShow: true,
}));
if (current !== State.Disabled) {
items.unshift({
setTempDisabled: !isTemporarilyDisabled,
label: isTemporarilyDisabled ? TEXT_TEMP_ENABLE : TEXT_TEMP_DISABLE,
alwaysShow: true,
});
}
quickPick.items = items;
quickPick.activeItems = isTemporarilyDisabled
? [items[0]]
: quickPick.items.filter(i => 'state' in i && i.state === current);
quickPick.title = isGlobalScope ? TEXT_TOGGLE_GLOBAL : TEXT_TOGGLE_WORKSPACE;
quickPick.buttons = [
{
iconPath: new vscode.ThemeIcon(isGlobalScope ? 'folder' : 'globe'),
tooltip: isGlobalScope ? TEXT_TOGGLE_WORKSPACE : TEXT_TOGGLE_GLOBAL,
},
];
quickPick.show();
let result = await new Promise<PickResult>(resolve => {
quickPick.onDidAccept(() => resolve(quickPick.selectedItems[0]));
quickPick.onDidHide(() => resolve(undefined));
quickPick.onDidTriggerButton(() => {
resolve({
scope: isGlobalScope
? vscode.ConfigurationTarget.Workspace
: vscode.ConfigurationTarget.Global,
});
});
});
quickPick.dispose();
if (!result) {
return;
}
if ('scope' in result) {
return await toggleAutoAttachSetting(context, result.scope);
}
if ('state' in result) {
if (result.state !== current) {
section.update(SETTING_STATE, result.state, scope);
} else if (isTemporarilyDisabled) {
result = { setTempDisabled: false };
}
}
if ('setTempDisabled' in result) {
updateStatusBar(context, current, true);
isTemporarilyDisabled = result.setTempDisabled;
if (result.setTempDisabled) {
await destroyAttachServer();
} else {
await createAttachServer(context); // unsets temp disabled var internally
}
updateStatusBar(context, current, false);
}
}
function readCurrentState(): State {
const section = vscode.workspace.getConfiguration(SETTING_SECTION);
return section.get<State>(SETTING_STATE) ?? State.Disabled;
}
async function clearJsDebugAttachState(context: vscode.ExtensionContext) {
await context.workspaceState.update(STORAGE_IPC, undefined);
await vscode.commands.executeCommand('extension.js-debug.clearAutoAttachVariables');
await destroyAttachServer();
}
/**
* Turns auto attach on, and returns the server auto attach is listening on
* if it's successful.
*/
async function createAttachServer(context: vscode.ExtensionContext) {
const ipcAddress = await getIpcAddress(context);
if (!ipcAddress) {
return undefined;
}
server = createServerInner(ipcAddress).catch(err => {
console.error(err);
return undefined;
});
return await server;
}
const createServerInner = async (ipcAddress: string) => {
try {
return await createServerInstance(ipcAddress);
} catch (e) {
// On unix/linux, the file can 'leak' if the process exits unexpectedly.
// If we see this, try to delete the file and then listen again.
await fs.unlink(ipcAddress).catch(() => undefined);
return await createServerInstance(ipcAddress);
}
};
const createServerInstance = (ipcAddress: string) =>
new Promise<Server>((resolve, reject) => {
const s = createServer(socket => {
let data: Buffer[] = [];
socket.on('data', async chunk => {
if (chunk[chunk.length - 1] !== 0) {
// terminated with NUL byte
data.push(chunk);
return;
}
data.push(chunk.slice(0, -1));
try {
await vscode.commands.executeCommand(
'extension.js-debug.autoAttachToProcess',
JSON.parse(Buffer.concat(data).toString()),
);
socket.write(Buffer.from([0]));
} catch (err) {
socket.write(Buffer.from([1]));
console.error(err);
}
});
})
.on('error', reject)
.listen(ipcAddress, () => resolve(s));
});
/**
* Destroys the auto-attach server, if it's running.
*/
async function destroyAttachServer() {
const instance = await server;
if (instance) {
await new Promise(r => instance.close(r));
}
}
interface CachedIpcState {
ipcAddress: string;
jsDebugPath: string;
settingsValue: string;
}
/**
* Map of logic that happens when auto attach states are entered and exited.
* All state transitions are queued and run in order; promises are awaited.
*/
const transitions: { [S in State]: (context: vscode.ExtensionContext) => Promise<void> } = {
async [State.Disabled](context) {
await clearJsDebugAttachState(context);
},
async [State.OnlyWithFlag](context) {
await createAttachServer(context);
},
async [State.Smart](context) {
await createAttachServer(context);
},
async [State.Always](context) {
await createAttachServer(context);
},
};
/**
* Ensures the status bar text reflects the current state.
*/
function updateStatusBar(context: vscode.ExtensionContext, state: State, busy = false) {
if (state === State.Disabled && !busy) {
statusItem?.hide();
return;
}
if (!statusItem) {
statusItem = vscode.window.createStatusBarItem('status.debug.autoAttach', vscode.StatusBarAlignment.Left);
statusItem.name = localize('status.name.auto.attach', "Debug Auto Attach");
statusItem.command = TOGGLE_COMMAND;
statusItem.tooltip = localize('status.tooltip.auto.attach', "Automatically attach to node.js processes in debug mode");
context.subscriptions.push(statusItem);
}
let text = busy ? '$(loading) ' : '';
text += isTemporarilyDisabled ? TEXT_TEMP_DISABLE_LABEL : TEXT_STATUSBAR_LABEL[state];
statusItem.text = text;
statusItem.show();
}
/**
* Updates the auto attach feature based on the user or workspace setting
*/
function updateAutoAttach(newState: State) {
currentState = currentState.then(async ({ context, state: oldState }) => {
if (newState === oldState) {
return { context, state: oldState };
}
if (oldState !== null) {
updateStatusBar(context, oldState, true);
}
await transitions[newState](context);
isTemporarilyDisabled = false;
updateStatusBar(context, newState, false);
return { context, state: newState };
});
}
/**
* Gets the IPC address for the server to listen on for js-debug sessions. This
* is cached such that we can reuse the address of previous activations.
*/
async function getIpcAddress(context: vscode.ExtensionContext) {
// Iff the `cachedData` is present, the js-debug registered environment
// variables for this workspace--cachedData is set after successfully
// invoking the attachment command.
const cachedIpc = context.workspaceState.get<CachedIpcState>(STORAGE_IPC);
// We invalidate the IPC data if the js-debug path changes, since that
// indicates the extension was updated or reinstalled and the
// environment variables will have been lost.
// todo: make a way in the API to read environment data directly without activating js-debug?
const jsDebugPath =
vscode.extensions.getExtension('ms-vscode.js-debug-nightly')?.extensionPath ||
vscode.extensions.getExtension('ms-vscode.js-debug')?.extensionPath;
const settingsValue = getJsDebugSettingKey();
if (cachedIpc?.jsDebugPath === jsDebugPath && cachedIpc?.settingsValue === settingsValue) {
return cachedIpc.ipcAddress;
}
const result = await vscode.commands.executeCommand<{ ipcAddress: string }>(
'extension.js-debug.setAutoAttachVariables',
cachedIpc?.ipcAddress,
);
if (!result) {
return;
}
const ipcAddress = result.ipcAddress;
await context.workspaceState.update(STORAGE_IPC, {
ipcAddress,
jsDebugPath,
settingsValue,
} as CachedIpcState);
return ipcAddress;
}
function getJsDebugSettingKey() {
let o: { [key: string]: unknown } = {};
const config = vscode.workspace.getConfiguration(SETTING_SECTION);
for (const setting of SETTINGS_CAUSE_REFRESH) {
o[setting] = config.get(setting);
}
return JSON.stringify(o);
}