myex-cli
Version:
Opinionated Express.js framework with CLI tools
92 lines (78 loc) • 3.09 kB
JavaScript
import path from 'path';
import fs from 'fs-extra';
import { fileURLToPath } from 'url';
import chalk from 'chalk';
import ora from 'ora';
import { execSync } from 'child_process';
// Convert ES Module path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const templatesDir = path.resolve(__dirname, '../templates/project');
/**
* Create a new MYX project
* @param {string} projectName - Name of the project
* @param {Object} options - Command options
*/
export async function createProject(projectName, options) {
// Resolve paths
const destPath = path.join(options.directory, projectName);
// Start spinner
const spinner = ora(`Creating new MYX project: ${chalk.blue(projectName)}`).start();
try {
// Check if directory already exists
if (fs.existsSync(destPath)) {
spinner.fail(chalk.red(`Directory ${destPath} already exists. Please choose a different name.`));
return;
}
// Copy template files
spinner.text = 'Copying project template...';
await fs.copy(templatesDir, destPath);
// Update package.json
spinner.text = 'Configuring package.json...';
const packageJsonPath = path.join(destPath, 'package.json');
const packageJson = await fs.readJson(packageJsonPath);
packageJson.name = projectName;
await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
// Initialize git repository if needed
if (options.git) {
spinner.text = 'Initializing git repository...';
try {
execSync('git init', { cwd: destPath, stdio: 'ignore' });
// Create initial commit
execSync('git add .', { cwd: destPath, stdio: 'ignore' });
execSync('git commit -m "Initial commit from MYX CLI"', { cwd: destPath, stdio: 'ignore' });
} catch (err) {
spinner.warn(chalk.yellow('Git initialization failed. Do you have Git installed?'));
}
}
// Install dependencies if needed
if (options.install) {
spinner.text = 'Installing dependencies...';
try {
execSync('npm install', { cwd: destPath, stdio: 'ignore' });
} catch (err) {
spinner.warn(chalk.yellow('Dependencies installation failed. Please run npm install manually.'));
}
}
// Success message
spinner.succeed(chalk.green(`MYX project created successfully at ${destPath}`));
// Print next steps
console.log('');
console.log(chalk.cyan('Next steps:'));
console.log(` ${chalk.cyan('cd')} ${projectName}`);
if (!options.install) {
console.log(` ${chalk.cyan('npm install')}`);
}
console.log(` ${chalk.cyan('npm run dev')}`);
console.log('');
console.log(chalk.cyan('Generate components with:'));
console.log(` ${chalk.cyan('myx generate feature <name>')}`);
console.log('');
} catch (error) {
spinner.fail(chalk.red(`Failed to create project: ${error.message}`));
// Clean up if something goes wrong
if (fs.existsSync(destPath)) {
await fs.remove(destPath);
}
}
}