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
7 changes: 7 additions & 0 deletions api/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ All notable changes to the `@vscode/python-environments` API package are documen
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.6.0]

### Added

- Added optional `CreateEnvironmentOptions.name` so API consumers can request a specific name when creating an environment.
- Added `EnvironmentManager.createCapabilities.customName` so managers explicitly advertise support for exact caller-supplied names. Named creation now rejects before invoking managers that do not support it.

## [1.5.0]

### Added
Expand Down
4 changes: 2 additions & 2 deletions api/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@vscode/python-environments",
"description": "An API facade for the Python Environments extension in VS Code",
"version": "1.5.0",
"version": "1.6.0",
"author": {
"name": "Microsoft Corporation"
},
Expand Down
14 changes: 9 additions & 5 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,11 +274,13 @@ applies to.

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `quickCreate` | `boolean` | No | `true` creates without any prompts. `false` means the user explicitly declined quick create, so prompts are allowed. `undefined` leaves the decision to the manager, which may offer quick create. |
| `additionalPackages` | `string[]` | No | Packages to install in addition to whatever the manager installs by default. |
| `name` | `string` | `false` | Portable path segment to use as the new environment's name. Directory separators, control characters, Windows-reserved filename characters (such as `:` and `?`) and device names (such as `CON` and `NUL`), trailing periods or spaces, `.` and `..` are rejected. The selected manager must advertise `createCapabilities.customName`; otherwise creation rejects. When omitted, the manager may prompt for a name or choose a default. |
| `quickCreate` | `boolean` | `false` | `true` creates without any prompts. `false` means the user explicitly declined quick create, so prompts are allowed. `undefined` leaves the decision to the manager, which may offer quick create. |
| `additionalPackages` | `string[]` | `false` | Packages to install in addition to whatever the manager installs by default. |

```typescript
const env = await api.createEnvironment(projectUri, {
name: 'analysis-env',
quickCreate: true,
additionalPackages: ['requests', 'pytest'],
});
Expand Down Expand Up @@ -506,16 +508,17 @@ createEnvironment(
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `scope` | [`CreateEnvironmentScope`](#scope-types) | Yes | `Uri` or `Uri[]` for the projects the environment is created for; `'global'` creates one outside any project. |
| `options` | [`CreateEnvironmentOptions`](#createenvironmentoptions) | No | Controls prompting (`quickCreate`) and extra packages (`additionalPackages`). |
| `options` | [`CreateEnvironmentOptions`](#createenvironmentoptions) | No | Controls the environment name (`name`), prompting (`quickCreate`), and extra packages (`additionalPackages`). |

**Returns** `Promise<PythonEnvironment | undefined>` - `undefined` when no
environment was created, for example because the user cancelled the flow.
Rejects when no environment manager is registered for the scope, when the
manager does not support creation, or when creation itself fails - so handle
errors as well as `undefined`.
manager does not support creation, when a supplied name is unsupported, or when
creation itself fails - so handle errors as well as `undefined`.

```typescript
const created = await api.createEnvironment(projectUri, {
name: 'analysis-env',
quickCreate: true,
additionalPackages: ['requests'],
});
Expand Down Expand Up @@ -1561,6 +1564,7 @@ trigger, as the specification.
| `set(scope, environment?)` | `(scope: SetEnvironmentScope, environment?: PythonEnvironment) => Promise<void>` | Yes | Sets or clears the active environment for the scope. Also called at startup to rehydrate persisted state. |
| `get(scope)` | `(scope: GetEnvironmentScope) => Promise<PythonEnvironment \| undefined>` | Yes | Returns the active environment for the scope. Called very frequently. |
| `resolve(context)` | `(context: ResolveEnvironmentContext) => Promise<PythonEnvironment \| undefined>` | Yes | Turns a `Uri` for an interpreter or environment folder into a fully populated environment with complete `execInfo`. |
| `createCapabilities` | `CreateEnvironmentCapabilities` | No | Declares optional creation behavior. Set `customName: true` only when `create` uses a supplied name exactly or rejects it. Omitted capabilities are unsupported. |
| `create(scope, options?)` | `(scope: CreateEnvironmentScope, options?: CreateEnvironmentOptions) => Promise<PythonEnvironment \| undefined>` | No | Creates an environment. Omit the method entirely if creation is unsupported - the UI disables create when `create === undefined`. Add a `.gitignore` when creating a folder inside the workspace. |
| `remove(environment, options?)` | `(environment: PythonEnvironment, options?: RemoveEnvironmentOptions) => Promise<void>` | No | Deletes an environment. |
| `quickCreateConfig()` | `() => QuickCreateConfig \| undefined` | No | Describes the quick create path. Implementing it enables quick create, which requires `create` too. |
Expand Down
26 changes: 24 additions & 2 deletions src/common/utils/pathUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,29 @@ export function isSameOrParentPath(parentPath: string, candidatePath: string): b
);
}

