Skip to content
Open
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
24 changes: 24 additions & 0 deletions src/managers/builtin/builtInEnvironmentManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ import {
setVenvForWorkspaces,
} from './venvUtils';

/**
* Discovery creates new environment items with random ids on every refresh, so compare what
* identifies the interpreter instead.
*/
function isSameInterpreter(a: PythonEnvironment | undefined, b: PythonEnvironment): boolean {
return (
a?.envId.managerId === b.envId.managerId &&
normalizePath(a.environmentPath.fsPath) === normalizePath(b.environmentPath.fsPath) &&
a.version === b.version
);
}

export class BuiltInEnvironmentManager implements EnvironmentManager {
readonly capabilities: Capabilities<EnvironmentManagerCapability> = {
[EnvironmentCapability.List]: supportedCapability,
Expand Down Expand Up @@ -820,8 +832,10 @@ export class BuiltInEnvironmentManager implements EnvironmentManager {
const globals = await (toolExecution && tools?.getEnvironments
? tools.getEnvironments('global')
: this.baseManager.getEnvironments('global'));
const previousGlobalEnv = this.globalEnv;
await this.loadGlobalEnv(globals);

const previousProjectEnvs = new Map(this.fsPathToEnv);
this.fsPathToEnv.forEach((_env, key) => {
if (isCurrent(key)) {
this.fsPathToEnv.delete(key);
Expand Down Expand Up @@ -890,6 +904,16 @@ export class BuiltInEnvironmentManager implements EnvironmentManager {
) ?? projectEnvs[0];
if (found) {
this.fsPathToEnv.set(normalizedPath, found);
// A venv created in the project after the last refresh replaces the global fallback
// that get() returned so far, so consumers have to be notified.
const previousEnv = previousProjectEnvs.get(normalizedPath) ?? previousGlobalEnv;
if (!isSameInterpreter(previousEnv, found)) {
events.push(() => {
if (isCurrent(normalizedPath)) {
this._onDidChangeEnvironment.fire({ uri: project.uri, old: previousEnv, new: found });
}
});
}
}
}
}
Expand Down
81 changes: 75 additions & 6 deletions src/test/managers/builtin/venvManager.autoSelect.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@ import assert from 'assert';
import * as path from 'path';
import * as sinon from 'sinon';
import { LogOutputChannel, Uri } from 'vscode';
import { EnvironmentManager, PythonEnvironment, PythonEnvironmentApi, PythonProject } from '../../../api';
import { VENV_MANAGER_ID } from '../../../common/constants';
import {
DidChangeEnvironmentEventArgs,
EnvironmentManager,
PythonEnvironment,
PythonEnvironmentApi,
PythonProject,
} from '../../../api';
import { SYSTEM_MANAGER_ID, VENV_MANAGER_ID } from '../../../common/constants';
import { normalizePath } from '../../../common/utils/pathUtils';
import * as windowApis from '../../../common/window.apis';
import { BuiltInEnvironmentManager } from '../../../managers/builtin/builtInEnvironmentManager';
Expand All @@ -24,9 +30,9 @@ suite('VenvManager auto-selection for a project', () => {
return Uri.file(path.join(projectUri.fsPath, ...segments, '.venv')).fsPath;
}

function makeVenv(prefix: string, version: string): PythonEnvironment {
function makeVenv(prefix: string, version: string, id = prefix): PythonEnvironment {
return createMockPythonEnvironment({
id: prefix,
id,
name: '.venv',
envPath: path.join(prefix, bin, 'python'),
sysPrefix: prefix,
Expand All @@ -35,7 +41,20 @@ suite('VenvManager auto-selection for a project', () => {
});
}

async function createManager(): Promise<BuiltInEnvironmentManager> {
function makeGlobal(prefix: string, version: string): PythonEnvironment {
return createMockPythonEnvironment({
id: prefix,
name: 'python',
envPath: path.join(prefix, 'python'),
sysPrefix: prefix,
version,
managerId: SYSTEM_MANAGER_ID,
});
}

async function createManager(
getGlobals: sinon.SinonStub = sinon.stub().resolves([]),
): Promise<BuiltInEnvironmentManager> {
const project = { name: 'project', uri: projectUri } as PythonProject;
const projectRoot = normalizePath(projectUri.fsPath);
const api = {
Expand All @@ -45,7 +64,7 @@ suite('VenvManager auto-selection for a project', () => {
},
getPythonProjects: () => [project],
} as unknown as PythonEnvironmentApi;
const baseManager = { getEnvironments: sinon.stub().resolves([]) } as unknown as EnvironmentManager;
const baseManager = { getEnvironments: getGlobals } as unknown as EnvironmentManager;
const log = { info: sinon.stub(), warn: sinon.stub(), error: sinon.stub() } as unknown as LogOutputChannel;
const manager = new BuiltInEnvironmentManager(
{} as NativePythonFinder,
Expand Down Expand Up @@ -102,4 +121,54 @@ suite('VenvManager auto-selection for a project', () => {

assert.strictEqual((await manager.get(projectUri))?.envId.id, brokenRoot.envId.id);
});

test('fires onDidChangeEnvironment when a refresh finds a venv created in the project', async () => {
const rootVenv = makeVenv(venvIn(), '3.12.14');
const find = sinon.stub(venvUtils, 'findVirtualEnvironments').resolves([]);
const manager = await createManager();
const events: DidChangeEnvironmentEventArgs[] = [];
manager.onDidChangeEnvironment((e) => events.push(e));

find.resolves([rootVenv]);
await manager.refresh(undefined);

assert.strictEqual(events.length, 1);
assert.strictEqual(events[0].uri?.fsPath, projectUri.fsPath);
assert.strictEqual(events[0].new?.envId.id, rootVenv.envId.id);
assert.strictEqual((await manager.get(projectUri))?.envId.id, rootVenv.envId.id);
});

test('reports the global fallback from before the refresh as the old environment', async () => {
const oldGlobal = makeGlobal(path.resolve('python312'), '3.12.14');
const newGlobal = makeGlobal(path.resolve('python313'), '3.13.15');
const rootVenv = makeVenv(venvIn(), '3.12.14');
const getGlobals = sinon.stub().resolves([oldGlobal]);
const find = sinon.stub(venvUtils, 'findVirtualEnvironments').resolves([]);
const manager = await createManager(getGlobals);
const events: DidChangeEnvironmentEventArgs[] = [];
manager.onDidChangeEnvironment((e) => events.push(e));

getGlobals.resolves([oldGlobal, newGlobal]);
find.resolves([rootVenv]);
await manager.refresh(undefined);

assert.strictEqual(events.length, 1);
assert.strictEqual(events[0].old?.envId.id, oldGlobal.envId.id);
assert.strictEqual(events[0].new?.envId.id, rootVenv.envId.id);
});

test('does not fire onDidChangeEnvironment when a refresh finds the same venv again', async () => {
const find = sinon
.stub(venvUtils, 'findVirtualEnvironments')
.resolves([makeVenv(venvIn(), '3.12.14', 'first')]);
const manager = await createManager();
const events: DidChangeEnvironmentEventArgs[] = [];
manager.onDidChangeEnvironment((e) => events.push(e));

// Discovery creates a new item with a new id for the same interpreter.
find.resolves([makeVenv(venvIn(), '3.12.14', 'second')]);
await manager.refresh(undefined);

assert.strictEqual(events.length, 0);
});
});