Skip to content

Commit 7ea97a3

Browse files
edvilmeCopilotCopilot
authored
Add project-scoped package managers (#1816)
Fixes #1779 ## Summary Adds project-scoped package manager instances for package managers whose behavior depends on the active Python project. Instead of threading project context through every package operation, a provider can implement `PackageManager.createForProject(project)` and return a manager bound to that project. ## Changes - Add the optional `PackageManager.createForProject(project)` API. - Cache project-bound manager instances by provider and normalized project path while keeping project-independent managers shared. - Preserve the registered provider ID for scoped managers and allow scoped managers to create package items. - Forward package-change events from root and scoped managers through the internal and public APIs. - Keep package watchers distinct by provider, environment, and project. - Retain the scoped manager for package actions initiated from the project view. - Bind Poetry package operations to an immutable `PythonProject`: - `add`, `remove`, `show`, and `show --top-level` run from the project directory. - `manage` and `refresh` reject when Poetry is not project-bound. - `getPackages` and `getDirectPackageNames` return `undefined` when Poetry is not project-bound. - Project-independent operations such as `getVersion` and `formatInstallSpec` remain available. - Update the API package metadata, changelog, and documentation. ## Validation - `npm run lint` - `npm run compile-tests` - `npm run unittest` — 2,425 passing, 6 pending --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent f0648b9 commit 7ea97a3

26 files changed

Lines changed: 1604 additions & 156 deletions

‎.github/instructions/testing-workflow.instructions.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ This guide covers the full testing lifecycle:
1919
## Learnings
2020

2121
- Pip commands that return JSON must pass `--disable-pip-version-check`; the process helper combines stderr with stdout, so update notices can otherwise make valid JSON unparseable (1).
22+
- When a view subscribes to a newly added provider event, TypeMoq-based view tests must return a real `EventEmitter.event`; an unstubbed event yields an undefined disposable and fails during teardown (1).
2223

2324
### When to Use This Guide
2425

‎api/CHANGELOG.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@ All notable changes to the `@vscode/python-environments` API package are documen
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [1.5.0]
9+
10+
### Added
11+
12+
- Added the optional `PackageManager.createForProject` factory for package managers whose operations depend on the calling Python project. Explicit project contexts are used directly; environment-only operations use a scoped manager only when exactly one tracked project matches.
13+
- Added optional `PackageManager.dispose` support for releasing resources owned by project-scoped package managers.
14+
15+
### Changed
16+
17+
- Environment-only package operations no longer fall back to an unbound project-aware package manager. When no unique project can be inferred, package reads return `undefined` and mutations and refreshes reject with `No package manager found`.
18+
819
## [1.4.0]
920

1021
### Changed

‎api/package-lock.json‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎api/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@vscode/python-environments",
33
"description": "An API facade for the Python Environments extension in VS Code",
4-
"version": "1.4.0",
4+
"version": "1.5.0",
55
"author": {
66
"name": "Microsoft Corporation"
77
},

‎docs/README.md‎

Lines changed: 58 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -793,7 +793,8 @@ getPackages(
793793

794794
**Returns** `Promise<Package[] | undefined>`. `undefined` means the manager
795795
could not produce a list - for example no package manager is associated with
796-
the environment - which is different from an empty array meaning "nothing
796+
the environment, or a project-aware manager cannot identify one unique project
797+
for the environment - which is different from an empty array meaning "nothing
797798
installed".
798799

799800
```typescript
@@ -818,7 +819,10 @@ refreshPackages(environment: PythonEnvironment): Promise<void>;
818819
| `environment` | [`PythonEnvironment`](#pythonenvironment) | Yes | The environment whose package list should be refreshed. |
819820

820821
**Returns** `Promise<void>`. Changes surface through
821-
[`onDidChangePackages`](#ondidchangepackages).
822+
[`onDidChangePackages`](#ondidchangepackages). Rejects with
823+
`No package manager found` when no package manager can be resolved for the
824+
environment - including when a project-aware manager cannot identify one unique
825+
project.
822826

823827
```typescript
824828
// Packages were installed outside the extension - re-read the list.
@@ -842,8 +846,10 @@ managePackages(
842846
| `environment` | [`PythonEnvironment`](#pythonenvironment) | Yes | The environment to modify. |
843847
| `options` | [`PackageManagementOptions`](#packagemanagementoptions) | Yes | Must specify `install`, `uninstall`, or both. Also carries `upgrade`, `showSkipOption`, and `runHeadless`. |
844848

845-
**Returns** `Promise<void>`, resolving when the operation finishes. Rejects if
846-
the underlying tool fails.
849+
**Returns** `Promise<void>`, resolving when the operation finishes. Rejects with
850+
`No package manager found` when no package manager can be resolved for the
851+
environment - including when a project-aware manager cannot identify one unique
852+
project - or if the underlying tool fails.
847853

848854
```typescript
849855
await api.managePackages(env, {
@@ -1613,13 +1619,61 @@ Reports and changes the packages of an environment.
16131619
| `refresh(environment)` | `(environment: PythonEnvironment) => Promise<void>` | Yes | Re-reads the installed package list. |
16141620
| `getPackages(environment, options?)` | `(environment: PythonEnvironment, options?: GetPackagesOptions) => Promise<Package[] \| undefined>` | Yes | Returns installed packages, or `undefined` if they cannot be retrieved. |
16151621
| `getPackageWatchTargets(environment)` | `(environment: PythonEnvironment) => RelativePattern[]` | No | Extra filesystem patterns to watch for install and uninstall changes, appended to the default site-packages locations. Implement for manager-specific locations such as `conda-meta`. |
1622+
| `createForProject(project)` | `(project: PythonProject) => PackageManager` | No | Creates a manager bound to a project for project-sensitive operations. |
1623+
| `dispose()` | `() => void` | No | Releases resources owned by the manager. The extension disposes project-scoped managers when their project is removed or replaced, their provider is unregistered, or the extension shuts down. |
16161624
| `getDirectPackageNames(environment)` | `(environment: PythonEnvironment) => Promise<Set<string> \| undefined>` | No | Best-effort set of non-transitive package names. Most tools cannot record user intent - pip uses `pip list --not-required`, which reports leaf packages rather than explicitly installed ones. |
16171625
| `clearCache()` | `() => Promise<void>` | No | Drops cached package data. |
16181626
| `getVersion(environment)` | `(environment: PythonEnvironment) => Promise<Pep440Version \| undefined>` | No | Version of the underlying tool, such as pip, uv, or conda. |
16191627
| `getPackageAvailableVersions(environment, packageName)` | `(environment: PythonEnvironment, packageName: string) => Promise<Pep440Version[] \| undefined>` | No | Available versions, newest first. Throw `PackageVersionLookupNotSupportedError` when unsupported and let operational failures propagate. Resolving to `undefined` is treated as unsupported. |
16201628
| `formatInstallSpec(packageName, version)` | `(packageName: string, version: string) => string` | No | Formats a pinned specifier for this tool, for example `requests==2.31.0` for pip or `requests=2.31.0` for conda. Callers default to `name==version` when absent. |
16211629
| `onDidChangePackages` | `Event<DidChangePackagesEventArgs>` | No | Fire when packages change. |
16221630

1631+
##### Project-scoped package managers
1632+
1633+
Implement `createForProject` when package operations depend on project files or
1634+
the process working directory, as they do for tools such as Poetry. Callers that
1635+
already have a `PythonProject` use that project directly. For environment-only
1636+
operations, the extension selects a project-scoped manager only when exactly one
1637+
tracked project uses the environment; it does not choose arbitrarily when no
1638+
project or multiple projects match.
1639+
1640+
Environment-only paths never use a project-aware provider as an unbound
1641+
fallback. When no unique project can be inferred, `getPackageManager` returns no
1642+
manager, so package reads return `undefined`, package views suppress those
1643+
operations, and package mutations or refreshes reject with `No package manager
1644+
found`. Keep project-specific caches and mutable state on the manager returned by
1645+
`createForProject`, and implement `dispose` when that manager owns resources.
1646+
1647+
When a scoped manager fires `onDidChangePackages`, the event's `manager` must be
1648+
the exact scoped instance returned by `createForProject`. This requirement also
1649+
applies when root and scoped managers share an event emitter.
1650+
1651+
```typescript
1652+
class ProjectPackageManager implements PackageManager {
1653+
readonly name = 'project-pm';
1654+
1655+
constructor(private readonly project?: PythonProject) {}
1656+
1657+
createForProject(project: PythonProject): PackageManager {
1658+
return new ProjectPackageManager(project);
1659+
}
1660+
1661+
dispose(): void {
1662+
// Release project-specific watchers or processes.
1663+
}
1664+
1665+
async manage(
1666+
environment: PythonEnvironment,
1667+
options: PackageManagementOptions,
1668+
): Promise<void> {
1669+
if (!this.project) {
1670+
throw new Error('Package management requires a Python project.');
1671+
}
1672+
await runPackageCommand(options, { cwd: this.project.uri.fsPath });
1673+
}
1674+
}
1675+
```
1676+
16231677
```typescript
16241678
class MyPackageManager implements PackageManager {
16251679
readonly name = 'my-pm';

‎src/extension.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -367,16 +367,16 @@ export async function activate(context: ExtensionContext): Promise<PythonEnviron
367367
return;
368368
}
369369
try {
370-
resolved.packageManager.manage(resolved.environment, { install: [] });
370+
await resolved.packageManager.manage(resolved.environment, { install: [] });
371371
} catch (err) {
372372
traceError('Error when running command python-envs.packages', err);
373373
}
374374
}),
375375
commands.registerCommand('python-envs.uninstallPackage', async (context: unknown) => {
376-
await handlePackageUninstall(context, envManagers);
376+
await handlePackageUninstall(context);
377377
}),
378378
commands.registerCommand('python-envs.managePackageVersion', async (context: unknown) => {
379-
await managePackageVersion(context, envManagers);
379+
await managePackageVersion(context);
380380
}),
381381
commands.registerCommand('python-envs.set', async (item) => {
382382
await setEnvironmentCommand(item, envManagers, projectManager);

‎src/extensionApi.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ export class PythonEnvironmentApiImpl implements PythonEnvironmentApi {
8686
this._onDidChangePythonProjects,
8787
this._onDidChangePackages,
8888
this._onDidChangeEnvironmentVariables,
89+
this.envManagers.onDidChangePackageProviderPackages((e) => this._onDidChangePackages.fire(e)),
8990
this.envManagers.onDidChangeActiveEnvironment((e) => {
9091
this._onDidChangeEnvironment.fire(e);
9192
const location = e.uri?.fsPath ?? 'global';
@@ -295,12 +296,7 @@ export class PythonEnvironmentApiImpl implements PythonEnvironmentApi {
295296
}
296297

297298
registerPackageManager(manager: PackageManager, options?: { extensionId?: string }): Disposable {
298-
const disposables: Disposable[] = [];
299-
disposables.push(this.envManagers.registerPackageManager(manager, options));
300-
if (manager.onDidChangePackages) {
301-
disposables.push(manager.onDidChangePackages((e) => this._onDidChangePackages.fire(e)));
302-
}
303-
return new Disposable(() => disposables.forEach((d) => d.dispose()));
299+
return this.envManagers.registerPackageManager(manager, options);
304300
}
305301
async managePackages(context: PythonEnvironment, options: PackageManagementOptions): Promise<void> {
306302
await waitForEnvManagerId([context.envId.managerId]);

‎src/features/envCommands.ts‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,7 @@ export async function refreshPackagesCommand(context: unknown, managers?: Enviro
144144
}
145145
} else if (context instanceof PythonEnvTreeItem) {
146146
const view = context as PythonEnvTreeItem;
147-
const envManager =
148-
view.parent.kind === EnvTreeItemKind.environmentGroup ? view.parent.parent.manager : view.parent.manager;
149-
const pkgManager = managers?.getPackageManager(envManager.preferredPackageManagerId);
147+
const pkgManager = managers?.getPackageManager(view.environment);
150148
if (pkgManager) {
151149
await pkgManager.refresh(view.environment);
152150
}
@@ -325,7 +323,7 @@ export async function removeEnvironmentCommand(context: unknown, managers: Envir
325323
}
326324
}
327325

328-
export async function handlePackageUninstall(context: unknown, em: EnvironmentManagers) {
326+
export async function handlePackageUninstall(context: unknown) {
329327
if (context instanceof PackageTreeItem || context instanceof ProjectPackage) {
330328
if (context.pkg.isTransitive) {
331329
const confirm = await showInformationMessage(
@@ -343,8 +341,7 @@ export async function handlePackageUninstall(context: unknown, em: EnvironmentMa
343341
}
344342
const moduleName = context.pkg.name;
345343
const environment = context.parent.environment;
346-
const packageManager = em.getPackageManager(environment);
347-
await packageManager?.manage(environment, { uninstall: [moduleName], install: [] });
344+
await context.manager.manage(environment, { uninstall: [moduleName], install: [] });
348345
return;
349346
}
350347
traceError(`Invalid context for uninstall command: ${typeof context}`);
@@ -354,15 +351,11 @@ export async function handlePackageUninstall(context: unknown, em: EnvironmentMa
354351
* Manages package versions by allowing the user to select from available versions or enter a specific version.
355352
* If available versions can be fetched, a QuickPick is shown. Otherwise, an InputBox is used for free-text version entry.
356353
*/
357-
export async function managePackageVersion(context: unknown, em: EnvironmentManagers) {
354+
export async function managePackageVersion(context: unknown) {
358355
if (context instanceof PackageTreeItem || context instanceof ProjectPackage) {
359356
const pkg = context.pkg;
360357
const environment = context.parent.environment;
361-
const packageManager = em.getPackageManager(environment);
362-
363-
if (!packageManager) {
364-
return;
365-
}
358+
const packageManager = context.manager;
366359

367360
if (pkg.isTransitive) {
368361
const confirm = await showInformationMessage(

0 commit comments

Comments
 (0)