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 96
/
Copy pathconfigurationProvider.ts
303 lines (255 loc) · 9.57 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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
'use strict';
import * as vscode from 'vscode';
import { execSync } from 'child_process';
import { join, isAbsolute, dirname } from 'path';
import * as fs from 'fs';
import { log, localize } from './utilities';
import { detectDebugType, detectProtocolForPid, INSPECTOR_PORT_DEFAULT, LEGACY_PORT_DEFAULT } from './protocolDetection';
import { pickProcess } from './processPicker';
//---- NodeConfigurationProvider
export class NodeConfigurationProvider implements vscode.DebugConfigurationProvider {
/**
* 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> {
// if launch.json is missing or empty
if (!config.type && !config.request && !config.name) {
config = createLaunchConfigFromContext(folder, true);
if (!config.program) {
const message = localize('program.not.found.message', "Cannot find a program to debug");
return vscode.window.showInformationMessage(message).then(_ => {
return undefined; // abort launch
});
}
}
// make sure that config has a 'cwd' attribute set
if (!config.cwd) {
if (folder) {
config.cwd = folder.uri.fsPath;
} else if (config.program) {
// derive 'cwd' from 'program'
config.cwd = dirname(config.program);
}
}
// if we detect that VS Code was launched for WSL, we add the 'useWSL' attribute on the fly
if (process.platform === 'win32' && config.request === 'launch' && typeof config.useWSL !== 'boolean') {
const HOME = <string> process.env.HOME;
if (HOME && HOME.indexOf('/home/') === 0) {
config.useWSL = true;
}
}
// determine which protocol to use
return determineDebugType(config).then(debugType => {
if (debugType) {
config.type = debugType;
}
return config;
});
}
}
//---- helpers ----------------------------------------------------------------------------------------------------------------
function createLaunchConfigFromContext(folder: vscode.WorkspaceFolder | undefined, resolve: boolean): vscode.DebugConfiguration {
const config = {
type: 'node',
request: 'launch',
name: localize('node.launch.config.name', "Launch Program")
};
const pkg = loadJSON(folder, 'package.json');
if (pkg && pkg.name === 'mern-starter') {
if (resolve) {
log(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;
// try to find a better value for 'program' by analysing package.json
if (pkg) {
program = guessProgramFromPackage(folder, pkg);
if (program && resolve) {
log(localize('program.guessed.from.package.json.explanation', "Launch configuration created based on 'package.json'."));
}
}
// use file open in editor
if (!program && folder) {
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) {
const path = vscode.workspace.asRelativePath(editor.document.uri);
program = '${workspaceFolder}/' + path;
}
}
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) {
log(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): 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 (path && !fs.existsSync(path) && !fs.existsSync(path + '.js')) {
return undefined;
}
}
} catch (error) {
// silently ignore
}
return program;
}
//---- debug type -------------------------------------------------------------------------------------------------------------
function determineDebugType(config: any): Promise<string | null> {
if (config.request === 'attach' && typeof config.processId === 'string') {
return determineDebugTypeForPidConfig(config);
} else if (config.protocol === 'legacy') {
return Promise.resolve('node');
} else if (config.protocol === 'inspector') {
return Promise.resolve('node2');
} else {
// 'auto', or unspecified
return detectDebugType(config);
}
}
function determineDebugTypeForPidConfig(config: any): Promise<string | null> {
const getPidP = isPickProcessCommand(config.processId) ?
pickProcess() :
Promise.resolve(config.processId);
return getPidP.then(pid => {
if (pid && pid.match(/^[0-9]+$/)) {
const pidNum = Number(pid);
putPidInDebugMode(pidNum);
return determineDebugTypeForPidInDebugMode(config, pidNum);
} else {
throw new Error(localize('VSND2006', "Attach to process: '{0}' doesn't look like a process id.", pid));
}
}).then(debugType => {
if (debugType) {
// processID is handled, so turn this config into a normal port attach config
config.processId = undefined;
config.port = debugType === 'node2' ? INSPECTOR_PORT_DEFAULT : LEGACY_PORT_DEFAULT;
}
return debugType;
});
}
function isPickProcessCommand(configProcessId: string): boolean {
configProcessId = configProcessId.trim();
return configProcessId === '${command:PickProcess}' || configProcessId === '${command:extension.pickNodeProcess}';
}
function putPidInDebugMode(pid: number): void {
try {
if (process.platform === 'win32') {
// regular node has an undocumented API function for forcing another node process into debug mode.
// (<any>process)._debugProcess(pid);
// But since we are running on Electron's node, process._debugProcess doesn't work (for unknown reasons).
// So we use a regular node instead:
const command = `node -e process._debugProcess(${pid})`;
execSync(command);
} else {
process.kill(pid, 'SIGUSR1');
}
} catch (e) {
throw new Error(localize('VSND2021', "Attach to process: cannot enable debug mode for process '{0}' ({1}).", pid, e));
}
}
function determineDebugTypeForPidInDebugMode(config: any, pid: number): Promise<string | null> {
let debugProtocolP: Promise<string | null>;
if (config.port === INSPECTOR_PORT_DEFAULT) {
debugProtocolP = Promise.resolve('inspector');
} else if (config.port === LEGACY_PORT_DEFAULT) {
debugProtocolP = Promise.resolve('legacy');
} else if (config.protocol) {
debugProtocolP = Promise.resolve(config.protocol);
} else {
debugProtocolP = detectProtocolForPid(pid);
}
return debugProtocolP.then(debugProtocol => {
return debugProtocol === 'inspector' ? 'node2' :
debugProtocol === 'legacy' ? 'node' :
null;
});
}