Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 25 additions & 18 deletions src/managers/builtin/venvManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { NativePythonFinder } from '../common/nativePythonFinder';
import { getLatest, shortVersion, sortEnvironments } from '../common/utils';
import {
clearVenvCache,
CreateEnvironmentResult,
createPythonVenv,
findVirtualEnvironments,
getDefaultGlobalVenvLocation,
Expand Down Expand Up @@ -140,39 +141,45 @@ export class VenvManager implements EnvironmentManager {
const venvRoot: Uri = Uri.file(await findParentIfFile(uri.fsPath));

const globals = await this.baseManager.getEnvironments('global');
let environment: PythonEnvironment | undefined = undefined;
let result: CreateEnvironmentResult | undefined = undefined;
if (options?.quickCreate) {
if (this.globalEnv && this.globalEnv.version.startsWith('3.')) {
environment = await quickCreateVenv(
this.nativeFinder,
this.api,
this.log,
this,
this.globalEnv,
venvRoot,
options?.additionalPackages,
);
} else if (!this.globalEnv) {
// error on missing information
if (!this.globalEnv) {
this.log.error('No base python found');
showErrorMessage(VenvManagerStrings.venvErrorNoBasePython);
throw new Error('No base python found');
} else if (!this.globalEnv.version.startsWith('3.')) {
}
if (!this.globalEnv.version.startsWith('3.')) {
this.log.error('Did not find any base python 3.*');
globals.forEach((e, i) => {
this.log.error(`${i}: ${e.version} : ${e.environmentPath.fsPath}`);
});
showErrorMessage(VenvManagerStrings.venvErrorNoPython3);
throw new Error('Did not find any base python 3.*');
}
if (this.globalEnv && this.globalEnv.version.startsWith('3.')) {
// quick create given correct information
result = await quickCreateVenv(
this.nativeFinder,
this.api,
this.log,
this,
this.globalEnv,
venvRoot,
options?.additionalPackages,
);
}
} else {
environment = await createPythonVenv(this.nativeFinder, this.api, this.log, this, globals, venvRoot, {
// If quickCreate is not set that means the user triggered this method from
// environment manager View, by selecting the venv manager.
// If quickCreate is not set that means the user triggered this method from
// environment manager View, by selecting the venv manager.
result = await createPythonVenv(this.nativeFinder, this.api, this.log, this, globals, venvRoot, {
showQuickAndCustomOptions: options?.quickCreate === undefined,
});
}

if (environment) {
if (result?.environment) {
const environment = result.environment;

this.addEnvironment(environment, true);

// Add .gitignore to the .venv folder
Expand Down Expand Up @@ -201,7 +208,7 @@ export class VenvManager implements EnvironmentManager {
);
}
}
return environment;
return result?.environment ?? undefined;
} finally {
this.skipWatcherRefresh = false;
}
Expand Down
62 changes: 48 additions & 14 deletions src/managers/builtin/venvUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,26 @@ import { resolveSystemPythonEnvironmentPath } from './utils';
export const VENV_WORKSPACE_KEY = `${ENVS_EXTENSION_ID}:venv:WORKSPACE_SELECTED`;
export const VENV_GLOBAL_KEY = `${ENVS_EXTENSION_ID}:venv:GLOBAL_SELECTED`;

/**
* Result of environment creation operation.
*/
export interface CreateEnvironmentResult {
/**
* The created environment, if successful.
*/
environment?: PythonEnvironment;

/*
* Exists if error occurred during environment creation and includes error explanation.
*/
envCreationErr?: string;

/*
* Exists if error occurred while installing packages and includes error description.
*/
pkgInstallationErr?: string;
}

export async function clearVenvCache(): Promise<void> {
const keys = [VENV_WORKSPACE_KEY, VENV_GLOBAL_KEY];
const state = await getWorkspacePersistentState();
Expand Down Expand Up @@ -281,7 +301,7 @@ async function createWithProgress(
venvRoot: Uri,
envPath: string,
packages?: PipPackages,
) {
): Promise<CreateEnvironmentResult | undefined> {
const pythonPath =
os.platform() === 'win32' ? path.join(envPath, 'Scripts', 'python.exe') : path.join(envPath, 'bin', 'python');

Expand All @@ -295,8 +315,10 @@ async function createWithProgress(
),
},
async () => {
const result: CreateEnvironmentResult = {};
try {
const useUv = await isUvInstalled(log);
// env creation
if (basePython.execInfo?.run.executable) {
if (useUv) {
await runUV(
Expand All @@ -313,26 +335,33 @@ async function createWithProgress(
);
}
if (!(await fsapi.pathExists(pythonPath))) {
log.error('no python executable found in virtual environment');
throw new Error('no python executable found in virtual environment');
}
}

// handle admin of new env
const resolved = await nativeFinder.resolve(pythonPath);
const env = api.createPythonEnvironmentItem(await getPythonInfo(resolved), manager);

// install packages
if (packages && (packages.install.length > 0 || packages.uninstall.length > 0)) {
await api.managePackages(env, {
upgrade: false,
install: packages?.install,
uninstall: packages?.uninstall ?? [],
});
try {
await api.managePackages(env, {
upgrade: false,
install: packages?.install,
uninstall: packages?.uninstall ?? [],
});
} catch (e) {
// error occurred while installing packages
result.pkgInstallationErr = e instanceof Error ? e.message : String(e);
}
}
return env;
result.environment = env;
} catch (e) {
log.error(`Failed to create virtual environment: ${e}`);
showErrorMessage(VenvManagerStrings.venvCreateFailed);
return;
result.envCreationErr = `Failed to create virtual environment: ${e}`;
}
return result;
},
);
}
Expand Down Expand Up @@ -365,7 +394,7 @@ export async function quickCreateVenv(
baseEnv: PythonEnvironment,
venvRoot: Uri,
additionalPackages?: string[],
): Promise<PythonEnvironment | undefined> {
): Promise<CreateEnvironmentResult | undefined> {
const project = api.getPythonProject(venvRoot);

sendTelemetryEvent(EventNames.VENV_CREATION, undefined, { creationType: 'quick' });
Expand All @@ -387,6 +416,7 @@ export async function quickCreateVenv(
venvPath = `${venvPath}-${i}`;
}

// createWithProgress handles building CreateEnvironmentResult and adding err msgs
return await createWithProgress(nativeFinder, api, log, manager, baseEnv, venvRoot, venvPath, {
install: allPackages,
uninstall: [],
Expand All @@ -401,7 +431,7 @@ export async function createPythonVenv(
basePythons: PythonEnvironment[],
venvRoot: Uri,
options: { showQuickAndCustomOptions: boolean; additionalPackages?: string[] },
): Promise<PythonEnvironment | undefined> {
): Promise<CreateEnvironmentResult | undefined> {
const sortedEnvs = ensureGlobalEnv(basePythons, log);

let customize: boolean | undefined = true;
Expand All @@ -421,7 +451,9 @@ export async function createPythonVenv(
const basePython = await pickEnvironmentFrom(sortedEnvs);
if (!basePython || !basePython.execInfo) {
log.error('No base python selected, cannot create virtual environment.');
return;
return {
envCreationErr: 'No base python selected, cannot create virtual environment.',
};
}

const name = await showInputBox({
Expand All @@ -439,7 +471,9 @@ export async function createPythonVenv(
});
if (!name) {
log.error('No name entered, cannot create virtual environment.');
return;
return {
envCreationErr: 'No name entered, cannot create virtual environment.',
};
}

const envPath = path.join(venvRoot.fsPath, name);
Expand Down