Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
10 changes: 6 additions & 4 deletions src/extension/common/utils/localize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,12 @@ export namespace DebugConfigStrings {
label: l10n.t('FastAPI'),
description: l10n.t('Launch and debug a FastAPI web application'),
};
export const enterAppPathOrNamePath = {
title: l10n.t('Debug FastAPI'),
prompt: l10n.t("Enter the path to the application, e.g. 'main.py' or 'main'"),
invalid: l10n.t('Enter a valid name'),
export const snippetFile = {
name: l10n.t('Python Debugger: FastAPI File'),
};
export const selectConfigurationWithFile = {
label: l10n.t('FastAPI File'),
description: l10n.t('Launch and debug a FastAPI web application using the current file'),
};
}
export namespace flask {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { IMultiStepInputFactory, InputStep, IQuickPickParameters, MultiStepInput
import { AttachRequestArguments, DebugConfigurationArguments, LaunchRequestArguments } from '../../types';
import { DebugConfigurationState, DebugConfigurationType, IDebugConfigurationService } from '../types';
import { buildDjangoLaunchDebugConfiguration } from './providers/djangoLaunch';
import { buildFastAPILaunchDebugConfiguration } from './providers/fastapiLaunch';
import { buildFastAPILaunchDebugConfiguration, buildFastAPIWithFileLaunchDebugConfiguration } from './providers/fastapiLaunch';
import { buildFileLaunchDebugConfiguration } from './providers/fileLaunch';
import { buildFlaskLaunchDebugConfiguration } from './providers/flaskLaunch';
import { buildModuleLaunchConfiguration } from './providers/moduleLaunch';
Expand Down Expand Up @@ -158,6 +158,11 @@ export class PythonDebugConfigurationService implements IDebugConfigurationServi
type: DebugConfigurationType.launchFastAPI,
description: DebugConfigStrings.fastapi.selectConfiguration.description,
},
{
label: DebugConfigStrings.fastapi.selectConfigurationWithFile.label,
type: DebugConfigurationType.launchFastAPIWithFile,
description: DebugConfigStrings.fastapi.selectConfigurationWithFile.description,
},
{
label: DebugConfigStrings.flask.selectConfiguration.label,
type: DebugConfigurationType.launchFlask,
Expand All @@ -178,6 +183,7 @@ export class PythonDebugConfigurationService implements IDebugConfigurationServi
>();
debugConfigurations.set(DebugConfigurationType.launchDjango, buildDjangoLaunchDebugConfiguration);
debugConfigurations.set(DebugConfigurationType.launchFastAPI, buildFastAPILaunchDebugConfiguration);
debugConfigurations.set(DebugConfigurationType.launchFastAPIWithFile, buildFastAPIWithFileLaunchDebugConfiguration);
debugConfigurations.set(DebugConfigurationType.launchFile, buildFileLaunchDebugConfiguration);
debugConfigurations.set(DebugConfigurationType.launchFileWithArgs, buildFileWithArgsLaunchDebugConfiguration);
debugConfigurations.set(DebugConfigurationType.launchFlask, buildFlaskLaunchDebugConfiguration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import * as path from 'path';
import { CancellationToken, DebugConfiguration, WorkspaceFolder } from 'vscode';
import { IDynamicDebugConfigurationService } from '../types';
import { DebuggerTypeName } from '../../constants';
import { replaceAll } from '../../common/stringUtils';
import { getDjangoPaths, getFastApiPaths, getFlaskPaths } from './utils/configuration';
import { sendTelemetryEvent } from '../../telemetry';
import { EventName } from '../../telemetry/constants';
Expand Down Expand Up @@ -63,15 +62,21 @@ export class DynamicPythonDebugConfigurationService implements IDynamicDebugConf
}

const fastApiPaths = await getFastApiPaths(folder);
Comment thread
savannahostrowski marked this conversation as resolved.
let fastApiPath = fastApiPaths?.length ? fastApiPaths[0].fsPath : null;
if (fastApiPath) {
fastApiPath = replaceAll(path.relative(folder.uri.fsPath, fastApiPath), path.sep, '.').replace('.py', '');
if (fastApiPaths?.length) {
providers.push({
name: 'Python Debugger: FastAPI',
type: DebuggerTypeName,
request: 'launch',
module: 'uvicorn',
args: [`${fastApiPath}:app`, '--reload'],
module: 'fastapi',
args: ['run'],
jinja: true,
});
providers.push({
name: 'Python Debugger: FastAPI File',
type: DebuggerTypeName,
request: 'launch',
module: 'fastapi',
args: ['run', '${file}'],
jinja: true,
});
}
Expand Down
60 changes: 20 additions & 40 deletions src/extension/debugger/configuration/providers/fastapiLaunch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@

'use strict';

import * as path from 'path';
import * as fs from 'fs-extra';
import { WorkspaceFolder } from 'vscode';
import { MultiStepInput } from '../../../common/multiStepInput';
import { DebugConfigStrings } from '../../../common/utils/localize';
import { sendTelemetryEvent } from '../../../telemetry';
Expand All @@ -15,54 +12,37 @@ import { LaunchRequestArguments } from '../../../types';
import { DebugConfigurationState, DebugConfigurationType } from '../../types';

export async function buildFastAPILaunchDebugConfiguration(
input: MultiStepInput<DebugConfigurationState>,
_input: MultiStepInput<DebugConfigurationState>,
state: DebugConfigurationState,
): Promise<void> {
const application = await getApplicationPath(state.folder);
let manuallyEnteredAValue: boolean | undefined;
const config: Partial<LaunchRequestArguments> = {
Comment thread
savannahostrowski marked this conversation as resolved.
name: DebugConfigStrings.fastapi.snippet.name,
type: DebuggerTypeName,
request: 'launch',
module: 'uvicorn',
args: ['main:app', '--reload'],
module: 'fastapi',
args: ['run'],
jinja: true,
};

if (!application) {
Comment thread
savannahostrowski marked this conversation as resolved.
const selectedPath = await input.showInputBox({
title: DebugConfigStrings.fastapi.enterAppPathOrNamePath.title,
value: 'main.py',
prompt: DebugConfigStrings.fastapi.enterAppPathOrNamePath.prompt,
validate: (value) =>
Promise.resolve(
value && value.trim().length > 0
? undefined
: DebugConfigStrings.fastapi.enterAppPathOrNamePath.invalid,
),
});
if (selectedPath) {
manuallyEnteredAValue = true;
config.args = [`${path.basename(selectedPath, '.py').replace('/', '.')}:app`, '--reload'];
} else {
return;
}
}

sendTelemetryEvent(EventName.DEBUGGER_CONFIGURATION_PROMPTS, undefined, {
configurationType: DebugConfigurationType.launchFastAPI,
autoDetectedFastAPIMainPyPath: !!application,
manuallyEnteredAValue,
});
Object.assign(state.config, config);
}
export async function getApplicationPath(folder: WorkspaceFolder | undefined): Promise<string | undefined> {
if (!folder) {
return undefined;
}
const defaultLocationOfManagePy = path.join(folder.uri.fsPath, 'main.py');
if (await fs.pathExists(defaultLocationOfManagePy)) {
return 'main.py';
}
return undefined;

export async function buildFastAPIWithFileLaunchDebugConfiguration(
_input: MultiStepInput<DebugConfigurationState>,
state: DebugConfigurationState,
): Promise<void> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot generated:
The Architect notes the ['run', '${file}'] config literal now lives in two places (here and dynamicdebugConfigurationService.ts), and the ['run'] default is encoded both in tryResolveFastApiArgs and as ?? ['run'] in the dynamic caller. Hoist to a shared constant / small helper to prevent drift. Low priority.

[verified]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I tried this but extracting ['run', '${file}'] into a readonly string[] constant required spreading at every call site ([...FASTAPI_RUN_FILE_ARGS]), which was longer than the inline literal.

const config: Partial<LaunchRequestArguments> = {
name: DebugConfigStrings.fastapi.snippetFile.name,
type: DebuggerTypeName,
request: 'launch',
module: 'fastapi',
args: ['run', '${file}'],
jinja: true,
};
sendTelemetryEvent(EventName.DEBUGGER_CONFIGURATION_PROMPTS, undefined, {
configurationType: DebugConfigurationType.launchFastAPIWithFile,
});
Object.assign(state.config, config);
}
1 change: 1 addition & 0 deletions src/extension/debugger/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export enum DebugConfigurationType {
remoteAttach = 'remoteAttach',
launchDjango = 'launchDjango',
launchFastAPI = 'launchFastAPI',
launchFastAPIWithFile = 'launchFastAPIWithFile',
launchFlask = 'launchFlask',
launchModule = 'launchModule',
launchPyramid = 'launchPyramid',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@
'use strict';

import { expect } from 'chai';
import * as path from 'path';
import * as fs from 'fs-extra';
import * as sinon from 'sinon';
import { anything, instance, mock, when } from 'ts-mockito';
import { instance, mock } from 'ts-mockito';
import { Uri } from 'vscode';
import * as path from 'path';
import { DebugConfigStrings } from '../../../../extension/common/utils/localize';
import { DebuggerTypeName } from '../../../../extension/constants';
import * as fastApiLaunch from '../../../../extension/debugger/configuration/providers/fastapiLaunch';
Expand All @@ -17,45 +15,41 @@ import { MultiStepInput } from '../../../../extension/common/multiStepInput';

suite('Debugging - Configuration Provider FastAPI', () => {
let input: MultiStepInput<DebugConfigurationState>;
let pathExistsStub: sinon.SinonStub;

setup(() => {
input = mock<MultiStepInput<DebugConfigurationState>>(MultiStepInput);
pathExistsStub = sinon.stub(fs, 'pathExists');
});
teardown(() => {
sinon.restore();
});
test("getApplicationPath should return undefined if file doesn't exist", async () => {
const folder = { uri: Uri.parse(path.join('one', 'two')), name: '1', index: 0 };
const appPyPath = path.join(folder.uri.fsPath, 'main.py');
pathExistsStub.withArgs(appPyPath).resolves(false);
const file = await fastApiLaunch.getApplicationPath(folder);

expect(file).to.be.equal(undefined, 'Should return undefined');
});
test('getApplicationPath should find path', async () => {
test('Launch JSON with default configuration', async () => {
const folder = { uri: Uri.parse(path.join('one', 'two')), name: '1', index: 0 };
const appPyPath = path.join(folder.uri.fsPath, 'main.py');
pathExistsStub.withArgs(appPyPath).resolves(true);
const file = await fastApiLaunch.getApplicationPath(folder);
const state = { config: {}, folder };
Comment thread
savannahostrowski marked this conversation as resolved.

await fastApiLaunch.buildFastAPILaunchDebugConfiguration(instance(input), state);

const config = {
name: DebugConfigStrings.fastapi.snippet.name,
type: DebuggerTypeName,
request: 'launch',
module: 'fastapi',
args: ['run'],
jinja: true,
};

expect(file).to.be.equal('main.py');
expect(state.config).to.be.deep.equal(config);
});
test('Launch JSON with selected app path', async () => {

test('Launch JSON with file configuration', async () => {
const folder = { uri: Uri.parse(path.join('one', 'two')), name: '1', index: 0 };
const state = { config: {}, folder };

when(input.showInputBox(anything())).thenResolve('main');

await fastApiLaunch.buildFastAPILaunchDebugConfiguration(instance(input), state);
await fastApiLaunch.buildFastAPIWithFileLaunchDebugConfiguration(instance(input), state);

const config = {
name: DebugConfigStrings.fastapi.snippet.name,
name: DebugConfigStrings.fastapi.snippetFile.name,
type: DebuggerTypeName,
request: 'launch',
module: 'uvicorn',
args: ['main:app', '--reload'],
module: 'fastapi',
args: ['run', '${file}'],
jinja: true,
};

Expand Down
Loading