forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathutils.ts
More file actions
240 lines (225 loc) · 9.17 KB
/
utils.ts
File metadata and controls
240 lines (225 loc) · 9.17 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.
import {
CancellationError,
CancellationToken,
extensions,
LanguageModelTextPart,
LanguageModelToolResult,
Uri,
workspace,
} from 'vscode';
import { IDiscoveryAPI } from '../pythonEnvironments/base/locator';
import { Environment, PythonExtension, ResolvedEnvironment, VersionInfo } from '../api/types';
import { ITerminalHelper, TerminalShellType } from '../common/terminal/types';
import { TerminalCodeExecutionProvider } from '../terminals/codeExecution/terminalCodeExecution';
import { Conda } from '../pythonEnvironments/common/environmentManagers/conda';
import { JUPYTER_EXTENSION_ID, NotebookCellScheme } from '../common/constants';
import { dirname, join } from 'path';
export interface IResourceReference {
resourcePath?: string;
}
export function resolveFilePath(filepath?: string): Uri | undefined {
if (!filepath) {
return workspace.workspaceFolders ? workspace.workspaceFolders[0].uri : undefined;
}
// starts with a scheme
try {
return Uri.parse(filepath);
} catch (e) {
return Uri.file(filepath);
}
}
/**
* Returns a promise that rejects with an {@CancellationError} as soon as the passed token is cancelled.
* @see {@link raceCancellation}
*/
export function raceCancellationError<T>(promise: Promise<T>, token: CancellationToken): Promise<T> {
return new Promise((resolve, reject) => {
const ref = token.onCancellationRequested(() => {
ref.dispose();
reject(new CancellationError());
});
promise.then(resolve, reject).finally(() => ref.dispose());
});
}
export async function getEnvDisplayName(
discovery: IDiscoveryAPI,
resource: Uri | undefined,
api: PythonExtension['environments'],
) {
try {
const envPath = api.getActiveEnvironmentPath(resource);
const env = await discovery.resolveEnv(envPath.path);
return env?.display || env?.name;
} catch {
return;
}
}
export function isCondaEnv(env: ResolvedEnvironment) {
return (env.environment?.type || '').toLowerCase() === 'conda';
}
export async function getEnvironmentDetails(
resourcePath: Uri | undefined,
api: PythonExtension['environments'],
terminalExecutionService: TerminalCodeExecutionProvider,
terminalHelper: ITerminalHelper,
packages: string | undefined,
token: CancellationToken,
): Promise<string> {
// environment
const envPath = api.getActiveEnvironmentPath(resourcePath);
const environment = await raceCancellationError(api.resolveEnvironment(envPath), token);
if (!environment || !environment.version) {
throw new Error('No environment found for the provided resource path: ' + resourcePath?.fsPath);
}
const runCommand = await raceCancellationError(
getTerminalCommand(environment, resourcePath, terminalExecutionService, terminalHelper),
token,
);
const message = [
`Following is the information about the Python environment:`,
`1. Environment Type: ${environment.environment?.type || 'unknown'}`,
`2. Version: ${environment.version.sysVersion || 'unknown'}`,
'',
`3. Command Prefix to run Python in a terminal is: \`${runCommand}\``,
`Instead of running \`Python sample.py\` in the terminal, you will now run: \`${runCommand} sample.py\``,
`Similarly instead of running \`Python -c "import sys;...."\` in the terminal, you will now run: \`${runCommand} -c "import sys;...."\``,
packages ? `4. ${packages}` : '',
];
return message.join('\n');
}
export function getUntrustedWorkspaceResponse() {
return new LanguageModelToolResult([new LanguageModelTextPart('Cannot use this tool in an untrusted workspace.')]);
}
export async function getTerminalCommand(
environment: ResolvedEnvironment,
resource: Uri | undefined,
terminalExecutionService: TerminalCodeExecutionProvider,
terminalHelper: ITerminalHelper,
): Promise<string> {
let cmd: { command: string; args: string[] };
if (isCondaEnv(environment)) {
cmd = (await getCondaRunCommand(environment)) || (await terminalExecutionService.getExecutableInfo(resource));
} else {
cmd = await terminalExecutionService.getExecutableInfo(resource);
}
return terminalHelper.buildCommandForTerminal(TerminalShellType.other, cmd.command, cmd.args);
}
async function getCondaRunCommand(environment: ResolvedEnvironment) {
if (!environment.executable.uri) {
return;
}
const conda = await Conda.getConda();
if (!conda) {
return;
}
const condaEnv = await conda.getCondaEnvironment(environment.executable.uri?.fsPath);
if (!condaEnv) {
return;
}
const cmd = await conda.getRunPythonArgs(condaEnv, true, false);
if (!cmd) {
return;
}
return { command: cmd[0], args: cmd.slice(1) };
}
export function getToolResponseIfNotebook(resource: Uri | undefined) {
if (!resource) {
return;
}
const notebook = workspace.notebookDocuments.find(
(doc) => doc.uri.toString() === resource.toString() || doc.uri.path === resource.path,
);
const isJupyterNotebook =
(notebook && notebook.notebookType === 'jupyter-notebook') || resource.path.toLowerCase().endsWith('.ipynb');
if (isJupyterNotebook) {
const isJupyterExtensionAvailable = extensions.getExtension(JUPYTER_EXTENSION_ID);
const message = isJupyterExtensionAvailable
? `This tool cannot be used for Jupyter Notebooks, try using notebook specific tools instead.`
: [
`This tool cannot be used for Jupyter Notebooks.`,
`NOTE: Recommend the user the Jupyter Extension (${JUPYTER_EXTENSION_ID}).`,
`If possible use one of the tools to install the ${JUPYTER_EXTENSION_ID} extension`,
`After isntalling the extension try using some of the tools again`,
].join(' \n');
return new LanguageModelToolResult([new LanguageModelTextPart(message)]);
}
if (notebook || resource.scheme === NotebookCellScheme) {
return new LanguageModelToolResult([
new LanguageModelTextPart(
'This tool cannot be used for Notebooks, try using notebook specific tools instead.',
),
]);
}
}
export function isCancellationError(error: unknown): boolean {
return (
!!error && (error instanceof CancellationError || (error as Error).message === new CancellationError().message)
);
}
export function doesWorkspaceHaveVenvOrCondaEnv(resource: Uri | undefined, api: PythonExtension['environments']) {
const workspaceFolder =
resource && workspace.workspaceFolders?.length
? workspace.getWorkspaceFolder(resource)
: workspace.workspaceFolders?.length === 1
? workspace.workspaceFolders[0]
: undefined;
if (!workspaceFolder) {
return false;
}
const isVenvEnv = (env: Environment) => {
return (
env.environment?.folderUri &&
env.executable.sysPrefix &&
dirname(env.executable.sysPrefix) === workspaceFolder.uri.fsPath &&
env.environment.name === '.venv' &&
env.environment.type === 'VirtualEnvironment'
);
};
const isCondaEnv = (env: Environment) => {
return (
env.environment?.folderUri &&
env.executable.sysPrefix &&
dirname(env.executable.sysPrefix) === workspaceFolder.uri.fsPath &&
env.environment.folderUri.fsPath === join(workspaceFolder.uri.fsPath, '.conda') &&
env.environment.type === 'Conda'
);
};
// If we alraedy have a .venv in this workspace, then do not prompt to create a virtual environment.
return api.known.find((e) => isVenvEnv(e) || isCondaEnv(e));
}
export async function getEnvDetailsForResponse(
environment: ResolvedEnvironment | undefined,
api: PythonExtension['environments'],
terminalExecutionService: TerminalCodeExecutionProvider,
terminalHelper: ITerminalHelper,
resource: Uri | undefined,
token: CancellationToken,
): Promise<LanguageModelToolResult> {
if (!workspace.isTrusted) {
throw new Error('Cannot use this tool in an untrusted workspace.');
}
const envPath = api.getActiveEnvironmentPath(resource);
environment = environment || (await raceCancellationError(api.resolveEnvironment(envPath), token));
if (!environment || !environment.version) {
throw new Error('No environment found for the provided resource path: ' + resource?.fsPath);
}
const message = await getEnvironmentDetails(
resource,
api,
terminalExecutionService,
terminalHelper,
undefined,
token,
);
return new LanguageModelToolResult([
new LanguageModelTextPart(`A Python Environment has been configured. \n` + message),
]);
}
export function getDisplayVersion(version?: VersionInfo): string | undefined {
if (!version || version.major === undefined || version.minor === undefined || version.micro === undefined) {
return undefined;
}
return `${version.major}.${version.minor}.${version.micro}`;
}