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
45 changes: 43 additions & 2 deletions src/common/childProcess.apis.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,49 @@
import * as cp from 'child_process';
import { promisify } from 'util';

const cpExec = promisify(cp.exec);

/**
* Result of execProcess - contains stdout and stderr as strings.
*/
export interface ExecResult {
stdout: string;
stderr: string;
}

/**
* Executes a command and returns the result as a promise.
* This function abstracts cp.exec to make it easier to mock in tests.
*
* Environment handling: process.env is always inherited, with options.env merged on top.
* PYTHONUTF8='1' is set as a fallback (can be overridden by process.env or options.env).
*
* @param command The command to execute (can include arguments).
* @param options Optional execution options.
* @returns A promise that resolves with { stdout, stderr } strings.
*/
export async function execProcess(command: string, options?: cp.ExecOptions): Promise<ExecResult> {
// Sets PYTHONUTF8='1' as fallback, then inherits process.env, then merges options.env overrides
const env = {
PYTHONUTF8: '1',
...process.env,
...options?.env,
};
// Force encoding: 'utf8' to guarantee string output (cp.exec can return Buffers otherwise)
const result = await cpExec(command, { ...options, env, encoding: 'utf8' });
return {
stdout: result.stdout ?? '',
stderr: result.stderr ?? '',
};
}

/**
* Spawns a new process using the specified command and arguments.
* This function abstracts cp.spawn to make it easier to mock in tests.
*
* Environment handling: process.env is always inherited, with options.env merged on top.
* PYTHONUTF8='1' is set as a fallback (can be overridden by process.env or options.env).
*
* When stdio: 'pipe' is used, returns ChildProcessWithoutNullStreams.
* Otherwise returns the standard ChildProcess.
*/
Expand All @@ -24,10 +64,11 @@ export function spawnProcess(
args: string[],
options?: cp.SpawnOptions,
): cp.ChildProcess | cp.ChildProcessWithoutNullStreams {
// Set PYTHONUTF8=1; user-provided PYTHONUTF8 values take precedence.
// Sets PYTHONUTF8='1' as fallback, then inherits process.env, then merges options.env overrides
const env = {
PYTHONUTF8: '1',
...(options?.env ?? process.env),
...process.env,
...options?.env,
};
return cp.spawn(command, args, { ...options, env });
}
13 changes: 4 additions & 9 deletions src/managers/poetry/poetryUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as path from 'path';
import { Uri } from 'vscode';
import which from 'which';
import { EnvironmentManager, PythonEnvironment, PythonEnvironmentApi, PythonEnvironmentInfo } from '../../api';
import { execProcess } from '../../common/childProcess.apis';
import { ENVS_EXTENSION_ID } from '../../common/constants';
import { traceError, traceInfo } from '../../common/logging';
import { getWorkspacePersistentState } from '../../common/persistentState';
Expand Down Expand Up @@ -190,7 +191,7 @@ export async function getPoetryVirtualenvsPath(poetryExe?: string): Promise<stri
const poetry = poetryExe || (await getPoetry());
if (poetry) {
try {
const { stdout } = await exec(`"${poetry}" config virtualenvs.path`);
const { stdout } = await execProcess(`"${poetry}" config virtualenvs.path`);
if (stdout) {
const venvPath = stdout.trim();
// Poetry might return the path with placeholders like {cache-dir}
Expand Down Expand Up @@ -225,20 +226,14 @@ export async function getPoetryVirtualenvsPath(poetryExe?: string): Promise<stri
return undefined;
}

// These are now exported for use in main.ts or environment manager logic
import * as cp from 'child_process';
import { promisify } from 'util';

const exec = promisify(cp.exec);

export async function getPoetryVersion(poetry: string): Promise<string | undefined> {
try {
const { stdout } = await exec(`"${poetry}" --version`);
const { stdout } = await execProcess(`"${poetry}" --version`);
// Handle both formats:
// Old: "Poetry version 1.5.1"
// New: "Poetry (version 2.1.3)"
traceInfo(`Poetry version output: ${stdout.trim()}`);
const match = stdout.match(/Poetry (?:version|[\(\s]+version[\s\)]+)([0-9]+\.[0-9]+\.[0-9]+)/i);
const match = stdout.match(/Poetry (?:version |[\(\s]+version[\s\)]+)([0-9]+\.[0-9]+\.[0-9]+)/i);
return match ? match[1] : undefined;
} catch {
return undefined;
Expand Down
55 changes: 53 additions & 2 deletions src/test/managers/poetry/poetryUtils.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import assert from 'node:assert';
import * as sinon from 'sinon';
import { isPoetryVirtualenvsInProject, nativeToPythonEnv } from '../../../managers/poetry/poetryUtils';
import * as utils from '../../../managers/common/utils';
import { EnvironmentManager, PythonEnvironment, PythonEnvironmentApi, PythonEnvironmentInfo } from '../../../api';
import * as childProcessApis from '../../../common/childProcess.apis';
import { NativeEnvInfo } from '../../../managers/common/nativePythonFinder';
import * as utils from '../../../managers/common/utils';
import {
getPoetryVersion,
isPoetryVirtualenvsInProject,
nativeToPythonEnv,
} from '../../../managers/poetry/poetryUtils';

suite('isPoetryVirtualenvsInProject', () => {
test('should return false when env var is not set', () => {
Expand Down Expand Up @@ -157,3 +162,49 @@ suite('nativeToPythonEnv - POETRY_VIRTUALENVS_IN_PROJECT integration', () => {
assert.strictEqual(capturedInfo!.group, undefined, 'Non-global path should not be global');
});
});

suite('getPoetryVersion - childProcess.apis mocking pattern', () => {
let execProcessStub: sinon.SinonStub;

setup(() => {
execProcessStub = sinon.stub(childProcessApis, 'execProcess');
});

teardown(() => {
sinon.restore();
});

test('should parse Poetry 1.x version format', async () => {
execProcessStub.resolves({ stdout: 'Poetry version 1.5.1\n', stderr: '' });

const version = await getPoetryVersion('/usr/bin/poetry');

assert.strictEqual(version, '1.5.1');
assert.ok(execProcessStub.calledOnce);
assert.ok(execProcessStub.calledWith('"/usr/bin/poetry" --version'));
});

test('should parse Poetry 2.x version format', async () => {
execProcessStub.resolves({ stdout: 'Poetry (version 2.1.3)\n', stderr: '' });

const version = await getPoetryVersion('/usr/bin/poetry');

assert.strictEqual(version, '2.1.3');
});

test('should return undefined when command fails', async () => {
execProcessStub.rejects(new Error('Command not found'));

const version = await getPoetryVersion('/nonexistent/poetry');

assert.strictEqual(version, undefined);
});

test('should return undefined when output does not match expected format', async () => {
execProcessStub.resolves({ stdout: 'unexpected output', stderr: '' });

const version = await getPoetryVersion('/usr/bin/poetry');

assert.strictEqual(version, undefined);
});
});
Loading