forked from microsoft/vscode-python-debugger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.ts
More file actions
329 lines (296 loc) · 14.3 KB
/
base.ts
File metadata and controls
329 lines (296 loc) · 14.3 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import * as path from 'path';
import { CancellationToken, DebugConfiguration, Uri, WorkspaceFolder } from 'vscode';
import { sendTelemetryEvent } from '../../../telemetry';
import { EventName } from '../../../telemetry/constants';
import { DebuggerTelemetry } from '../../../telemetry/types';
import { getWorkspaceFolders, getWorkspaceFolder as getVSCodeWorkspaceFolder } from '../../../common/vscodeapi';
import { AttachRequestArguments, DebugOptions, LaunchRequestArguments, PathMapping } from '../../../types';
import { PythonPathSource } from '../../types';
import { IDebugConfigurationResolver } from '../types';
import { resolveWorkspaceVariables } from '../utils/common';
import { getProgram } from './helper';
import { getSettingsPythonPath, getInterpreterDetails } from '../../../common/python';
import { getOSType, OSType } from '../../../common/platform';
import { traceLog } from '../../../common/log/logging';
export abstract class BaseConfigurationResolver<T extends DebugConfiguration>
implements IDebugConfigurationResolver<T>
{
protected pythonPathSource: PythonPathSource = PythonPathSource.launchJson;
constructor() {}
// This is a legacy hook used solely for backwards-compatible manual substitution
// of ${command:python.interpreterPath} in "pythonPath", for the sake of other
// existing implementations of resolveDebugConfiguration() that may rely on it.
//
// For all future config variables, expansion should be performed by VSCode itself,
// and validation of debug configuration in derived classes should be performed in
// resolveDebugConfigurationWithSubstitutedVariables() instead, where all variables
// are already substituted.
// eslint-disable-next-line class-methods-use-this
public async resolveDebugConfiguration(
_folder: WorkspaceFolder | undefined,
debugConfiguration: DebugConfiguration,
_token?: CancellationToken,
): Promise<T | undefined> {
if (!debugConfiguration.clientOS) {
debugConfiguration.clientOS = getOSType() === OSType.Windows ? 'windows' : 'unix';
}
if (debugConfiguration.consoleName) {
debugConfiguration.consoleTitle = debugConfiguration.consoleName;
delete debugConfiguration.consoleName;
}
return debugConfiguration as T;
}
public abstract resolveDebugConfigurationWithSubstitutedVariables(
folder: WorkspaceFolder | undefined,
debugConfiguration: DebugConfiguration,
token?: CancellationToken,
): Promise<T | undefined>;
protected static getWorkspaceFolder(folder: WorkspaceFolder | undefined): Uri | undefined {
if (folder) {
return folder.uri;
}
const program = getProgram();
const workspaceFolders = getWorkspaceFolders();
if (!Array.isArray(workspaceFolders) || workspaceFolders.length === 0) {
traceLog('No workspace folder found');
return program ? Uri.file(path.dirname(program)) : undefined;
}
if (workspaceFolders.length === 1) {
traceLog('Using the only workspaceFolder found: ', workspaceFolders[0].uri.fsPath);
return workspaceFolders[0].uri;
}
if (program) {
const workspaceFolder = getVSCodeWorkspaceFolder(Uri.file(program));
if (workspaceFolder) {
traceLog('Using workspaceFolder found for the program: ', workspaceFolder.uri.fsPath);
return workspaceFolder.uri;
}
}
return undefined;
}
/**
* Resolves and updates file paths and Python interpreter paths in the debug configuration.
*
* This method performs two main operations:
* 1. Resolves workspace variables in the envFile path (if specified)
* 2. Resolves and updates Python interpreter paths, handling legacy pythonPath deprecation
*
* @param workspaceFolder The workspace folder URI for variable resolution
* @param debugConfiguration The launch configuration to update
*/
protected async resolveAndUpdatePaths(
workspaceFolder: Uri | undefined,
debugConfiguration: LaunchRequestArguments,
): Promise<void> {
BaseConfigurationResolver.resolveAndUpdateEnvFilePath(workspaceFolder, debugConfiguration);
await this.resolveAndUpdatePythonPath(workspaceFolder, debugConfiguration);
}
/**
* Resolves workspace variables in the envFile path.
*
* Expands variables like ${workspaceFolder} in the envFile configuration using the
* workspace folder path or current working directory as the base for resolution.
*
* @param workspaceFolder The workspace folder URI for variable resolution
* @param debugConfiguration The launch configuration containing the envFile path
*/
protected static resolveAndUpdateEnvFilePath(
workspaceFolder: Uri | undefined,
debugConfiguration: LaunchRequestArguments,
): void {
// Early exit if no configuration or no envFile to resolve
if (!debugConfiguration?.envFile) {
return;
}
const basePath = workspaceFolder?.fsPath || debugConfiguration.cwd;
if (basePath) {
// update envFile with resolved variables
debugConfiguration.envFile = resolveWorkspaceVariables(debugConfiguration.envFile, basePath, undefined);
}
}
/**
* Resolves Python interpreter paths and handles the legacy pythonPath deprecation.
*
* @param workspaceFolder The workspace folder URI for variable resolution and interpreter detection
* @param debugConfiguration The launch configuration to update with resolved Python paths
*/
protected async resolveAndUpdatePythonPath(
workspaceFolder: Uri | undefined,
debugConfiguration: LaunchRequestArguments,
): Promise<void> {
if (!debugConfiguration) {
return;
}
// get the interpreter details in the context of the workspace folder
const interpreterDetail = await getInterpreterDetails(workspaceFolder);
const interpreterPath = interpreterDetail?.path ?? (await getSettingsPythonPath(workspaceFolder));
const resolvedInterpreterPath = interpreterPath ? interpreterPath[0] : interpreterPath;
traceLog(
`resolveAndUpdatePythonPath - Initial state: ` +
`pythonPath='${debugConfiguration.pythonPath}', ` +
`python='${debugConfiguration.python}', ` +
`debugAdapterPython='${debugConfiguration.debugAdapterPython}', ` +
`debugLauncherPython='${debugConfiguration.debugLauncherPython}', ` +
`workspaceFolder='${workspaceFolder?.fsPath}'` +
`resolvedInterpreterPath='${resolvedInterpreterPath}'`,
);
// STEP 1: Resolve legacy pythonPath property (DEPRECATED)
// pythonPath will equal user set value, or getInterpreterDetails if undefined or set to command
if (debugConfiguration.pythonPath === '${command:python.interpreterPath}' || !debugConfiguration.pythonPath) {
this.pythonPathSource = PythonPathSource.settingsJson;
debugConfiguration.pythonPath = resolvedInterpreterPath;
} else {
// User provided explicit pythonPath in launch.json
debugConfiguration.pythonPath = resolveWorkspaceVariables(
debugConfiguration.pythonPath,
workspaceFolder?.fsPath,
undefined,
);
}
// STEP 2: Resolve current python property (CURRENT STANDARD)
if (debugConfiguration.python === '${command:python.interpreterPath}') {
// if python is set to the command, resolve it
this.pythonPathSource = PythonPathSource.settingsJson;
debugConfiguration.python = resolvedInterpreterPath;
} else if (!debugConfiguration.python) {
// fallback to pythonPath if python undefined
this.pythonPathSource = PythonPathSource.settingsJson;
debugConfiguration.python = debugConfiguration.pythonPath;
} else {
// User provided explicit python path in launch.json
this.pythonPathSource = PythonPathSource.launchJson;
debugConfiguration.python = resolveWorkspaceVariables(
debugConfiguration.python,
workspaceFolder?.fsPath,
undefined,
);
}
// STEP 3: Set debug adapter and launcher Python paths (backwards compatible)
this.setDebugComponentPythonPaths(debugConfiguration);
// STEP 4: Clean up - remove the deprecated pythonPath property
delete debugConfiguration.pythonPath;
}
/**
* Sets debugAdapterPython and debugLauncherPython with backwards compatibility.
* Prefers pythonPath over python for these internal properties.
*
* @param debugConfiguration The debug configuration to update
*/
private setDebugComponentPythonPaths(debugConfiguration: LaunchRequestArguments): void {
const shouldSetDebugAdapter =
debugConfiguration.debugAdapterPython === '${command:python.interpreterPath}' ||
debugConfiguration.debugAdapterPython === undefined;
const shouldSetDebugLauncher =
debugConfiguration.debugLauncherPython === '${command:python.interpreterPath}' ||
debugConfiguration.debugLauncherPython === undefined;
// Default fallback path (prefer pythonPath for backwards compatibility)
const fallbackPath = debugConfiguration.pythonPath ?? debugConfiguration.python;
if (debugConfiguration.pythonPath !== debugConfiguration.python) {
sendTelemetryEvent(EventName.DEPRECATED_CODE_PATH_USAGE, undefined, {
codePath: 'different_python_paths_in_debug_config',
});
}
if (shouldSetDebugAdapter) {
debugConfiguration.debugAdapterPython = fallbackPath;
}
if (shouldSetDebugLauncher) {
debugConfiguration.debugLauncherPython = fallbackPath;
}
}
protected static debugOption(debugOptions: DebugOptions[], debugOption: DebugOptions): void {
if (debugOptions.indexOf(debugOption) >= 0) {
return;
}
debugOptions.push(debugOption);
}
protected static isLocalHost(hostName?: string): boolean {
const localHosts = ['localhost', '127.0.0.1', '::1'];
return !!(hostName && localHosts.indexOf(hostName.toLowerCase()) >= 0);
}
protected static fixUpPathMappings(
pathMappings: PathMapping[],
defaultLocalRoot?: string,
defaultRemoteRoot?: string,
): PathMapping[] {
if (!defaultLocalRoot) {
return [];
}
if (!defaultRemoteRoot) {
defaultRemoteRoot = defaultLocalRoot;
}
if (pathMappings.length === 0) {
pathMappings = [
{
localRoot: defaultLocalRoot,
remoteRoot: defaultRemoteRoot,
},
];
} else {
// Expand ${workspaceFolder} variable first if necessary.
pathMappings = pathMappings.map(({ localRoot: mappedLocalRoot, remoteRoot }) => {
const resolvedLocalRoot = resolveWorkspaceVariables(mappedLocalRoot, defaultLocalRoot, undefined);
return {
localRoot: resolvedLocalRoot || '',
// TODO: Apply to remoteRoot too?
remoteRoot,
};
});
}
// If on Windows, lowercase the drive letter for path mappings.
// TODO: Apply even if no localRoot?
if (getOSType() === OSType.Windows) {
// TODO: Apply to remoteRoot too?
pathMappings = pathMappings.map(({ localRoot: windowsLocalRoot, remoteRoot }) => {
let localRoot = windowsLocalRoot;
if (windowsLocalRoot.match(/^[A-Z]:/)) {
localRoot = `${windowsLocalRoot[0].toLowerCase()}${windowsLocalRoot.substr(1)}`;
}
return { localRoot, remoteRoot };
});
}
return pathMappings;
}
protected static isDebuggingFastAPI(
debugConfiguration: Partial<LaunchRequestArguments & AttachRequestArguments>,
): boolean {
return !!(debugConfiguration.module && debugConfiguration.module.toUpperCase() === 'FASTAPI');
}
protected static isDebuggingFlask(
debugConfiguration: Partial<LaunchRequestArguments & AttachRequestArguments>,
): boolean {
return !!(debugConfiguration.module && debugConfiguration.module.toUpperCase() === 'FLASK');
}
protected static sendTelemetry(
trigger: 'launch' | 'attach' | 'test',
debugConfiguration: Partial<LaunchRequestArguments & AttachRequestArguments>,
): void {
const name = debugConfiguration.name || '';
const moduleName = debugConfiguration.module || '';
const telemetryProps: DebuggerTelemetry = {
trigger,
console: debugConfiguration.console,
hasEnvVars: typeof debugConfiguration.env === 'object' && Object.keys(debugConfiguration.env).length > 0,
django: !!debugConfiguration.django,
fastapi: BaseConfigurationResolver.isDebuggingFastAPI(debugConfiguration),
flask: BaseConfigurationResolver.isDebuggingFlask(debugConfiguration),
hasArgs: Array.isArray(debugConfiguration.args) && debugConfiguration.args.length > 0,
isLocalhost: BaseConfigurationResolver.isLocalHost(debugConfiguration.host),
isModule: moduleName.length > 0,
isSudo: !!debugConfiguration.sudo,
jinja: !!debugConfiguration.jinja,
pyramid: !!debugConfiguration.pyramid,
stopOnEntry: !!debugConfiguration.stopOnEntry,
showReturnValue: !!debugConfiguration.showReturnValue,
subProcess: !!debugConfiguration.subProcess,
autoStartBrowser: !!debugConfiguration,
watson: name.toLowerCase().indexOf('watson') >= 0,
pyspark: name.toLowerCase().indexOf('pyspark') >= 0,
gevent: name.toLowerCase().indexOf('gevent') >= 0,
scrapy: moduleName.toLowerCase() === 'scrapy',
};
sendTelemetryEvent(EventName.DEBUGGER, undefined, telemetryProps);
}
}