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
31 changes: 31 additions & 0 deletions src/common/childProcess.apis.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,35 @@
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.
*
* @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> {
const env = {
PYTHONUTF8: '1',
...(options?.env ?? process.env),
};
const result = await cpExec(command, { ...options, env });
return {
stdout: result.stdout ?? '',

Check failure on line 29 in src/common/childProcess.apis.ts

View workflow job for this annotation

GitHub Actions / TypeScript Unit Tests (windows-latest)

Type 'string | Buffer' is not assignable to type 'string'.

Check failure on line 29 in src/common/childProcess.apis.ts

View workflow job for this annotation

GitHub Actions / TypeScript Unit Tests (ubuntu-latest)

Type 'string | Buffer' is not assignable to type 'string'.

Check failure on line 29 in src/common/childProcess.apis.ts

View workflow job for this annotation

GitHub Actions / TypeScript Unit Tests (windows-latest)

Type 'string | Buffer' is not assignable to type 'string'.

Check failure on line 29 in src/common/childProcess.apis.ts

View workflow job for this annotation

GitHub Actions / TypeScript Unit Tests (ubuntu-latest)

Type 'string | Buffer' is not assignable to type 'string'.
stderr: result.stderr ?? '',

Check failure on line 30 in src/common/childProcess.apis.ts

View workflow job for this annotation

GitHub Actions / TypeScript Unit Tests (windows-latest)

Type 'string | Buffer' is not assignable to type 'string'.

Check failure on line 30 in src/common/childProcess.apis.ts

View workflow job for this annotation

GitHub Actions / TypeScript Unit Tests (ubuntu-latest)

Type 'string | Buffer' is not assignable to type 'string'.

Check failure on line 30 in src/common/childProcess.apis.ts

View workflow job for this annotation

GitHub Actions / TypeScript Unit Tests (windows-latest)

Type 'string | Buffer' is not assignable to type 'string'.

Check failure on line 30 in src/common/childProcess.apis.ts

View workflow job for this annotation

GitHub Actions / TypeScript Unit Tests (ubuntu-latest)

Type 'string | Buffer' is not assignable to type 'string'.
Comment on lines +28 to +30
Copy link

Copilot AI Feb 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

execProcess is documented/typed to return stdout/stderr as strings, but cp.exec can return Buffers when callers pass encoding: 'buffer' | null in options. As written, a Buffer will flow through (it’s not nullish) and can break callers that do string operations (e.g. .trim()). Consider forcing encoding: 'utf8' (or converting Buffer→string before returning) to make the wrapper’s contract true and avoid runtime type mismatches.

Suggested change
return {
stdout: result.stdout ?? '',
stderr: result.stderr ?? '',
const rawStdout = result.stdout ?? '';
const rawStderr = result.stderr ?? '';
return {
stdout: Buffer.isBuffer(rawStdout) ? rawStdout.toString('utf8') : rawStdout,
stderr: Buffer.isBuffer(rawStderr) ? rawStderr.toString('utf8') : rawStderr,

Copilot uses AI. Check for mistakes.
};
}

/**
* Spawns a new process using the specified command and arguments.
Expand Down
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