create-ex-den-kit
Version:
Create exam projects with Ex-Den-Kit
198 lines (163 loc) • 6.49 kB
JavaScript
import { Command } from 'commander';
import inquirer from 'inquirer';
import chalk from 'chalk';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import { execSync } from 'child_process';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const program = new Command();
const themes = {
bookexchange: {
name: '📚 Буквоежка',
description: 'Система обмена книгами',
config: {
name: 'Буквоежка',
admin: { login: 'admin', password: 'bookworm' }
}
},
cargo: {
name: '🚚 Грузовозофф',
description: 'Система заказа грузоперевозок',
config: {
name: 'Грузовозофф',
admin: { login: 'admin', password: 'gruzovik2024' }
}
},
courses: {
name: '🎓 Корочки.есть',
description: 'Система записи на онлайн курсы',
config: {
name: 'Корочки.есть',
admin: { login: 'admin', password: 'education' }
}
},
restaurant: {
name: '🍴 Я буду кушац',
description: 'Система бронирования столиков',
config: {
name: 'Я буду кушац',
admin: { login: 'admin', password: 'restaurant' }
}
}
};
async function createProject() {
console.log(chalk.cyan.bold('\n🚀 Ex-Den-Kit - Создание проекта для экзамена\n'));
const answers = await inquirer.prompt([
{
type: 'input',
name: 'projectName',
message: 'Название проекта:',
default: 'my-exam-project',
validate: (input) => {
if (/^[a-zA-Z0-9-_]+$/.test(input)) return true;
return 'Название может содержать только буквы, цифры, дефис и подчеркивание';
}
},
{
type: 'list',
name: 'theme',
message: 'Выберите тему:',
choices: Object.entries(themes).map(([key, theme]) => ({
name: `${theme.name} - ${theme.description}`,
value: key
}))
},
{
type: 'confirm',
name: 'installDeps',
message: 'Установить зависимости автоматически?',
default: true
}
]);
const projectPath = path.join(process.cwd(), answers.projectName);
// Проверяем, существует ли папка
if (fs.existsSync(projectPath)) {
console.log(chalk.red(`\n❌ Папка ${answers.projectName} уже существует!`));
process.exit(1);
}
console.log(chalk.yellow('\n📦 Создание структуры проекта...'));
try {
// Создаем папку проекта
fs.mkdirSync(projectPath);
// Копируем шаблоны
const templatePath = path.join(__dirname, '..', 'template');
// Копируем backend
fs.copySync(
path.join(__dirname, '..', 'backend'),
path.join(projectPath, 'backend')
);
// Копируем frontend
fs.copySync(
path.join(__dirname, '..', 'frontend'),
path.join(projectPath, 'frontend')
);
// Создаем конфигурацию темы
const themeConfig = {
selectedTheme: answers.theme,
themeName: themes[answers.theme].config.name,
admin: themes[answers.theme].config.admin
};
// Записываем конфигурацию
fs.writeFileSync(
path.join(projectPath, 'theme.config.json'),
JSON.stringify(themeConfig, null, 2)
);
// Обновляем frontend config
const frontendConfigPath = path.join(projectPath, 'frontend', 'src', 'config', 'themes.js');
let configContent = fs.readFileSync(frontendConfigPath, 'utf-8');
// Добавляем автоматический выбор темы
configContent = configContent.replace(
"return savedTheme || 'bookexchange';",
`return savedTheme || '${answers.theme}';`
);
fs.writeFileSync(frontendConfigPath, configContent);
console.log(chalk.green('✅ Структура проекта создана!'));
// Установка зависимостей
if (answers.installDeps) {
console.log(chalk.yellow('\n📦 Установка зависимостей...'));
process.chdir(projectPath);
console.log(chalk.blue('Backend...'));
process.chdir('backend');
execSync('npm install', { stdio: 'inherit' });
console.log(chalk.blue('\nFrontend...'));
process.chdir('../frontend');
execSync('npm install', { stdio: 'inherit' });
process.chdir('..');
}
// Инструкции
console.log(chalk.green.bold('\n✨ Проект успешно создан!\n'));
console.log(chalk.cyan('Выбранная тема:'), chalk.yellow(themes[answers.theme].name));
console.log(chalk.cyan('Админ доступ:'), chalk.yellow(`${themeConfig.admin.login} / ${themeConfig.admin.password}`));
console.log(chalk.white('\n📋 Дальнейшие шаги:\n'));
console.log(chalk.gray(`cd ${answers.projectName}`));
if (!answers.installDeps) {
console.log(chalk.gray('cd backend && npm install'));
console.log(chalk.gray('cd ../frontend && npm install'));
console.log(chalk.gray('cd ..'));
}
console.log(chalk.gray('\n# Настройте PostgreSQL:'));
console.log(chalk.gray('# 1. Создайте БД: CREATE DATABASE ex_den_kit;'));
console.log(chalk.gray('# 2. Настройте backend/.env'));
console.log(chalk.gray('\n# Запустите проект:'));
console.log(chalk.gray('cd backend && npm run dev'));
console.log(chalk.gray('# В новом терминале:'));
console.log(chalk.gray('cd frontend && npm run dev'));
console.log(chalk.green.bold('\n🎉 Удачи на экзамене!'));
} catch (error) {
console.error(chalk.red('❌ Ошибка при создании проекта:'), error);
// Удаляем папку при ошибке
if (fs.existsSync(projectPath)) {
fs.removeSync(projectPath);
}
process.exit(1);
}
}
program
.name('ex-den-kit')
.description('CLI для создания проекта Ex-Den-Kit')
.version('1.0.0')
.action(createProject);
program.parse();