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
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Copilot Instructions for <project_name>

- The Flask project `<project_name>` is a Python Project located in the folder `<project_name>-folder`.
- You need to call the `Get Python Environment Information` tool on the `<project_name>` path to get the Python executable details.
- Substitute the Python executable you get from the `Get Python Environment Information` tool anywhere you see `<python>` in these instructions.
- Run command for `<project_name>`: `<python> -m flask --app app run`
- Command to run tests for `<project_name>`: `<python> -m pytest tests`
- In the workspace `launch.json` file, configurations related to this project have the prefix `<project_name>`.
- The project `<project_name>` has a defined `pyproject.toml` file that you should use and keep up to date.
12 changes: 12 additions & 0 deletions files/templates/newFlaskTemplate/app.py
Original file line number Diff line number Diff line change
@@ -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)
9 changes: 9 additions & 0 deletions files/templates/newFlaskTemplate/pyproject.toml
Original file line number Diff line number Diff line change
@@ -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",
]
8 changes: 8 additions & 0 deletions files/templates/newFlaskTemplate/tests/test_app.py
Original file line number Diff line number Diff line change
@@ -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
5 changes: 5 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -207,6 +208,7 @@ export async function activate(context: ExtensionContext): Promise<PythonEnviron
projectCreators.registerPythonProjectCreator(new AutoFindProjects(projectManager, envManagers)),
projectCreators.registerPythonProjectCreator(new NewPackageProject(envManagers, projectManager)),
projectCreators.registerPythonProjectCreator(new NewScriptProject(projectManager)),
projectCreators.registerPythonProjectCreator(new NewFlaskProject(envManagers, projectManager)),
);

// Silent observer for `.py` files that declare PEP 723 inline
Expand Down Expand Up @@ -594,6 +596,9 @@ export async function activate(context: ExtensionContext): Promise<PythonEnviron
if (projectType === 'python-script') {
selected = creators.find((c) => 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.`);
}
Expand Down
210 changes: 210 additions & 0 deletions src/features/creators/newFlaskProject.ts
Original file line number Diff line number Diff line change
@@ -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<PythonProject | Uri | undefined> {
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: '<project_name>', 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;
}
}
Loading