From 79e19b46d60c30649166a7f9e7de0b2220a04863 Mon Sep 17 00:00:00 2001 From: Tanu Saini Date: Sun, 29 Nov 2026 01:22:45 +0530 Subject: [PATCH] Add NewFlaskProject template and creator --- .../flask-copilot-instructions.md | 9 + files/templates/newFlaskTemplate/app.py | 12 + .../templates/newFlaskTemplate/pyproject.toml | 9 + .../newFlaskTemplate/tests/test_app.py | 8 + src/extension.ts | 5 + src/features/creators/newFlaskProject.ts | 210 ++++++++++++++++++ .../creators/newFlaskProject.unit.test.ts | 189 ++++++++++++++++ 7 files changed, 442 insertions(+) create mode 100644 files/templates/copilot-instructions-text/flask-copilot-instructions.md create mode 100644 files/templates/newFlaskTemplate/app.py create mode 100644 files/templates/newFlaskTemplate/pyproject.toml create mode 100644 files/templates/newFlaskTemplate/tests/test_app.py create mode 100644 src/features/creators/newFlaskProject.ts create mode 100644 src/test/features/creators/newFlaskProject.unit.test.ts diff --git a/files/templates/copilot-instructions-text/flask-copilot-instructions.md b/files/templates/copilot-instructions-text/flask-copilot-instructions.md new file mode 100644 index 000000000..386c4777d --- /dev/null +++ b/files/templates/copilot-instructions-text/flask-copilot-instructions.md @@ -0,0 +1,9 @@ +# Copilot Instructions for + +- The Flask project `` is a Python Project located in the folder `-folder`. +- You need to call the `Get Python Environment Information` tool on the `` path to get the Python executable details. +- Substitute the Python executable you get from the `Get Python Environment Information` tool anywhere you see `` in these instructions. + - Run command for ``: ` -m flask --app app run` + - Command to run tests for ``: ` -m pytest tests` +- In the workspace `launch.json` file, configurations related to this project have the prefix ``. +- The project `` has a defined `pyproject.toml` file that you should use and keep up to date. diff --git a/files/templates/newFlaskTemplate/app.py b/files/templates/newFlaskTemplate/app.py new file mode 100644 index 000000000..c204b04a3 --- /dev/null +++ b/files/templates/newFlaskTemplate/app.py @@ -0,0 +1,12 @@ +from flask import Flask + +app = Flask(__name__) + + +@app.route("/") +def home() -> str: + return "Hello, Flask!" + + +if __name__ == "__main__": + app.run(debug=True) diff --git a/files/templates/newFlaskTemplate/pyproject.toml b/files/templates/newFlaskTemplate/pyproject.toml new file mode 100644 index 000000000..24699ead2 --- /dev/null +++ b/files/templates/newFlaskTemplate/pyproject.toml @@ -0,0 +1,9 @@ +[project] +name = "project_name" +version = "1.0.0" +description = "" # TODO: Add a short description of your Flask app +authors = [{ name = "Your Name", email = "your@email.com" }] # TODO: Add your name and email +requires-python = ">=3.9" +dependencies = [ + "flask", +] diff --git a/files/templates/newFlaskTemplate/tests/test_app.py b/files/templates/newFlaskTemplate/tests/test_app.py new file mode 100644 index 000000000..98b177667 --- /dev/null +++ b/files/templates/newFlaskTemplate/tests/test_app.py @@ -0,0 +1,8 @@ +from app import app + + +def test_home_route() -> None: + client = app.test_client() + response = client.get("/") + assert response.status_code == 200 + assert b"Hello, Flask!" in response.data diff --git a/src/extension.ts b/src/extension.ts index e088619c2..62e156a78 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -42,6 +42,7 @@ import { getPythonApi, setPythonApi } from './extensionApi'; import { createManagerReady } from './features/common/managerReady'; import { AutoFindProjects } from './features/creators/autoFindProjects'; import { ExistingProjects } from './features/creators/existingProjects'; +import { NewFlaskProject } from './features/creators/newFlaskProject'; import { NewPackageProject } from './features/creators/newPackageProject'; import { NewScriptProject } from './features/creators/newScriptProject'; import type { ProjectCreators } from './features/creators/projectCreators'; @@ -207,6 +208,7 @@ export async function activate(context: ExtensionContext): Promise c.name === 'newScript'); } + if (projectType === 'python-flask') { + selected = creators.find((c) => c.name === 'newFlask'); + } if (!selected) { throw new Error(`Project creator for type "${projectType}" not found.`); } diff --git a/src/features/creators/newFlaskProject.ts b/src/features/creators/newFlaskProject.ts new file mode 100644 index 000000000..1fa4ec001 --- /dev/null +++ b/src/features/creators/newFlaskProject.ts @@ -0,0 +1,210 @@ +import * as fs from 'fs-extra'; +import * as path from 'path'; +import { commands, l10n, MarkdownString, QuickInputButtons, Uri } from 'vscode'; +import { PythonEnvironment, PythonProject, PythonProjectCreator, PythonProjectCreatorOptions } from '../../api'; +import { NEW_PROJECT_TEMPLATES_FOLDER, VENV_MANAGER_ID } from '../../common/constants'; +import { traceError } from '../../common/logging'; +import { showErrorMessage, showInputBoxWithButtons, showTextDocument } from '../../common/window.apis'; +import { getWorkspaceFolders } from '../../common/workspace.apis'; +import type { EnvironmentManagers } from '../envManagers'; +import type { PythonProjectManager } from '../projectManager'; +import { + isCopilotInstalled, + manageCopilotInstructionsFile, + manageLaunchJsonFile, + promptForVenv, + replaceInFilesAndNames, +} from './creationHelpers'; + +function validateProjectName(value: string): string | null { + const pathSegments = value.split(/[\\/]/); + if (pathSegments.length !== 1 || pathSegments.includes('..')) { + return l10n.t('Project name must be a folder name without path separators or traversal.'); + } + // following PyPI (PEP 508) rules for project names + if (!/^([a-z_]|[a-z0-9_][a-z0-9._-]*[a-z0-9_])$/i.test(value)) { + return l10n.t( + 'Invalid project name. Use only letters, numbers, underscores, hyphens, or periods. Must start and end with a letter or number.', + ); + } + if (/^[-._0-9]$/i.test(value)) { + return l10n.t('Single-character project names cannot be a number, hyphen, or period.'); + } + return null; +} + +export class NewFlaskProject implements PythonProjectCreator { + public readonly name = l10n.t('newFlask'); + public readonly displayName = l10n.t('Flask'); + public readonly description = l10n.t('Creates a Flask project folder in your current workspace'); + public readonly tooltip = new MarkdownString(l10n.t('Create a new Flask project')); + + constructor( + private readonly envManagers: EnvironmentManagers, + private readonly projectManager: PythonProjectManager, + ) {} + + async create(options?: PythonProjectCreatorOptions): Promise { + let projectName = options?.name; + let createVenv: boolean | undefined; + let createCopilotInstructions: boolean | undefined; + + if (options?.quickCreate === true) { + if (!projectName) { + throw new Error('Project name is required in quickCreate mode.'); + } + createVenv = true; + createCopilotInstructions = true; + } else { + if (!projectName) { + try { + projectName = await showInputBoxWithButtons({ + prompt: l10n.t('What is the name of the Flask project? (e.g. my_flask_app)'), + ignoreFocusOut: true, + showBackButton: true, + validateInput: validateProjectName, + }); + } catch (ex) { + if (ex === QuickInputButtons.Back) { + await commands.executeCommand('python-envs.createNewProjectFromTemplate'); + } + } + if (!projectName) { + return undefined; + } + const callback = () => { + return this.create(options); + }; + createVenv = await promptForVenv(callback); + if (createVenv === undefined) { + return undefined; + } + if (isCopilotInstalled()) { + createCopilotInstructions = true; + } + } + } + + const validationError = validateProjectName(projectName); + if (validationError) { + if (options?.quickCreate === true) { + throw new Error(validationError); + } + showErrorMessage(validationError); + return undefined; + } + + // 1. Copy template folder + const newFlaskTemplateFolder = path.join(NEW_PROJECT_TEMPLATES_FOLDER, 'newFlaskTemplate'); + if (!(await fs.pathExists(newFlaskTemplateFolder))) { + showErrorMessage(l10n.t('Template folder does not exist, aborting creation.')); + traceError(`Template folder not found at: ${newFlaskTemplateFolder}`); + return undefined; + } + + // Check if the destination folder is provided, otherwise use the first workspace folder + let destRoot = options?.rootUri?.fsPath; + if (!destRoot) { + const workspaceFolders = getWorkspaceFolders(); + if (!workspaceFolders || workspaceFolders.length === 0) { + showErrorMessage(l10n.t('No workspace folder is open or provided, aborting creation.')); + return undefined; + } + destRoot = workspaceFolders[0].uri.fsPath; + } + + // Check if the destination folder already exists + const projectDestinationFolder = path.join(destRoot, projectName); + if (await fs.pathExists(projectDestinationFolder)) { + showErrorMessage( + l10n.t( + 'A project folder by that name already exists, aborting creation. Please retry with a unique project name given your workspace.', + ), + ); + return undefined; + } + + await fs.copy(newFlaskTemplateFolder, projectDestinationFolder); + + // 2. Replace 'project_name' in all files and file/folder names + await replaceInFilesAndNames(projectDestinationFolder, 'project_name', projectName); + + const createdProject: PythonProject = { + name: projectName, + uri: Uri.file(projectDestinationFolder), + }; + await this.projectManager.add(createdProject); + + // 3. Create virtual environment if requested + let createdEnv: PythonEnvironment | undefined; + if (createVenv) { + const en = this.envManagers.getEnvironmentManager(undefined); + if (en?.supportsQuickCreate) { + createdEnv = await en.create(Uri.file(projectDestinationFolder), { quickCreate: true }); + } else if (!options?.quickCreate && en?.supportsCreate) { + createdEnv = await en.create(Uri.file(projectDestinationFolder), {}); + } else { + const venvManager = this.envManagers.managers.find( + (m) => m.id === VENV_MANAGER_ID || m.supportsQuickCreate, + ); + if (venvManager) { + createdEnv = await venvManager.create(Uri.file(projectDestinationFolder), { + quickCreate: true, + }); + } else { + const action = await showErrorMessage( + l10n.t( + 'A virtual environment could not be created for the new project "{0}" because your default environment manager does not support this operation and no alternative was available.', + projectName, + ), + l10n.t('Create custom environment'), + ); + if (action === l10n.t('Create custom environment')) { + await commands.executeCommand('python-envs.createAny', { + uri: createdProject.uri, + selectEnvironment: true, + }); + createdEnv = await this.envManagers.getEnvironment(createdProject.uri); + } + } + } + } + + // 4. Get and set the Python environment for the project if available + createdEnv = createdEnv || (await this.envManagers.getEnvironment(createdProject.uri)); + if (createdEnv) { + await this.envManagers.setEnvironment(createdProject.uri, createdEnv); + } + + // 5. Add custom GitHub Copilot instructions if applicable + if (createCopilotInstructions) { + const flaskInstructionsPath = path.join( + NEW_PROJECT_TEMPLATES_FOLDER, + 'copilot-instructions-text', + 'flask-copilot-instructions.md', + ); + await manageCopilotInstructionsFile(destRoot, flaskInstructionsPath, [ + { searchValue: '', replaceValue: projectName }, + ]); + } + + // 6. Update launch.json with Flask debug configuration + const launchJsonConfig = { + name: `Python Flask: ${projectName}`, + type: 'debugpy', + request: 'launch', + module: 'flask', + env: { + FLASK_APP: 'app.py', + FLASK_DEBUG: '1', + }, + args: ['run', '--no-debugger', '--no-reload'], + jinja: true, + }; + await manageLaunchJsonFile(destRoot, JSON.stringify(launchJsonConfig)); + + await showTextDocument(Uri.file(path.join(projectDestinationFolder, 'app.py'))); + + return createdProject; + } +} diff --git a/src/test/features/creators/newFlaskProject.unit.test.ts b/src/test/features/creators/newFlaskProject.unit.test.ts new file mode 100644 index 000000000..c62ebea5d --- /dev/null +++ b/src/test/features/creators/newFlaskProject.unit.test.ts @@ -0,0 +1,189 @@ +import assert from 'assert'; +import fsExtra from 'fs-extra'; +import * as fs from 'fs-extra'; +import * as os from 'os'; +import * as path from 'path'; +import * as sinon from 'sinon'; +import { TextEditor, Uri, WorkspaceFolder } from 'vscode'; +import { PythonEnvironment, PythonProject } from '../../../api'; +import { NEW_PROJECT_TEMPLATES_FOLDER } from '../../../common/constants'; +import * as windowApis from '../../../common/window.apis'; +import * as workspaceApis from '../../../common/workspace.apis'; +import * as creationHelpers from '../../../features/creators/creationHelpers'; +import { NewFlaskProject } from '../../../features/creators/newFlaskProject'; +import type { EnvironmentManagers } from '../../../features/envManagers'; +import type { PythonProjectManager } from '../../../features/projectManager'; + +const TEMPLATE_FOLDER = path.join( + __dirname, + '..', + '..', + '..', + '..', + 'files', + 'templates', + 'newFlaskTemplate', +); + +suite('newFlaskTemplate / NewFlaskProject', () => { + let tmpDir: string; + let workspaceFolder: WorkspaceFolder; + + setup(async () => { + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'new-flask-test-')); + workspaceFolder = { + index: 0, + name: 'test-workspace', + uri: Uri.file(tmpDir), + }; + sinon.stub(workspaceApis, 'getWorkspaceFolders').returns([workspaceFolder]); + }); + + teardown(async () => { + sinon.restore(); + await fs.remove(tmpDir); + }); + + function createMockEnvManagers(env?: PythonEnvironment): EnvironmentManagers { + return { + managers: [], + getEnvironmentManager: sinon.stub().returns({ + supportsQuickCreate: true, + create: sinon.stub().resolves(env), + }), + getEnvironment: sinon.stub().resolves(env), + setEnvironment: sinon.stub().resolves(), + } as unknown as EnvironmentManagers; + } + + function stubTemplateCopy() { + const expectedTemplateFolder = path.resolve(path.join(NEW_PROJECT_TEMPLATES_FOLDER, 'newFlaskTemplate')); + sinon.stub(fsExtra, 'pathExists').callsFake(async (checkedPath) => { + return path.resolve(String(checkedPath)) === expectedTemplateFolder; + }); + const copyStub = sinon.stub(fsExtra, 'copy').callsFake(async (_src, dest) => { + await fs.promises.cp(TEMPLATE_FOLDER, dest, { recursive: true }); + }); + const showTextDocumentStub = sinon.stub(windowApis, 'showTextDocument').resolves({} as TextEditor); + const instructionsStub = sinon.stub(creationHelpers, 'manageCopilotInstructionsFile').resolves(); + const launchJsonStub = sinon.stub(creationHelpers, 'manageLaunchJsonFile').resolves(); + return { copyStub, showTextDocumentStub, instructionsStub, launchJsonStub }; + } + + test('shipped template contains app.py, pyproject.toml, and tests/test_app.py', async () => { + assert.strictEqual(await fs.pathExists(path.join(TEMPLATE_FOLDER, 'app.py')), true); + assert.strictEqual(await fs.pathExists(path.join(TEMPLATE_FOLDER, 'pyproject.toml')), true); + assert.strictEqual(await fs.pathExists(path.join(TEMPLATE_FOLDER, 'tests', 'test_app.py')), true); + + const pyproject = await fs.readFile(path.join(TEMPLATE_FOLDER, 'pyproject.toml'), 'utf8'); + assert.ok(pyproject.includes('"flask"')); + }); + + test('interactive project name validation rejects unsafe names and accepts valid names', async () => { + const addStub = sinon.stub().resolves(); + const creator = new NewFlaskProject( + createMockEnvManagers(), + { add: addStub } as unknown as PythonProjectManager, + ); + const promptStub = sinon.stub(windowApis, 'showInputBoxWithButtons').callsFake(async (options) => { + const validateInput = options?.validateInput; + assert.ok(validateInput); + assert.strictEqual(typeof (await validateInput('../escape')), 'string'); + assert.strictEqual(typeof (await validateInput('nested/app')), 'string'); + assert.strictEqual(typeof (await validateInput('invalid name')), 'string'); + assert.strictEqual(await validateInput('my_flask_app'), null); + return undefined; + }); + + const result = await creator.create(); + + assert.strictEqual(result, undefined); + assert.ok(promptStub.calledOnce); + assert.strictEqual(addStub.called, false); + }); + + test('quick create rejects invalid project name without prompting', async () => { + const addStub = sinon.stub().resolves(); + const creator = new NewFlaskProject( + createMockEnvManagers(), + { add: addStub } as unknown as PythonProjectManager, + ); + const promptStub = sinon.stub(windowApis, 'showInputBoxWithButtons'); + + await assert.rejects( + creator.create({ + name: '../escape', + quickCreate: true, + rootUri: Uri.file(tmpDir), + }), + /path separators or traversal/, + ); + + assert.strictEqual(promptStub.called, false); + assert.strictEqual(addStub.called, false); + }); + + test('quick create copies template, replaces project_name, registers project, and opens app.py', async () => { + const rootUri = Uri.file(tmpDir); + const projectDest = path.join(tmpDir, 'my_flask_app'); + const mockEnv = { envId: { id: 'venv-1', managerId: 'venv' } } as unknown as PythonEnvironment; + const envManagers = createMockEnvManagers(mockEnv); + const addStub = sinon.stub().resolves(); + const creator = new NewFlaskProject(envManagers, { add: addStub } as unknown as PythonProjectManager); + const promptStub = sinon.stub(windowApis, 'showInputBoxWithButtons'); + const { copyStub, showTextDocumentStub, instructionsStub, launchJsonStub } = stubTemplateCopy(); + + const result = await creator.create({ + name: 'my_flask_app', + quickCreate: true, + rootUri, + }); + + assert.ok(result); + const createdProject = result as PythonProject; + assert.strictEqual(createdProject.name, 'my_flask_app'); + assert.strictEqual(createdProject.uri.fsPath, Uri.file(projectDest).fsPath); + assert.strictEqual(promptStub.called, false); + assert.ok(copyStub.calledOnce); + assert.ok(addStub.calledOnceWithExactly(createdProject)); + assert.ok((envManagers.setEnvironment as sinon.SinonStub).calledOnceWithExactly(createdProject.uri, mockEnv)); + assert.ok(instructionsStub.calledOnce); + assert.ok(launchJsonStub.calledOnce); + assert.ok(showTextDocumentStub.calledOnce); + assert.strictEqual( + showTextDocumentStub.firstCall.args[0].fsPath, + Uri.file(path.join(projectDest, 'app.py')).fsPath, + ); + + const pyproject = await fs.readFile(path.join(projectDest, 'pyproject.toml'), 'utf8'); + assert.ok(pyproject.includes('name = "my_flask_app"')); + }); + + test('aborts when destination folder already exists', async () => { + const rootUri = Uri.file(tmpDir); + const existingFolder = path.join(tmpDir, 'existing_app'); + await fs.ensureDir(existingFolder); + const expectedTemplateFolder = path.resolve(path.join(NEW_PROJECT_TEMPLATES_FOLDER, 'newFlaskTemplate')); + + sinon.stub(fsExtra, 'pathExists').callsFake(async (checkedPath) => { + const resolved = path.resolve(String(checkedPath)); + return resolved === expectedTemplateFolder || resolved === path.resolve(existingFolder); + }); + const showErrorStub = sinon.stub(windowApis, 'showErrorMessage'); + const addStub = sinon.stub().resolves(); + const creator = new NewFlaskProject( + createMockEnvManagers(), + { add: addStub } as unknown as PythonProjectManager, + ); + + const result = await creator.create({ + name: 'existing_app', + quickCreate: true, + rootUri, + }); + + assert.strictEqual(result, undefined); + assert.ok(showErrorStub.calledOnce); + assert.strictEqual(addStub.called, false); + }); +});