diff --git a/package.json b/package.json index 3c5865b59b37..96ffc0bf95fa 100644 --- a/package.json +++ b/package.json @@ -622,6 +622,15 @@ "scope": "resource", "type": "boolean" }, + "python.terminal.commandPrefix": { + "default": [], + "description": "%python.terminal.commandPrefix.description%", + "items": { + "type": "string" + }, + "scope": "resource", + "type": "array" + }, "python.terminal.executeInFileDir": { "default": false, "description": "%python.terminal.executeInFileDir.description%", diff --git a/package.nls.json b/package.nls.json index 038c0f278305..3f80b504c367 100644 --- a/package.nls.json +++ b/package.nls.json @@ -76,6 +76,7 @@ "python.terminal.shellIntegration.enabled.description": "Enable [shell integration](https://code.visualstudio.com/docs/terminal/shell-integration) for the terminals running python. Shell integration enhances the terminal experience by enabling command decorations, run recent command, improving accessibility among other things. Note: PyREPL (available in Python 3.13+) is automatically disabled when shell integration is enabled to avoid cursor indentation issues.", "python.terminal.activateEnvInCurrentTerminal.description": "Activate Python Environment in the current Terminal on load of the Extension.", "python.terminal.activateEnvironment.description": "Activate Python Environment in all Terminals created.", + "python.terminal.commandPrefix.description": "Custom command prefix (e.g., [\"uv\", \"run\"] or [\"poetry\", \"run\"]) to run Python files in the terminal instead of invoking the Python interpreter directly.", "python.terminal.executeInFileDir.description": "When executing a file in the terminal, whether to use execute in the file's directory, instead of the current open folder.", "python.terminal.focusAfterLaunch.description": "When launching a python terminal, whether to focus the cursor on the terminal.", "python.terminal.launchArgs.description": "Python launch arguments to use when executing a file in the terminal.", diff --git a/src/client/common/configSettings.ts b/src/client/common/configSettings.ts index 91c06d9331fd..20cabcb96805 100644 --- a/src/client/common/configSettings.ts +++ b/src/client/common/configSettings.ts @@ -372,6 +372,7 @@ export class PythonSettings implements IPythonSettings { this.terminal = this.terminal ? this.terminal : { + commandPrefix: [], executeInFileDir: true, focusAfterLaunch: false, launchArgs: [], diff --git a/src/client/common/types.ts b/src/client/common/types.ts index c30ad704b6c1..b0cf47b3edd0 100644 --- a/src/client/common/types.ts +++ b/src/client/common/types.ts @@ -183,6 +183,7 @@ export interface IInterpreterSettings { } export interface ITerminalSettings { + readonly commandPrefix?: string[]; readonly executeInFileDir: boolean; readonly focusAfterLaunch: boolean; readonly launchArgs: string[]; diff --git a/src/client/terminals/codeExecution/codeExecutionManager.ts b/src/client/terminals/codeExecution/codeExecutionManager.ts index fe1520a2f61e..7819638935b1 100644 --- a/src/client/terminals/codeExecution/codeExecutionManager.ts +++ b/src/client/terminals/codeExecution/codeExecutionManager.ts @@ -23,6 +23,7 @@ import { } from '../../pythonEnvironments/creation/createEnvironmentTrigger'; import { ReplType } from '../../repl/types'; import { runInDedicatedTerminal, runInTerminal, useEnvExtension } from '../../envExt/api.internal'; +import { getNormalizedCommandPrefix } from './terminalCodeExecution'; @injectable() export class CodeExecutionManager implements ICodeExecutionManager { @@ -136,8 +137,22 @@ export class CodeExecutionManager implements ICodeExecutionManager { fileToExecute = fileAfterSave; } - // Check on setting terminal.executeInFileDir + // Check on setting terminal.commandPrefix const pythonSettings = this.configSettings.getSettings(file); + const commandPrefix = getNormalizedCommandPrefix(pythonSettings?.terminal?.commandPrefix); + if (commandPrefix.length > 0) { + const executionService = this.serviceContainer.get( + ICodeExecutionService, + 'standard', + ); + await executionService.executeFile(fileToExecute, { newTerminalPerFile: dedicated }); + if (this.shouldTerminalFocusOnStart(fileToExecute)) { + this.commandManager.executeCommand('workbench.action.terminal.focus'); + } + return; + } + + // Check on setting terminal.executeInFileDir let cwd = pythonSettings.terminal.executeInFileDir ? path.dirname(fileToExecute.fsPath) : undefined; // Check on setting terminal.launchArgs diff --git a/src/client/terminals/codeExecution/terminalCodeExecution.ts b/src/client/terminals/codeExecution/terminalCodeExecution.ts index 3a04f250d882..3444a7a5dea2 100644 --- a/src/client/terminals/codeExecution/terminalCodeExecution.ts +++ b/src/client/terminals/codeExecution/terminalCodeExecution.ts @@ -20,6 +20,13 @@ import { ICodeExecutionService } from '../../terminals/types'; import { EventName } from '../../telemetry/constants'; import { sendTelemetryEvent } from '../../telemetry'; +export function getNormalizedCommandPrefix(commandPrefix?: string[]): string[] { + if (!Array.isArray(commandPrefix)) { + return []; + } + return commandPrefix.map((part) => (typeof part === 'string' ? part.trim() : '')).filter(Boolean); +} + @injectable() export class TerminalCodeExecutionProvider implements ICodeExecutionService { private hasRanOutsideCurrentDrive = false; @@ -123,6 +130,12 @@ export class TerminalCodeExecutionProvider implements ICodeExecutionService { // Overridden in subclasses, see djangoShellCodeExecution.ts public async getExecuteFileArgs(resource?: Uri, executeArgs: string[] = []): Promise { + const pythonSettings = this.configurationService.getSettings(resource); + const commandPrefix = getNormalizedCommandPrefix(pythonSettings.terminal.commandPrefix); + if (commandPrefix.length > 0) { + const launchArgs = pythonSettings.terminal.launchArgs ?? []; + return buildPythonExecInfo(commandPrefix, [...launchArgs, ...executeArgs]); + } return this.getExecutableInfo(resource, executeArgs); } private getTerminalService(resource: Resource, options?: { newTerminalPerFile: boolean }): ITerminalService { diff --git a/src/test/terminals/codeExecution/codeExecutionManager.unit.test.ts b/src/test/terminals/codeExecution/codeExecutionManager.unit.test.ts index 60f36230ca56..60e4fcde0bea 100644 --- a/src/test/terminals/codeExecution/codeExecutionManager.unit.test.ts +++ b/src/test/terminals/codeExecution/codeExecutionManager.unit.test.ts @@ -437,4 +437,59 @@ suite('Terminal - Code Execution Manager', () => { test('Ensure executeSelectionInDjangoShell will normalize selected text and send it to the terminal', async () => { await testExecutionOfSelectionIsSentToTerminal(Commands.Exec_Selection_In_Django_Shell, 'djangoShell'); }); + + test('Ensure executeUsingExtension delegates to standard execution service when terminal.commandPrefix is set', async () => { + useEnvExtensionStub.returns(true); + const runInTerminalStub = sinon.stub(extapi, 'runInTerminal'); + const fileToExecute = Uri.file('test_uv.py'); + + let commandHandler: undefined | ((file?: Uri) => Promise); + commandManager + .setup((c) => c.registerCommand as any) + .returns(() => { + return (command: string, callback: (...args: any[]) => any) => { + if (command === Commands.Exec_In_Terminal_Icon) { + commandHandler = callback; + } + return { dispose: () => void 0 }; + }; + }); + executionManager.registerCommands(); + expect(commandHandler).not.to.be.an('undefined'); + + const helper = TypeMoq.Mock.ofType(); + helper.setup((h) => h.saveFileIfDirty(fileToExecute)).returns(() => Promise.resolve(fileToExecute)); + serviceContainer.setup((s) => s.get(TypeMoq.It.isValue(ICodeExecutionHelper))).returns(() => helper.object); + + const settings = TypeMoq.Mock.ofType(); + settings + .setup((s) => s.terminal) + .returns( + () => + ({ + commandPrefix: ['uv', 'run'], + executeInFileDir: false, + focusAfterLaunch: false, + launchArgs: [], + activateEnvironment: true, + activateEnvInCurrentTerminal: false, + shellIntegration: { enabled: false }, + } as any), + ); + configService.setup((c) => c.getSettings(TypeMoq.It.isAny())).returns(() => settings.object); + + const executionService = TypeMoq.Mock.ofType(); + executionService + .setup((e) => e.executeFile(fileToExecute, TypeMoq.It.isValue({ newTerminalPerFile: false }))) + .returns(() => Promise.resolve()) + .verifiable(TypeMoq.Times.once()); + serviceContainer + .setup((s) => s.get(TypeMoq.It.isValue(ICodeExecutionService), TypeMoq.It.isValue('standard'))) + .returns(() => executionService.object); + + await commandHandler!(fileToExecute); + + expect(runInTerminalStub.called).to.equal(false); + executionService.verifyAll(); + }); }); diff --git a/src/test/terminals/codeExecution/terminalCodeExec.unit.test.ts b/src/test/terminals/codeExecution/terminalCodeExec.unit.test.ts index cb7f94938ae8..634cd9744d2f 100644 --- a/src/test/terminals/codeExecution/terminalCodeExec.unit.test.ts +++ b/src/test/terminals/codeExecution/terminalCodeExec.unit.test.ts @@ -682,4 +682,90 @@ suite('Terminal - Code Execution', () => { }); }); }); + + suite('Terminal Execution - Custom commandPrefix', () => { + let terminalSettings: TypeMoq.IMock; + let terminalService: TypeMoq.IMock; + let terminalFactory: TypeMoq.IMock; + let executor: TerminalCodeExecutionProvider; + + setup(() => { + terminalFactory = TypeMoq.Mock.ofType(); + terminalSettings = TypeMoq.Mock.ofType(); + terminalService = TypeMoq.Mock.ofType(); + const configService = TypeMoq.Mock.ofType(); + const workspace = TypeMoq.Mock.ofType(); + const platform = TypeMoq.Mock.ofType(); + const commandManager = TypeMoq.Mock.ofType(); + const interpreterService = TypeMoq.Mock.ofType(); + const applicationShell = TypeMoq.Mock.ofType(); + const settings = TypeMoq.Mock.ofType(); + + settings.setup((s) => s.terminal).returns(() => terminalSettings.object); + configService.setup((c) => c.getSettings(TypeMoq.It.isAny())).returns(() => settings.object); + platform.setup((p) => p.isWindows).returns(() => false); + terminalFactory + .setup((f) => f.getTerminalService(TypeMoq.It.isAny())) + .returns(() => terminalService.object); + terminalService + .setup((t) => t.sendCommand(TypeMoq.It.isAny(), TypeMoq.It.isAny())) + .returns(() => Promise.resolve()); + interpreterService + .setup((s) => s.getActiveInterpreter(TypeMoq.It.isAny())) + .returns(() => Promise.resolve(({ path: '/usr/bin/python3' } as unknown) as PythonEnvironment)); + + executor = new TerminalCodeExecutionProvider( + terminalFactory.object, + configService.object, + workspace.object, + [], + platform.object, + interpreterService.object, + commandManager.object, + applicationShell.object, + ); + }); + + test('Uses configured commandPrefix instead of Python interpreter when executing a file', async () => { + const file = Uri.file(path.join('workspace', 'app.py')); + terminalSettings.setup((t) => t.commandPrefix).returns(() => ['uv', 'run']); + terminalSettings.setup((t) => t.launchArgs).returns(() => ['--quiet']); + terminalSettings.setup((t) => t.executeInFileDir).returns(() => false); + + await executor.executeFile(file); + + terminalService.verify( + (t) => t.sendCommand('uv', ['run', '--quiet', file.fsPath.fileToCommandArgumentForPythonExt()]), + TypeMoq.Times.once(), + ); + }); + + test('Trims whitespace and ignores empty entries in commandPrefix', async () => { + const file = Uri.file(path.join('workspace', 'script.py')); + terminalSettings.setup((t) => t.commandPrefix).returns(() => [' poetry ', ' ', 'run ']); + terminalSettings.setup((t) => t.launchArgs).returns(() => []); + terminalSettings.setup((t) => t.executeInFileDir).returns(() => false); + + await executor.executeFile(file); + + terminalService.verify( + (t) => t.sendCommand('poetry', ['run', file.fsPath.fileToCommandArgumentForPythonExt()]), + TypeMoq.Times.once(), + ); + }); + + test('Falls back to Python interpreter when commandPrefix is empty', async () => { + const file = Uri.file(path.join('workspace', 'fallback.py')); + terminalSettings.setup((t) => t.commandPrefix).returns(() => [' ', '']); + terminalSettings.setup((t) => t.launchArgs).returns(() => ['-u']); + terminalSettings.setup((t) => t.executeInFileDir).returns(() => false); + + await executor.executeFile(file); + + terminalService.verify( + (t) => t.sendCommand('/usr/bin/python3', ['-u', file.fsPath.fileToCommandArgumentForPythonExt()]), + TypeMoq.Times.once(), + ); + }); + }); });