function matchesWindowsReservedDeviceName(value: string): boolean {
const deviceBaseName = value.split('.')[0];
return /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(deviceBaseName);
}

/**
* Determines whether `value` can be used as a path segment on all supported platforms.
*
* @param value The path segment to validate.
* @returns `true` when the value is valid on Windows, macOS, and Linux.
*/
export function isValidPortablePathSegment(value: string): boolean {
return (
value.length > 0 &&
value.trim().length > 0 &&
value !== '.' &&
value !== '..' &&
!/[<>:"/\\|?*\u0000-\u001f]/.test(value) &&
!/[. ]$/.test(value) &&
!matchesWindowsReservedDeviceName(value)
);
}

/**
* Determines whether `value` maps to a reserved Windows device name (e.g. `CON`,
* `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LPT9`).
Expand All @@ -99,8 +122,7 @@ export function isSameOrParentPath(parentPath: string, candidatePath: string): b
* @returns `true` on Windows when `value` resolves to a reserved device name.
*/
export function isWindowsReservedDeviceName(value: string): boolean {
const deviceBaseName = value.split('.')[0];
return isWindows() && /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(deviceBaseName);
return isWindows() && matchesWindowsReservedDeviceName(value);
}

export function getResourceUri(resourcePath: string, root?: string): Uri | undefined {
Expand Down
26 changes: 22 additions & 4 deletions src/extensionApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ import type {
ResolveEnvironmentContext,
SetEnvironmentScope,
} from './types';
import { PackageVersionLookupNotSupportedError } from './publicErrors';
import { CreateEnvironmentOptionNotSupportedError, PackageVersionLookupNotSupportedError } from './publicErrors';
import { INLINE_SCRIPT_MANAGER_ID } from './common/constants';
import { traceError, traceInfo } from './common/logging';
import { pickEnvironmentManager } from './common/pickers/managers';
import { timeout } from './common/utils/asyncUtils';
import { createDeferred } from './common/utils/deferred';
import { checkUri } from './common/utils/pathUtils';
import { checkUri, isValidPortablePathSegment } from './common/utils/pathUtils';
import { handlePythonPath } from './common/utils/pythonPath';
import type { EnvironmentManagers } from './features/envManagers';
import type { ProjectCreators } from './features/creators/projectCreators';
Expand Down Expand Up @@ -157,6 +157,9 @@ export class PythonEnvironmentApiImpl implements PythonEnvironmentApi {
scope: CreateEnvironmentScope,
options: CreateEnvironmentOptions | undefined,
): Promise<PythonEnvironment | undefined> {
if (options?.name !== undefined && !isValidPortablePathSegment(options.name)) {
throw new Error('Environment name must be a valid portable path segment');
}
if (scope === 'global' || (!Array.isArray(scope) && scope instanceof Uri)) {
await waitForEnvManager(scope === 'global' ? undefined : [scope]);
const manager = this.envManagers.getEnvironmentManager(scope === 'global' ? undefined : scope);
Expand All @@ -166,6 +169,12 @@ export class PythonEnvironmentApiImpl implements PythonEnvironmentApi {
if (!manager.supportsCreate) {
throw new Error(`Environment manager does not support creating environments: ${manager.id}`);
}
if (options?.name !== undefined && !manager.supportsCustomName) {
throw new CreateEnvironmentOptionNotSupportedError(
'name',
`Environment manager does not support named environment creation: ${manager.id}`,
);
}
return manager.create(scope, options);
} else if (Array.isArray(scope) && scope.length === 1 && scope[0] instanceof Uri) {
return this.createEnvironment(scope[0], options);
Expand All @@ -183,12 +192,21 @@ export class PythonEnvironmentApiImpl implements PythonEnvironmentApi {
throw new Error('No environment managers found');
}

const managerId = await pickEnvironmentManager(managers);
const compatibleManagers =
options?.name === undefined ? managers : managers.filter((manager) => manager.supportsCustomName);
if (compatibleManagers.length === 0) {
throw new CreateEnvironmentOptionNotSupportedError(
'name',
'None of the environment managers for the requested scopes support named environment creation.',
);
}

const managerId = await pickEnvironmentManager(compatibleManagers);
if (!managerId) {
throw new Error('No environment manager selected');
}

const manager = managers.find((m) => m.id === managerId);
const manager = compatibleManagers.find((m) => m.id === managerId);
if (!manager) {
throw new Error('No environment manager found');
}
Expand Down
12 changes: 7 additions & 5 deletions src/features/envCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,13 +209,15 @@ export async function createAnyEnvironmentCommand(
},
): Promise<PythonEnvironment | undefined> {
const select = options?.selectEnvironment;
const supportsRequestedCreation = (manager: InternalEnvironmentManager): boolean =>
manager.supportsCreate && (options?.name === undefined || manager.supportsCustomName);
const projects = pm.getProjects(options?.uri ? [options?.uri] : undefined);
if (projects.length === 0) {
const managerId = await pickEnvironmentManager(
em.managers.filter((m) => m.supportsCreate),
em.managers.filter(supportsRequestedCreation),
undefined,
undefined,
true, // showEnterInterpreterPath
options?.name === undefined,
);

// Handle "Enter Interpreter Path" selection
Expand Down Expand Up @@ -243,7 +245,7 @@ export async function createAnyEnvironmentCommand(

selected.forEach((p) => {
const manager = em.getEnvironmentManager(p.uri);
if (manager && manager.supportsCreate && !defaultManagers.includes(manager)) {
if (manager && supportsRequestedCreation(manager) && !defaultManagers.includes(manager)) {
defaultManagers.push(manager);
}
});
Expand All @@ -255,10 +257,10 @@ export async function createAnyEnvironmentCommand(
manager = defaultManagers[0];
} else {
let managerId = await pickEnvironmentManager(
em.managers.filter((m) => m.supportsCreate),
em.managers.filter(supportsRequestedCreation),
defaultManagers,
options?.showBackButton,
true, // showEnterInterpreterPath
options?.name === undefined,
);

// Handle "Enter Interpreter Path" selection
Expand Down
1 change: 1 addition & 0 deletions src/managers/builtin/inlineScript/envManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@ export class InlineScriptEnvManager implements EnvironmentManager, Disposable {
public readonly displayName = l10n.t('Inline scripts');
public readonly preferredPackageManagerId = 'ms-python.python:pip';
public readonly description: string | undefined = undefined;
public readonly createCapabilities = { customName: false } as const;
public readonly tooltip: string | MarkdownString = new MarkdownString(
l10n.t('Environments built from PEP 723 inline script metadata.'),
true,
Expand Down
1 change: 1 addition & 0 deletions src/managers/builtin/sysPythonManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export class SysPythonManager implements EnvironmentManager {
public readonly description: string | undefined;
public readonly tooltip: string | MarkdownString;
public readonly iconPath: IconPath;
public readonly createCapabilities = { customName: false } as const;

constructor(
private readonly nativeFinder: NativePythonFinder,
Expand Down
6 changes: 6 additions & 0 deletions src/managers/builtin/venvManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export class VenvManager implements EnvironmentManager {
readonly description?: string | undefined;
readonly tooltip?: string | MarkdownString | undefined;
readonly iconPath?: IconPath | undefined;
readonly createCapabilities = { customName: true } as const;

constructor(
private readonly nativeFinder: NativePythonFinder,
Expand Down Expand Up @@ -185,13 +186,18 @@ export class VenvManager implements EnvironmentManager {
this.globalEnv,
venvRoot,
options?.additionalPackages,
options?.name,
);
}
} else {
// 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,
...(options?.name === undefined ? {} : { name: options.name }),
...(options?.additionalPackages === undefined
? {}
: { additionalPackages: options.additionalPackages }),
});
}

Expand Down
17 changes: 10 additions & 7 deletions src/managers/builtin/venvStepBasedFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ interface VenvCreationState {

// Name for the venv
venvName?: string;
suppliedName?: boolean;

// Packages to install in the venv
// undefined = not yet set, null = user canceled during package selection
Expand Down Expand Up @@ -161,8 +162,7 @@ async function selectBasePython(state: VenvCreationState): Promise<StepFunction

state.basePython = basePython;

// Next step: input venv name
return enterEnvironmentName;
return state.venvName === undefined ? enterEnvironmentName : selectPackages;
} catch (ex) {
if (ex === QuickInputButtons.Back) {
// Go back to create type selection if we came from there
Expand Down Expand Up @@ -269,8 +269,7 @@ async function selectPackages(state: VenvCreationState): Promise<StepFunction |
return null;
} catch (ex) {
if (ex === QuickInputButtons.Back) {
// Go back to environment name input
return enterEnvironmentName;
return state.suppliedName ? selectBasePython : enterEnvironmentName;
}
throw ex;
}
Expand Down Expand Up @@ -299,7 +298,7 @@ export async function createStepBasedVenvFlow(
manager: EnvironmentManager,
basePythons: PythonEnvironment[],
venvRoot: Uri,
options: { showQuickAndCustomOptions: boolean; additionalPackages?: string[] },
options: { showQuickAndCustomOptions: boolean; additionalPackages?: string[]; name?: string },
): Promise<CreateEnvironmentResult | undefined> {
// Sort and filter available Python environments
const sortedEnvs = ensureGlobalEnv(basePythons, log);
Expand All @@ -308,13 +307,18 @@ export async function createStepBasedVenvFlow(
envCreationErr: 'No suitable Python environments found',
};
}
if (options.name !== undefined && (await fse.pathExists(path.join(venvRoot.fsPath, options.name)))) {
Comment thread
edvilme marked this conversation as resolved.
return { envCreationErr: VenvManagerStrings.venvNameErrorExists };
}

// Initialize the state object that will track user selections
const state: VenvCreationState = {
sortedEnvs, // Store sorted environments in state to avoid re-sorting
api, // Store API reference for package selection
project: [api.getPythonProject(venvRoot)].filter(Boolean) as PythonProject[], // Get project for venvRoot
venvRoot, // Store venvRoot for path validation
venvName: options.name,
suppliedName: options.name !== undefined,
};

try {
Expand All @@ -335,8 +339,7 @@ export async function createStepBasedVenvFlow(
if (state.isQuickCreate && state.basePython) {
// Use quick create flow
sendTelemetryEvent(EventNames.VENV_CREATION, undefined, { creationType: 'quick' });
// Use the default .venv name for quick create
const quickEnvPath = path.join(venvRoot.fsPath, '.venv');
const quickEnvPath = path.join(venvRoot.fsPath, options.name ?? '.venv');

// Get workspace dependencies to install
const project = api.getPythonProject(venvRoot);
Expand Down
10 changes: 7 additions & 3 deletions src/managers/builtin/venvUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,7 @@ export async function quickCreateVenv(
baseEnv: PythonEnvironment,
venvRoot: Uri,
additionalPackages?: string[],
name?: string,
): Promise<CreateEnvironmentResult | undefined> {
const project = api.getPythonProject(venvRoot);

Expand All @@ -542,9 +543,12 @@ export async function quickCreateVenv(
return undefined;
}

// Check if .venv already exists
let venvPath = path.join(venvRoot.fsPath, '.venv');
const requestedName = name ?? '.venv';
let venvPath = path.join(venvRoot.fsPath, requestedName);
if (await fsapi.pathExists(venvPath)) {
if (name !== undefined) {
return { envCreationErr: VenvManagerStrings.venvNameErrorExists };
}
// increment to create a unique name, e.g. .venv-1
let i = 1;
while (await fsapi.pathExists(`${venvPath}-${i}`)) {
Expand All @@ -567,7 +571,7 @@ export async function createPythonVenv(
manager: EnvironmentManager,
basePythons: PythonEnvironment[],
venvRoot: Uri,
options: { showQuickAndCustomOptions: boolean; additionalPackages?: string[] },
options: { showQuickAndCustomOptions: boolean; additionalPackages?: string[]; name?: string },
): Promise<CreateEnvironmentResult | undefined> {
return createStepBasedVenvFlow(nativeFinder, api, log, manager, basePythons, venvRoot, options);
}
Expand Down
Loading
Loading