This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 97
/
configurationProvider.ts
431 lines (362 loc) · 13.4 KB
/
configurationProvider.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
'use strict';
import * as nls from 'vscode-nls';
import * as vscode from 'vscode';
import { join, isAbsolute, dirname } from 'path';
import * as fs from 'fs';
import { writeToConsole, mkdirP, Logger } from './utilities';
import { detectDebugType } from './protocolDetection';
import { resolveProcessId } from './processPicker';
import { Cluster } from './cluster';
const localize = nls.loadMessageBundle();
let stopOnEntry = false;
export function startDebuggingAndStopOnEntry() {
stopOnEntry = true;
vscode.commands.executeCommand('workbench.action.debug.start');
}
//---- NodeConfigurationProvider
export class NodeConfigurationProvider implements vscode.DebugConfigurationProvider {
private _logger: Logger;
constructor(private _extensionContext: vscode.ExtensionContext) {
this._logger = new Logger();
}
/**
* Returns an initial debug configuration based on contextual information, e.g. package.json or folder.
*/
provideDebugConfigurations(folder: vscode.WorkspaceFolder | undefined, token?: vscode.CancellationToken): vscode.ProviderResult<vscode.DebugConfiguration[]> {
return [createLaunchConfigFromContext(folder, false)];
}
/**
* Try to add all missing attributes to the debug configuration being launched.
*/
resolveDebugConfiguration(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, token?: vscode.CancellationToken): vscode.ProviderResult<vscode.DebugConfiguration> {
return this.resolveConfigAsync(folder, config).catch(err => {
return vscode.window.showErrorMessage(err.message, { modal: true }).then(_ => undefined); // abort launch
});
}
/**
* Try to add all missing attributes to the debug configuration being launched.
*/
private async resolveConfigAsync(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration | undefined> {
// if launch.json is missing or empty
if (!config.type && !config.request && !config.name) {
config = createLaunchConfigFromContext(folder, true, config);
if (!config.program) {
throw new Error(localize('program.not.found.message', "Cannot find a program to debug"));
}
}
// make sure that config has a 'cwd' attribute set
if (!config.cwd) {
if (folder) {
config.cwd = folder.uri.fsPath;
}
// no folder -> config is a user or workspace launch config
if (!config.cwd && vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) {
config.cwd = vscode.workspace.workspaceFolders[0].uri.fsPath;
}
// no folder case
if (!config.cwd && config.program === '${file}') {
config.cwd = '${fileDirname}';
}
// program is some absolute path
if (!config.cwd && config.program && isAbsolute(config.program)) {
// derive 'cwd' from 'program'
config.cwd = dirname(config.program);
}
// last resort
if (!config.cwd) {
config.cwd = '${workspaceFolder}';
}
}
// remove 'useWSL' on all platforms but Windows
if (process.platform !== 'win32' && config.useWSL) {
this._logger.debug('useWSL attribute ignored on non-Windows OS.');
delete config.useWSL;
}
// when using "integratedTerminal" ensure that debug console doesn't get activated; see #43164
if (config.console === 'integratedTerminal' && !config.internalConsoleOptions) {
config.internalConsoleOptions = 'neverOpen';
}
// "nvm" support
if (config.request === 'launch' && typeof config.runtimeVersion === 'string' && config.runtimeVersion !== 'default') {
await this.nvmSupport(config);
}
// "auto attach child process" support
if (config.autoAttachChildProcesses) {
Cluster.prepareAutoAttachChildProcesses(folder, config);
}
// "attach to process via picker" support
if (config.request === 'attach' && typeof config.processId === 'string') {
// we resolve Process Picker early (before VS Code) so that we can probe the process for its protocol
if (await resolveProcessId(config)) {
return undefined; // abort launch
}
}
// finally determine which protocol to use
const debugType = await determineDebugType(config, this._logger);
if (debugType) {
config.type = debugType;
}
// fixup log parameters
if (config.trace && !config.logFilePath) {
const fileName = config.type === 'node' ? 'debugadapter-legacy.txt' : 'debugadapter.txt';
if (this._extensionContext.logPath) {
try {
await mkdirP(this._extensionContext.logPath);
} catch (e) {
// Already exists
}
config.logFilePath = join(this._extensionContext.logPath, fileName);
}
}
if (stopOnEntry) {
config.stopOnEntry = true;
stopOnEntry = false;
}
// everything ok: let VS Code start the debug session
return config;
}
/**
* if a runtime version is specified we prepend env.PATH with the folder that corresponds to the version.
* Returns false on error
*/
private async nvmSupport(config: vscode.DebugConfiguration): Promise<void> {
let bin: string | undefined = undefined;
let versionManagerName: string | undefined = undefined;
// first try the Node Version Switcher 'nvs'
let nvsHome = process.env['NVS_HOME'];
if (!nvsHome) {
// NVS_HOME is not always set. Probe for 'nvs' directory instead
const nvsDir = process.platform === 'win32' ? join(process.env['LOCALAPPDATA'] || '', 'nvs') : join(process.env['HOME'] || '', '.nvs');
if (fs.existsSync(nvsDir)) {
nvsHome = nvsDir;
}
}
const { nvsFormat, remoteName, semanticVersion, arch } = parseVersionString(config.runtimeVersion);
if (nvsFormat || nvsHome) {
if (nvsHome) {
bin = join(nvsHome, remoteName, semanticVersion, arch);
if (process.platform !== 'win32') {
bin = join(bin, 'bin');
}
versionManagerName = 'nvs';
} else {
throw new Error(localize('NVS_HOME.not.found.message', "Attribute 'runtimeVersion' requires Node.js version manager 'nvs'."));
}
}
if (!bin) {
// now try the Node Version Manager 'nvm'
if (process.platform === 'win32') {
const nvmHome = process.env['NVM_HOME'];
if (!nvmHome) {
throw new Error(localize('NVM_HOME.not.found.message', "Attribute 'runtimeVersion' requires Node.js version manager 'nvm-windows' or 'nvs'."));
}
bin = join(nvmHome, `v${config.runtimeVersion}`);
versionManagerName = 'nvm-windows';
} else { // macOS and linux
let nvmHome = process.env['NVM_DIR'];
if (!nvmHome) {
// if NVM_DIR is not set. Probe for '.nvm' directory instead
const nvmDir = join(process.env['HOME'] || '', '.nvm');
if (fs.existsSync(nvmDir)) {
nvmHome = nvmDir;
}
}
if (!nvmHome) {
throw new Error(localize('NVM_DIR.not.found.message', "Attribute 'runtimeVersion' requires Node.js version manager 'nvm' or 'nvs'."));
}
bin = join(nvmHome, 'versions', 'node', `v${config.runtimeVersion}`, 'bin');
versionManagerName = 'nvm';
}
}
if (fs.existsSync(bin)) {
if (!config.env) {
config.env = {};
}
if (process.platform === 'win32') {
config.env['Path'] = `${bin};${process.env['Path']}`;
} else {
config.env['PATH'] = `${bin}:${process.env['PATH']}`;
}
} else {
throw new Error(localize('runtime.version.not.found.message', "Node.js version '{0}' not installed for '{1}'.", config.runtimeVersion, versionManagerName));
}
}
}
//---- helpers ----------------------------------------------------------------------------------------------------------------
function createLaunchConfigFromContext(folder: vscode.WorkspaceFolder | undefined, resolve: boolean, existingConfig?: vscode.DebugConfiguration): vscode.DebugConfiguration {
const config = {
type: 'node',
request: 'launch',
name: localize('node.launch.config.name', "Launch Program")
};
if (existingConfig && existingConfig.noDebug) {
config['noDebug'] = true;
}
const pkg = loadJSON(folder, 'package.json');
if (pkg && pkg.name === 'mern-starter') {
if (resolve) {
writeToConsole(localize({ key: 'mern.starter.explanation', comment: ['argument contains product name without translation'] }, "Launch configuration for '{0}' project created.", 'Mern Starter'));
}
configureMern(config);
} else {
let program: string | undefined;
let useSourceMaps = false;
if (pkg) {
// try to find a value for 'program' by analysing package.json
program = guessProgramFromPackage(folder, pkg, resolve);
if (program && resolve) {
writeToConsole(localize('program.guessed.from.package.json.explanation', "Launch configuration created based on 'package.json'."));
}
}
if (!program) {
// try to use file open in editor
const editor = vscode.window.activeTextEditor;
if (editor) {
const languageId = editor.document.languageId;
if (languageId === 'javascript' || isTranspiledLanguage(languageId)) {
const wf = vscode.workspace.getWorkspaceFolder(editor.document.uri);
if (wf === folder) {
program = vscode.workspace.asRelativePath(editor.document.uri);
if (!isAbsolute(program)) {
program = '${workspaceFolder}/' + program;
}
}
}
useSourceMaps = isTranspiledLanguage(languageId);
}
}
// if we couldn't find a value for 'program', we just let the launch config use the file open in the editor
if (!resolve && !program) {
program = '${file}';
}
if (program) {
config['program'] = program;
}
// prepare for source maps by adding 'outFiles' if typescript or coffeescript is detected
if (useSourceMaps || vscode.workspace.textDocuments.some(document => isTranspiledLanguage(document.languageId))) {
if (resolve) {
writeToConsole(localize('outFiles.explanation', "Adjust glob pattern(s) in the 'outFiles' attribute so that they cover the generated JavaScript."));
}
let dir = '';
const tsConfig = loadJSON(folder, 'tsconfig.json');
if (tsConfig && tsConfig.compilerOptions && tsConfig.compilerOptions.outDir) {
const outDir = <string>tsConfig.compilerOptions.outDir;
if (!isAbsolute(outDir)) {
dir = outDir;
if (dir.indexOf('./') === 0) {
dir = dir.substr(2);
}
if (dir[dir.length - 1] !== '/') {
dir += '/';
}
}
config['preLaunchTask'] = 'tsc: build - tsconfig.json';
}
config['outFiles'] = ['${workspaceFolder}/' + dir + '**/*.js'];
}
}
return config;
}
function loadJSON(folder: vscode.WorkspaceFolder | undefined, file: string): any {
if (folder) {
try {
const path = join(folder.uri.fsPath, file);
const content = fs.readFileSync(path, 'utf8');
return JSON.parse(content);
} catch (error) {
// silently ignore
}
}
return undefined;
}
function configureMern(config: any) {
config.protocol = 'inspector';
config.runtimeExecutable = 'nodemon';
config.program = '${workspaceFolder}/index.js';
config.restart = true;
config.env = {
BABEL_DISABLE_CACHE: '1',
NODE_ENV: 'development'
};
config.console = 'integratedTerminal';
config.internalConsoleOptions = 'neverOpen';
}
function isTranspiledLanguage(languagId: string): boolean {
return languagId === 'typescript' || languagId === 'coffeescript';
}
/*
* try to find the entry point ('main') from the package.json
*/
function guessProgramFromPackage(folder: vscode.WorkspaceFolder | undefined, packageJson: any, resolve: boolean): string | undefined {
let program: string | undefined;
try {
if (packageJson.main) {
program = packageJson.main;
} else if (packageJson.scripts && typeof packageJson.scripts.start === 'string') {
// assume a start script of the form 'node server.js'
program = (<string>packageJson.scripts.start).split(' ').pop();
}
if (program) {
let path: string | undefined;
if (isAbsolute(program)) {
path = program;
} else {
path = folder ? join(folder.uri.fsPath, program) : undefined;
program = join('${workspaceFolder}', program);
}
if (resolve && path && !fs.existsSync(path) && !fs.existsSync(path + '.js')) {
return undefined;
}
}
} catch (error) {
// silently ignore
}
return program;
}
//---- debug type -------------------------------------------------------------------------------------------------------------
function determineDebugType(config: any, logger: Logger): Promise<string | null> {
if (config.protocol === 'legacy') {
return Promise.resolve('node');
} else if (config.protocol === 'inspector') {
return Promise.resolve('node2');
} else {
// 'auto', or unspecified
return detectDebugType(config, logger);
}
}
function nvsStandardArchName(arch) {
switch (arch) {
case '32':
case 'x86':
case 'ia32':
return 'x86';
case '64':
case 'x64':
case 'amd64':
return 'x64';
case 'arm':
const arm_version = (process.config.variables as any).arm_version;
return arm_version ? 'armv' + arm_version + 'l' : 'arm';
default:
return arch;
}
}
/**
* Parses a node version string into remote name, semantic version, and architecture
* components. Infers some unspecified components based on configuration.
*/
function parseVersionString(versionString) {
const versionRegex = /^(([\w-]+)\/)?(v?(\d+(\.\d+(\.\d+)?)?))(\/((x86)|(32)|((x)?64)|(arm\w*)|(ppc\w*)))?$/i;
const match = versionRegex.exec(versionString);
if (!match) {
throw new Error('Invalid version string: ' + versionString);
}
const nvsFormat = !!(match[2] || match[8]);
const remoteName = match[2] || 'node';
const semanticVersion = match[4] || '';
const arch = nvsStandardArchName(match[8] || process.arch);
return { nvsFormat, remoteName, semanticVersion, arch };
}