forked from microsoft/vscode-python-debugger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlegacyPython.ts
More file actions
240 lines (223 loc) · 9.66 KB
/
legacyPython.ts
File metadata and controls
240 lines (223 loc) · 9.66 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/* eslint-disable @typescript-eslint/naming-convention */
import {
ActiveEnvironmentPathChangeEvent,
Environment,
EnvironmentPath,
EnvironmentVariables,
PythonExtension,
ResolvedEnvironment,
Resource,
} from '@vscode/python-extension';
import { EventEmitter, extensions, Uri, Disposable, Extension } from 'vscode';
import { createDeferred } from './utils/async';
import { traceError, traceLog } from './log/logging';
/**
* Interface for the Python extension API.
*/
interface LegacyIExtensionApi {
ready: Promise<void>;
settings: {
getExecutionDetails(resource?: Resource): { execCommand: string[] | undefined };
};
}
/**
* Details about a Python interpreter.
*/
export interface LegacyIInterpreterDetails {
/** Array of path components to the Python executable */
path?: string[];
/** The workspace resource associated with this interpreter */
resource?: Uri;
}
// /** Event emitter for Python interpreter changes */
// const legacyOnDidChangePythonInterpreterEvent = new EventEmitter<LegacyIInterpreterDetails>();
// /** Event that fires when the active Python interpreter changes */
// export const legacyOnDidChangePythonInterpreter: Event<LegacyIInterpreterDetails> =
// legacyOnDidChangePythonInterpreterEvent.event;
/**
* Activates the Python extension and ensures it's ready for use.
* @returns The activated Python extension instance
*/
async function legacyActivateExtension(): Promise<Extension<any> | undefined> {
console.log('Activating Python extension...');
activateEnvsExtension();
const extension = extensions.getExtension('ms-python.python');
if (extension) {
if (!extension.isActive) {
await extension.activate();
}
}
console.log('Python extension activated.');
return extension;
}
/**
* Activates the Python environments extension.
* @returns The activated Python environments extension instance
*/
async function activateEnvsExtension(): Promise<Extension<any> | undefined> {
const extension = extensions.getExtension('ms-python.vscode-python-envs');
if (extension) {
if (!extension.isActive) {
await extension.activate();
}
}
return extension;
}
/**
* Gets the Python extension's API interface.
* @returns The Python extension API or undefined if not available
*/
async function legacyGetPythonExtensionAPI(): Promise<LegacyIExtensionApi | undefined> {
const extension = await legacyActivateExtension();
return extension?.exports as LegacyIExtensionApi;
}
/**
* Gets the Python extension's environment API.
* @returns The Python extension environment API
*/
async function legacyGetPythonExtensionEnviromentAPI(): Promise<PythonExtension> {
// Load the Python extension API
await legacyActivateExtension();
return await PythonExtension.api();
}
/**
* Initializes Python integration by setting up event listeners and getting initial interpreter details.
* @param disposables Array to store disposable resources for cleanup
*/
export async function legacyInitializePython(
disposables: Disposable[],
onDidChangePythonInterpreterEvent: EventEmitter<LegacyIInterpreterDetails>,
): Promise<void> {
try {
traceLog('legacyInitializePython: Starting initialization');
const api = await legacyGetPythonExtensionEnviromentAPI();
if (api) {
disposables.push(
// This event is triggered when the active environment setting changes.
api.environments.onDidChangeActiveEnvironmentPath((e: ActiveEnvironmentPathChangeEvent) => {
traceLog(`legacyInitializePython: Active environment path changed to '${e.path}'`);
let resourceUri: Uri | undefined;
if (e.resource instanceof Uri) {
resourceUri = e.resource;
}
if (e.resource && 'uri' in e.resource) {
// WorkspaceFolder type
resourceUri = e.resource.uri;
}
onDidChangePythonInterpreterEvent.fire({ path: [e.path], resource: resourceUri });
}),
);
traceLog('Waiting for interpreter from python extension.');
onDidChangePythonInterpreterEvent.fire(await legacyGetInterpreterDetails());
traceLog('legacyInitializePython: Initial interpreter details fired');
}
} catch (error) {
traceError('Error initializing python: ', error);
}
}
/**
* Returns all the details needed to execute code within the selected environment,
* corresponding to the specified resource taking into account any workspace-specific settings
* for the workspace to which this resource belongs.
* @param resource Optional workspace resource to get settings for
* @returns Array of command components or undefined if not available
*/
export async function legacyGetSettingsPythonPath(resource?: Uri): Promise<string[] | undefined> {
const api = await legacyGetPythonExtensionAPI();
const execCommand = api?.settings.getExecutionDetails(resource).execCommand;
traceLog(`legacyGetSettingsPythonPath: execCommand='${execCommand?.join(' ')}' resource='${resource?.fsPath}'`);
return execCommand;
}
/**
* Returns the environment variables used by the extension for a resource, which includes the custom
* variables configured by user in `.env` files.
* @param resource Optional workspace resource to get environment variables for
* @returns Environment variables object
*/
export async function legacyGetEnvironmentVariables(resource?: Resource): Promise<EnvironmentVariables> {
const api = await legacyGetPythonExtensionEnviromentAPI();
return Promise.resolve(api.environments.getEnvironmentVariables(resource));
}
/**
* Returns details for the given environment, or `undefined` if the env is invalid.
* @param env Environment to resolve (can be Environment object, path, or string)
* @returns Resolved environment details
*/
export async function legacyResolveEnvironment(
env: Environment | EnvironmentPath | string,
): Promise<ResolvedEnvironment | undefined> {
const api = await legacyGetPythonExtensionEnviromentAPI();
traceLog(`legacyResolveEnvironment: Resolving environment '${typeof env === 'string' ? env : (env as any).path}'`);
const resolved = api.environments.resolveEnvironment(env);
resolved.then((r) => traceLog(`legacyResolveEnvironment: Resolved executable='${r?.executable.uri?.fsPath}'`));
return resolved;
}
/**
* Returns the environment configured by user in settings. Note that this can be an invalid environment, use
* resolve the environment to get full details.
* @param resource Optional workspace resource to get active environment for
* @returns Path to the active environment
*/
export async function legacyGetActiveEnvironmentPath(resource?: Resource): Promise<EnvironmentPath> {
const api = await legacyGetPythonExtensionEnviromentAPI();
const active = api.environments.getActiveEnvironmentPath(resource);
traceLog(
`legacyGetActiveEnvironmentPath: activePath='${active.path}' resource='${
(resource as any)?.uri?.fsPath || (resource as Uri)?.fsPath || ''
}'`,
);
return active;
}
/**
* Gets detailed information about the active Python interpreter.
* @param resource Optional workspace resource to get interpreter details for
* @returns Interpreter details including path and resource information
*/
export async function legacyGetInterpreterDetails(resource?: Uri): Promise<LegacyIInterpreterDetails> {
const api = await legacyGetPythonExtensionEnviromentAPI();
const environment = await api.environments.resolveEnvironment(api.environments.getActiveEnvironmentPath(resource));
if (environment?.executable.uri) {
traceLog(
`legacyGetInterpreterDetails: executable='${environment.executable.uri.fsPath}' resource='${resource?.fsPath}'`,
);
return { path: [environment?.executable.uri.fsPath], resource };
}
traceLog('legacyGetInterpreterDetails: No executable found');
return { path: undefined, resource };
}
/**
* Checks if any Python interpreters are available in the system.
* @returns True if interpreters are found, false otherwise
*/
export async function legacyHasInterpreters(): Promise<boolean> {
const api = await legacyGetPythonExtensionEnviromentAPI();
const onAddedToCollection = createDeferred();
api.environments.onDidChangeEnvironments(async () => {
if (api.environments.known) {
onAddedToCollection.resolve();
}
});
const initialEnvs = api.environments.known;
if (initialEnvs.length > 0) {
traceLog(`legacyHasInterpreters: Found ${initialEnvs.length} initial environments`);
return true;
}
// Initiates a refresh of Python environments within the specified scope.
await Promise.race([onAddedToCollection.promise, api?.environments.refreshEnvironments()]);
const has = api.environments.known.length > 0;
traceLog(`legacyHasInterpreters: After refresh count='${api.environments.known.length}' result='${has}'`);
return has;
}
/**
* Gets environments known to the extension at the time of fetching the property. Note this may not
* contain all environments in the system as a refresh might be going on.
* @returns Array of known Python environments
*/
export async function legacyGetInterpreters(): Promise<readonly Environment[]> {
const api = await legacyGetPythonExtensionEnviromentAPI();
const known = api.environments.known || [];
traceLog(`legacyGetInterpreters: returning ${known.length} environments`);
return known;
}