forked from microsoft/vscode-python-environments
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewPackageProject.ts
More file actions
184 lines (171 loc) · 8.72 KB
/
newPackageProject.ts
File metadata and controls
184 lines (171 loc) · 8.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import * as fs from 'fs-extra';
import * as path from 'path';
import { commands, l10n, MarkdownString, QuickInputButtons, Uri, window, workspace } from 'vscode';
import { PythonEnvironment, PythonProject, PythonProjectCreator, PythonProjectCreatorOptions } from '../../api';
import { NEW_PROJECT_TEMPLATES_FOLDER } from '../../common/constants';
import { traceError } from '../../common/logging';
import { showInputBoxWithButtons } from '../../common/window.apis';
import { EnvironmentManagers, PythonProjectManager } from '../../internal.api';
import {
isCopilotInstalled,
manageCopilotInstructionsFile,
manageLaunchJsonFile,
promptForVenv,
replaceInFilesAndNames,
} from './creationHelpers';
export class NewPackageProject implements PythonProjectCreator {
public readonly name = l10n.t('newPackage');
public readonly displayName = l10n.t('Package');
public readonly description = l10n.t('Creates a package folder in your current workspace');
public readonly tooltip = new MarkdownString(l10n.t('Create a new Python package'));
constructor(
private readonly envManagers: EnvironmentManagers,
private readonly projectManager: PythonProjectManager,
) {}
async create(options?: PythonProjectCreatorOptions): Promise<PythonProject | Uri | undefined> {
let packageName = options?.name;
let createVenv: boolean | undefined;
let createCopilotInstructions: boolean | undefined;
if (options?.quickCreate === true) {
// If quickCreate is true, we should not prompt for any input
if (!packageName) {
throw new Error('Package name is required in quickCreate mode.');
}
createVenv = true;
createCopilotInstructions = true;
} else {
//Prompt as quickCreate is false
if (!packageName) {
try {
packageName = await showInputBoxWithButtons({
prompt: l10n.t('What is the name of the package? (e.g. my_package)'),
ignoreFocusOut: true,
showBackButton: true,
validateInput: (value) => {
// following PyPI (PEP 508) rules for package names
if (!/^([a-z_]|[a-z0-9_][a-z0-9._-]*[a-z0-9_])$/i.test(value)) {
return l10n.t(
'Invalid package 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 package names cannot be a number, hyphen, or period.');
}
return null;
},
});
} catch (ex) {
if (ex === QuickInputButtons.Back) {
await commands.executeCommand('python-envs.createNewProjectFromTemplate');
}
}
if (!packageName) {
return undefined;
}
// Use helper to prompt for virtual environment creation
const callback = () => {
return this.create(options);
};
createVenv = await promptForVenv(callback);
if (createVenv === undefined) {
return undefined;
}
if (isCopilotInstalled()) {
createCopilotInstructions = true;
}
}
// 1. Copy template folder
const newPackageTemplateFolder = path.join(NEW_PROJECT_TEMPLATES_FOLDER, 'newPackageTemplate');
if (!(await fs.pathExists(newPackageTemplateFolder))) {
window.showErrorMessage(l10n.t('Template folder does not exist, aborting creation.'));
return undefined;
}
// Check if the destination folder is provided, otherwise use the first workspace folder
let destRoot = options?.rootUri.fsPath;
if (!destRoot) {
const workspaceFolders = workspace.workspaceFolders;
if (!workspaceFolders || workspaceFolders.length === 0) {
window.showErrorMessage(l10n.t('No workspace folder is open or provided, aborting creation.'));
traceError(`Template file not found at: ${newPackageTemplateFolder}`);
return undefined;
}
destRoot = workspaceFolders[0].uri.fsPath;
}
// Check if the destination folder already exists
const projectDestinationFolder = path.join(destRoot, `${packageName}_project`);
if (await fs.pathExists(projectDestinationFolder)) {
window.showErrorMessage(
l10n.t(
'A project folder by that name already exists, aborting creation. Please retry with a unique package name given your workspace.',
),
);
return undefined;
}
await fs.copy(newPackageTemplateFolder, projectDestinationFolder);
// 2. Replace 'package_name' in all files and file/folder names using a helper
await replaceInFilesAndNames(projectDestinationFolder, 'package_name', packageName);
const createdPackage: PythonProject | undefined = {
name: packageName,
uri: Uri.file(projectDestinationFolder),
};
// add package to list of packages
this.projectManager.add(createdPackage);
// 4. Create virtual environment if requested
let createdEnv: PythonEnvironment | undefined;
if (createVenv) {
// gets default environment manager
const en = this.envManagers.getEnvironmentManager(undefined);
if (en?.supportsQuickCreate) {
// opt to use quickCreate if available
createdEnv = await en.create(Uri.file(projectDestinationFolder), { quickCreate: true });
} else if (!options?.quickCreate && en?.supportsCreate) {
// if quickCreate unavailable, use create method only if project is not quickCreate
createdEnv = await en.create(Uri.file(projectDestinationFolder), {});
} else {
// get venv manager or any manager that supports quick creating environments
const venvManager = this.envManagers.managers.find(
(m) => m.id === 'ms-python.python:venv' || m.supportsQuickCreate,
);
if (venvManager) {
createdEnv = await venvManager.create(Uri.file(projectDestinationFolder), {
quickCreate: true,
});
} else {
window.showErrorMessage(l10n.t('Creating virtual environment failed during package creation.'));
}
}
}
// 5. Get the Python environment for the destination folder if not already created
createdEnv = createdEnv || (await this.envManagers.getEnvironment(Uri.parse(projectDestinationFolder)));
if (!createdEnv) {
window.showErrorMessage(
l10n.t('Project created but unable to be correlated to correct Python environment.'),
);
return undefined;
}
// 6. Set the Python environment for the package
this.envManagers.setEnvironment(createdPackage?.uri, createdEnv);
// 7. add custom github copilot instructions
if (createCopilotInstructions) {
const packageInstructionsPath = path.join(
NEW_PROJECT_TEMPLATES_FOLDER,
'copilot-instructions-text',
'package-copilot-instructions.md',
);
await manageCopilotInstructionsFile(destRoot, packageInstructionsPath, [
{ searchValue: '<package_name>', replaceValue: packageName },
]);
}
// update launch.json file with config for the package
const launchJsonConfig = {
name: `Python Package: ${packageName}`,
type: 'debugpy',
request: 'launch',
module: packageName,
};
await manageLaunchJsonFile(destRoot, JSON.stringify(launchJsonConfig));
return createdPackage;
}
return undefined;
}
}