forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcreateVirtualEnvTool.ts
More file actions
227 lines (211 loc) · 9.68 KB
/
createVirtualEnvTool.ts
File metadata and controls
227 lines (211 loc) · 9.68 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import {
CancellationError,
CancellationToken,
l10n,
LanguageModelTool,
LanguageModelToolInvocationOptions,
LanguageModelToolInvocationPrepareOptions,
LanguageModelToolResult,
PreparedToolInvocation,
Uri,
workspace,
} from 'vscode';
import { PythonExtension, ResolvedEnvironment } from '../api/types';
import { IServiceContainer } from '../ioc/types';
import { ICodeExecutionService } from '../terminals/types';
import { TerminalCodeExecutionProvider } from '../terminals/codeExecution/terminalCodeExecution';
import {
doesWorkspaceHaveVenvOrCondaEnv,
getDisplayVersion,
getEnvDetailsForResponse,
IResourceReference,
isCancellationError,
raceCancellationError,
} from './utils';
import { resolveFilePath } from './utils';
import { ITerminalHelper } from '../common/terminal/types';
import { raceTimeout, sleep } from '../common/utils/async';
import { IInterpreterPathService } from '../common/types';
import { DisposableStore } from '../common/utils/resourceLifecycle';
import { IRecommendedEnvironmentService } from '../interpreter/configuration/types';
import { EnvironmentType } from '../pythonEnvironments/info';
import { IDiscoveryAPI } from '../pythonEnvironments/base/locator';
import { convertEnvInfoToPythonEnvironment } from '../pythonEnvironments/legacyIOC';
import { sortInterpreters } from '../interpreter/helpers';
import { isStableVersion } from '../pythonEnvironments/info/pythonVersion';
import { createVirtualEnvironment } from '../pythonEnvironments/creation/createEnvApi';
import { traceError, traceVerbose, traceWarn } from '../logging';
import { StopWatch } from '../common/utils/stopWatch';
interface ICreateVirtualEnvToolParams extends IResourceReference {
packageList?: string[]; // Added only becausewe have ability to create a virtual env with list of packages same tool within the in Python Env extension.
}
export class CreateVirtualEnvTool implements LanguageModelTool<ICreateVirtualEnvToolParams> {
private readonly terminalExecutionService: TerminalCodeExecutionProvider;
private readonly terminalHelper: ITerminalHelper;
private readonly recommendedEnvService: IRecommendedEnvironmentService;
public static readonly toolName = 'create_virtual_environment';
constructor(
private readonly discoveryApi: IDiscoveryAPI,
private readonly api: PythonExtension['environments'],
private readonly serviceContainer: IServiceContainer,
) {
this.terminalExecutionService = this.serviceContainer.get<TerminalCodeExecutionProvider>(
ICodeExecutionService,
'standard',
);
this.terminalHelper = this.serviceContainer.get<ITerminalHelper>(ITerminalHelper);
this.recommendedEnvService = this.serviceContainer.get<IRecommendedEnvironmentService>(
IRecommendedEnvironmentService,
);
}
async invoke(
options: LanguageModelToolInvocationOptions<IResourceReference>,
token: CancellationToken,
): Promise<LanguageModelToolResult> {
const resource = resolveFilePath(options.input.resourcePath);
let info = await this.getPreferredEnvForCreation(resource);
if (!info) {
traceWarn(`Called ${CreateVirtualEnvTool.toolName} tool not invoked, no preferred environment found.`);
throw new CancellationError();
}
const { workspaceFolder, preferredGlobalPythonEnv } = info;
const interpreterPathService = this.serviceContainer.get<IInterpreterPathService>(IInterpreterPathService);
const disposables = new DisposableStore();
try {
const interpreterChanged = new Promise<void>((resolve) => {
disposables.add(interpreterPathService.onDidChange(() => resolve()));
});
const created = await raceCancellationError(
createVirtualEnvironment({
interpreter: preferredGlobalPythonEnv.id,
workspaceFolder,
}),
token,
);
if (!created?.path) {
traceWarn(`${CreateVirtualEnvTool.toolName} tool not invoked, virtual env not created.`);
throw new CancellationError();
}
// Wait a few secs to ensure the env is selected as the active environment..
// If this doesn't work, then something went wrong.
await raceTimeout(5_000, interpreterChanged);
const stopWatch = new StopWatch();
let env: ResolvedEnvironment | undefined;
while (stopWatch.elapsedTime < 5_000 || !env) {
env = await this.api.resolveEnvironment(created.path);
if (env) {
break;
} else {
traceVerbose(
`${CreateVirtualEnvTool.toolName} tool invoked, env created but not yet resolved, waiting...`,
);
await sleep(200);
}
}
if (!env) {
traceError(`${CreateVirtualEnvTool.toolName} tool invoked, env created but unable to resolve details.`);
throw new CancellationError();
}
return await getEnvDetailsForResponse(
env,
this.api,
this.terminalExecutionService,
this.terminalHelper,
resource,
token,
);
} catch (ex) {
if (!isCancellationError(ex)) {
traceError(
`${
CreateVirtualEnvTool.toolName
} tool failed to create virtual environment for resource ${resource?.toString()}`,
ex,
);
}
throw ex;
} finally {
disposables.dispose();
}
}
public async shouldCreateNewVirtualEnv(resource: Uri | undefined, token: CancellationToken): Promise<boolean> {
if (doesWorkspaceHaveVenvOrCondaEnv(resource, this.api)) {
// If we already have a .venv or .conda in this workspace, then do not prompt to create a virtual environment.
return false;
}
const info = await raceCancellationError(this.getPreferredEnvForCreation(resource), token);
return info ? true : false;
}
async prepareInvocation?(
options: LanguageModelToolInvocationPrepareOptions<IResourceReference>,
token: CancellationToken,
): Promise<PreparedToolInvocation> {
const resource = resolveFilePath(options.input.resourcePath);
const info = await raceCancellationError(this.getPreferredEnvForCreation(resource), token);
if (!info) {
return {};
}
const { preferredGlobalPythonEnv } = info;
const version = getDisplayVersion(preferredGlobalPythonEnv.version);
return {
confirmationMessages: {
title: l10n.t('Create a Virtual Environment{0}?', version ? ` (${version})` : ''),
message: l10n.t(`Virtual Environments provide the benefit of package isolation and more.`),
},
invocationMessage: l10n.t('Creating a Virtual Environment'),
};
}
async hasAlreadyGotAWorkspaceSpecificEnvironment(resource: Uri | undefined) {
const recommededEnv = await this.recommendedEnvService.getRecommededEnvironment(resource);
// Already selected workspace env, hence nothing to do.
if (recommededEnv?.reason === 'workspaceUserSelected' && workspace.workspaceFolders?.length) {
return recommededEnv.environment;
}
// No workspace folders, and the user selected a global environment.
if (recommededEnv?.reason === 'globalUserSelected' && !workspace.workspaceFolders?.length) {
return recommededEnv.environment;
}
}
private async getPreferredEnvForCreation(resource: Uri | undefined) {
if (await this.hasAlreadyGotAWorkspaceSpecificEnvironment(resource)) {
return undefined;
}
// If we have a resource or have only one workspace folder && there is no .venv and no workspace specific environment.
// Then lets recommend creating a virtual environment.
const workspaceFolder =
resource && workspace.workspaceFolders?.length
? workspace.getWorkspaceFolder(resource)
: workspace.workspaceFolders?.length === 1
? workspace.workspaceFolders[0]
: undefined;
if (!workspaceFolder) {
// No workspace folder, hence no need to create a virtual environment.
return undefined;
}
// Find the latest stable version of Python from the list of know envs.
let globalPythonEnvs = this.discoveryApi
.getEnvs()
.map((env) => convertEnvInfoToPythonEnvironment(env))
.filter((env) =>
[
EnvironmentType.System,
EnvironmentType.MicrosoftStore,
EnvironmentType.Global,
EnvironmentType.Pyenv,
].includes(env.envType),
)
.filter((env) => env.version && isStableVersion(env.version));
globalPythonEnvs = sortInterpreters(globalPythonEnvs);
const preferredGlobalPythonEnv = globalPythonEnvs.length
? this.api.known.find((e) => e.id === globalPythonEnvs[globalPythonEnvs.length - 1].id)
: undefined;
return workspaceFolder && preferredGlobalPythonEnv
? {
workspaceFolder,
preferredGlobalPythonEnv,
}
: undefined;
}
}