-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
498 lines (419 loc) · 14.2 KB
/
index.js
File metadata and controls
498 lines (419 loc) · 14.2 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#!/usr/bin/env node
const chalk = require('chalk');
const inquirer = require('inquirer');
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const ora = require('ora');
const figlet = require('figlet');
const questions = require('./utilities/questions');
const structures = require('./utilities/projectStructures');
// Funzione principale per gestire il menu iniziale
async function mainMenu() {
const answer = await inquirer.prompt([
{
type: 'list',
name: 'action',
message: 'What would you like to do?',
choices: [
'Create a new project ✨',
'Clone a repository from Git 🐙',
],
},
]);
if (answer.action === 'Create a new project ✨') {
await createProject();
} else if (answer.action === 'Clone a repository from Git 🐙') {
await cloneRepository();
}
}
// Funzione per clonare un repository Git
async function cloneRepository() {
try {
await checkPrerequisites(); // Verifica i prerequisiti prima di clonare
const answers = await inquirer.prompt([
{
name: 'repoUrl',
type: 'input',
message: 'Enter the URL of the repository to clone:',
validate(input) {
if (!input) {
return 'The repository URL cannot be empty.';
}
return true;
},
},
{
name: 'destination',
type: 'input',
message: 'Enter the directory where you want to clone the repository:',
default() {
return 'C:/';
},
},
]);
const { repoUrl, destination } = answers;
const folderName = path.basename(repoUrl, '.git');
const folderPath = path.join(destination, folderName);
const spinner = ora(`Cloning repository from ${repoUrl}...`).start();
exec(`git clone ${repoUrl}`, { cwd: destination }, (error) => {
spinner.stop();
if (error) {
console.error(chalk.bgRed(`Error cloning repository: ${error.message}`));
} else {
console.log(chalk.green(`Repository cloned successfully into ${folderPath}!`));
}
});
} catch (error) {
console.error(chalk.red(error.message));
}
}
function createReadme(folderPath, projectName, projectType) {
const readmeContent = `
# ${projectName}
## Description
Brief description of the project
## Installation
\`\`\`bash
pip install -r requirements.txt
\`\`\`
## Usage
[Usage instructions]
## Testing
[Testing Instructions]
## Contribute
[How to contribute to the project]
## License
[License Information]
`;
fs.writeFileSync(path.join(folderPath, 'README.md'), readmeContent);
}
// Funzione per il controllo dei prerequisiti
function checkPrerequisites() {
const spinner = ora('Checking prerequisites...').start();
return new Promise((resolve, reject) => {
// Controllo per Python
exec('python --version', (error) => {
if (error) {
spinner.stop();
console.error(chalk.bgRed('Error: Python is not installed or configured incorrectly in the PATH.'));
reject(new Error('Python not found'));
} else {
console.log('');
console.log(chalk.green('Python is configured correctly 🐍'));
// Controllo per Git
exec('git --version', (error) => {
spinner.stop();
if (error) {
console.error(chalk.bgRed('Error: Git is not installed or configured incorrectly in the PATH.'));
reject(new Error('Git not found'));
} else {
console.log(chalk.green('Git is configured correctly 🐙'));
resolve();
}
});
}
});
});
}
// Funzione per creare una licenza
function createLicense(folderPath, licenseType) {
const licenses = {
MIT: `MIT License\n\nCopyright (c) ${new Date().getFullYear()}\n\nPermission is hereby granted, free of charge...`,
GPL: `GNU GENERAL PUBLIC LICENSE\nVersion 3, 29 June 2007\n\nCopyright (C)...`,
Apache: `Apache License\nVersion 2.0, January 2004\n\nTERMS AND CONDITIONS FOR USE...`,
};
const licenseContent = licenses[licenseType];
if (!licenseContent) return;
const licensePath = path.join(folderPath, 'LICENSE');
const spinner = ora('creating LICENSE file...').start();
fs.writeFileSync(licensePath, licenseContent);
spinner.succeed(`LICENSE file (${licenseType}) created successfully! ⚖️`);
}
// Funzione per installare dipendenze
async function installDependencies(folderPath, virtualEnvName, requirementsPath, dependencies) {
const isWindows = process.platform === 'win32';
const pipPath = isWindows
? path.join(folderPath, virtualEnvName, 'Scripts', 'pip')
: path.join(folderPath, virtualEnvName, 'bin', 'pip');
let command = `"${pipPath}" install`;
if (requirementsPath) {
command += ` -r "${requirementsPath}"`;
} else if (dependencies.length > 0) {
command += ` ${dependencies.join(' ')}`;
} else {
return;
}
const spinner = ora('Installing dependencies...').start();
return new Promise((resolve, reject) => {
exec(command, { cwd: folderPath }, (error, stdout, stderr) => {
if (error) {
spinner.stop();
console.error(chalk.bgRed(`Error installing dependencies: ${stderr.trim()}`));
reject(error);
} else {
spinner.succeed('Dependencies installed successfully ⚙️');
resolve();
}
});
});
}
// Funzione per creare un file .gitignore
function createGitignore(folderPath) {
const gitignoreContent = `# Ignore virtual environments
venv/
__pycache__/
*.pyc
*.pyo
*.log
.env
`;
const gitignorePath = path.join(folderPath, '.gitignore');
const spinner = ora('creating .gitignore file...').start();
fs.writeFileSync(gitignorePath, gitignoreContent);
spinner.succeed('.gitignore file created successfully 🗑️');
}
// Funzione per inizializzare un repository Git
function initializeGitRepo(folderPath) {
const spinner = ora('Initializing the Git repository...').start();
return new Promise((resolve, reject) => {
exec('git init', { cwd: folderPath }, (error, stdout, stderr) => {
if (error) {
spinner.stop();
console.error(chalk.bgRed(`Error initializing Git: ${stderr.trim()}`));
reject(error);
} else {
spinner.succeed('Git repository initialized successfully 🐙');
resolve();
}
});
});
}
// Funzione per creare un Dockerfile
function createDockerfile(folderPath) {
const dockerfileContent = `FROM python:3.9-slim
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "main.py"]
`;
const dockerfilePath = path.join(folderPath, 'Dockerfile');
const spinner = ora('Creating Dockerfile...').start();
fs.writeFileSync(dockerfilePath, dockerfileContent);
spinner.succeed('Dockerfile successfully created 🐋');
}
// Domande interattive
async function askQuestions() {
const answers = await inquirer.prompt(questions);
return answers;
}
// Funzione modificata per chiedere se ricominciare
async function askToRestart() {
const answer = await inquirer.prompt([
{
type: 'confirm',
name: 'shouldRestart',
message: 'Setup complete! Do you want to create another project?',
default: true
}
]);
if (answer.shouldRestart) {
console.clear();
await createProject();
} else {
console.clear();
process.exit(0);
}
}
async function createProject() {
try {
await checkPrerequisites();
const {
directory,
folderName,
projectType,
createVirtualEnv,
virtualEnvName,
useRequirements,
requirementsPath,
dependencies,
addGitignore,
initializeGit,
addDockerfile,
addReadme,
license,
} = await askQuestions();
const folderPath = path.join(directory, folderName);
console.log('');
console.log(chalk.magenta('------------ BUILDING YOUR PROJECT ------------'));
if (!fs.existsSync(folderPath)) {
const spinner = ora('Creating Project folder').start();
fs.mkdirSync(folderPath, { recursive: true });
spinner.succeed('Project folder successfully created! 📂');
}
// Crea sempre la struttura delle cartelle in base al tipo di progetto
const spinner = ora('Creating project structure...').start();
try {
createProjectStructure(folderPath, projectType);
spinner.succeed('Project structure successfully created! 🗄️');
} catch (error) {
spinner.fail('Error creating project structure');
throw error;
}
// Crea README.md se richiesto
if (addReadme) {
const readmeSpinner = ora('Creating README.md...').start();
try {
createReadme(folderPath, folderName, projectType, license);
readmeSpinner.succeed('README.md created successfully 🌐');
} catch (error) {
readmeSpinner.fail('Error creating README.md');
throw error;
}
}
if (createVirtualEnv) {
const venvSpinner = ora('Creating the virtual environment...').start();
await new Promise((resolve, reject) => {
exec(`python -m venv ${virtualEnvName}`, { cwd: folderPath }, async (error) => {
if (error) {
venvSpinner.fail('Error creating virtual environment.');
reject(error);
} else {
venvSpinner.succeed('Virtual environment created successfully 🧬');
try {
await installDependencies(folderPath, virtualEnvName, requirementsPath, dependencies);
resolve();
} catch (err) {
reject(err);
}
}
});
});
}
if (addGitignore) {
createGitignore(folderPath);
}
if (initializeGit) {
await initializeGitRepo(folderPath);
}
if (addDockerfile) {
createDockerfile(folderPath);
}
if (license !== 'None') {
createLicense(folderPath, license);
}
console.log(chalk.green(figlet.textSync('Setup Complete! ✅')));
await new Promise(resolve => setTimeout(resolve, 1000));
await askToRestart();
} catch (error) {
console.error(chalk.red(error.message));
await askToRestart();
}
}
// Funzione per creare strutture di progetto specifiche
function createProjectStructure(folderPath, projectType) {
const structure = structures[projectType] || ['src', 'tests', 'docs'];
structure.forEach(item => {
const fullPath = path.join(folderPath, item);
if (item.endsWith('.py') || item.endsWith('.html') || item.endsWith('.yaml') || item.endsWith('.ipynb')) {
// Crea il file con contenuto di base
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, getTemplateContent(item, projectType));
} else {
// Crea la directory
fs.mkdirSync(fullPath, { recursive: true });
// Se è una directory che dovrebbe contenere un README, aggiungilo solo se non è 'data/raw' o 'data/processed'
if (item === 'data/raw' || item === 'data/processed') {
// Non creare README.md per queste cartelle
} else if (item.endsWith('models')) {
fs.writeFileSync(path.join(fullPath, 'README.md'),
`# ${path.basename(item)}\n\nThis directory contains ${getDirectoryDescription(item)}`);
}
}
});
}
function getTemplateContent(filename, projectType) {
const templates = {
'main.py': `#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n"""
${projectType} main module.
"""\n\ndef main():\n pass\n\nif __name__ == "__main__":\n main()`,
'cli.py': `#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"""
Command Line Interface for ${projectType}
\"""\n\nimport click\n\n@click.command()\ndef cli():\n pass\n\nif __name__ == "__main__":\n cli()`,
'__init__.py': '',
'config.py': `"""
Configuration settings for ${projectType}
"""\n\nclass Config:\n DEBUG = False\n TESTING = False\n\nclass DevelopmentConfig(Config):\n DEBUG = True`,
'base.html': `<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <title>${projectType}</title>\n</head>\n<body>\n {% block content %}{% endblock %}\n</body>\n</html>`,
'index.html': `{% extends "base.html" %}\n\n{% block content %}\n<h1>Welcome to ${projectType}</h1>\n{% endblock %}`,
};
return templates[path.basename(filename)] || '# Add your code here\n';
}
function getDirectoryDescription(dirname) {
const descriptions = {
'raw': 'the raw unprocessed data.',
'processed': 'processed data ready for analysis.',
'models': 'saved templates.',
'tests': 'the project tests.',
'docs': 'project documentation.'
};
return descriptions[path.basename(dirname)] || 'the specific files in this directory.';
}
// Funzione per creare un README completo
function createReadme(folderPath, projectName, projectType, license) {
const readmeContent = `# ${projectName}
## Description
Project ${projectType} created with CobraConfig.
## Project structure
\`\`\`
${getProjectStructure(folderPath)}
\`\`\`
## Requirements
- Python 3.x
- Virtual environment (optional)
${getDependenciesSection(folderPath)}
## Installation
1. Clone the repository
\`\`\`bash
git clone [url-repository]
cd ${projectName}
\`\`\`
2. (Optional) Create and activate a virtual environment
\`\`\`bash
python -m venv venv
source venv/bin/activate # Linux/MacOS
venv\\Scripts\\activate # Windows
\`\`\`
3. Install the dependencies
\`\`\`bash
pip install -r requirements.txt
\`\`\`
## Usage
[Add instructions for using the project here]
## Testing
[Add testing instructions here]
## Contributing
[Add guidelines to contribute to the project here]
## License
${getLicenseSection(license)}
`;
fs.writeFileSync(path.join(folderPath, 'README.md'), readmeContent);
}
function getProjectStructure(folderPath) {
// Implementa una funzione per ottenere la struttura delle cartelle
// Questo è un placeholder
return 'src/\n├── main.py\n└── ...\n';
}
function getDependenciesSection(folderPath) {
const reqPath = path.join(folderPath, 'requirements.txt');
if (fs.existsSync(reqPath)) {
return `\nDependencies (see requirements.txt):\n${fs.readFileSync(reqPath, 'utf8')}`;
}
return '';
}
function getLicenseSection(license) {
return license === 'None' ? 'This project does not yet have a license.' : `This project is under license ${license}.`;
}
console.log(chalk.cyan(figlet.textSync('CobraConfig')));
// Avvio dello script
mainMenu();