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
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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%",
Expand Down
1 change: 1 addition & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
1 change: 1 addition & 0 deletions src/client/common/configSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ export class PythonSettings implements IPythonSettings {
this.terminal = this.terminal
? this.terminal
: {
commandPrefix: [],
executeInFileDir: true,
focusAfterLaunch: false,
launchArgs: [],
Expand Down
1 change: 1 addition & 0 deletions src/client/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ export interface IInterpreterSettings {
}

export interface ITerminalSettings {
readonly commandPrefix?: string[];
readonly executeInFileDir: boolean;
readonly focusAfterLaunch: boolean;
readonly launchArgs: string[];
Expand Down
17 changes: 16 additions & 1 deletion src/client/terminals/codeExecution/codeExecutionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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>(
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
Expand Down
13 changes: 13 additions & 0 deletions src/client/terminals/codeExecution/terminalCodeExecution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -123,6 +130,12 @@ export class TerminalCodeExecutionProvider implements ICodeExecutionService {

// Overridden in subclasses, see djangoShellCodeExecution.ts
public async getExecuteFileArgs(resource?: Uri, executeArgs: string[] = []): Promise<PythonExecInfo> {
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 {
Expand Down
55 changes: 55 additions & 0 deletions src/test/terminals/codeExecution/codeExecutionManager.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>);
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<ICodeExecutionHelper>();
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<IPythonSettings>();
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<ICodeExecutionService>();
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();
});
});
86 changes: 86 additions & 0 deletions src/test/terminals/codeExecution/terminalCodeExec.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -682,4 +682,90 @@ suite('Terminal - Code Execution', () => {
});
});
});

suite('Terminal Execution - Custom commandPrefix', () => {
let terminalSettings: TypeMoq.IMock<ITerminalSettings>;
let terminalService: TypeMoq.IMock<ITerminalService>;
let terminalFactory: TypeMoq.IMock<ITerminalServiceFactory>;
let executor: TerminalCodeExecutionProvider;

setup(() => {
terminalFactory = TypeMoq.Mock.ofType<ITerminalServiceFactory>();
terminalSettings = TypeMoq.Mock.ofType<ITerminalSettings>();
terminalService = TypeMoq.Mock.ofType<ITerminalService>();
const configService = TypeMoq.Mock.ofType<IConfigurationService>();
const workspace = TypeMoq.Mock.ofType<IWorkspaceService>();
const platform = TypeMoq.Mock.ofType<IPlatformService>();
const commandManager = TypeMoq.Mock.ofType<ICommandManager>();
const interpreterService = TypeMoq.Mock.ofType<IInterpreterService>();
const applicationShell = TypeMoq.Mock.ofType<IApplicationShell>();
const settings = TypeMoq.Mock.ofType<IPythonSettings>();

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(),
);
});
});
});