#!/usr/bin/env node import * as fs from 'fs'; import * as path from 'path'; import * as inquirer from 'inquirer'; import * as template from './utils/template'; import * as shell from 'shelljs' const TEMPLATES = fs.readdirSync(path.join(__dirname, 'templates')); const QUESTIONS = [ { name: 'name', type: 'input', message: 'Please input a new project name:' }, { name: 'template', type: 'list', message: 'Which project template would you like to use?', choices: TEMPLATES } ]; export interface Options { projectName: string templateName: string templatePath: string tartgetPath: string } const CURR_DIR = process.cwd(); inquirer.prompt(QUESTIONS) .then(answers => { const projectName: any = answers['name']; const projectChoice: any = answers['template']; const templatePath = path.join(__dirname, 'templates', projectChoice); const tartgetPath = path.join(CURR_DIR, projectName); const options: Options = { projectName: projectName, templateName: projectChoice, templatePath, tartgetPath } if (!createProject(tartgetPath)) { return; } createDirectoryContents(templatePath, projectName); postProcess(options); }); const createProject = (projectPath: string) => { if (fs.existsSync(projectPath)) { console.log(`Folder ${projectPath} exists. Delete or use another name.`); return false; } fs.mkdirSync(projectPath); return true; } const SKIP_FILES = ['node_modules', '.template.json']; const createDirectoryContents = (templatePath: string, folderName: string = '') => { const filesToCreate = fs.readdirSync(templatePath); filesToCreate.forEach(file => { const origFilePath = path.join(templatePath, file); // current file status const stats = fs.statSync(origFilePath); // skip files that should not be copied if (SKIP_FILES.indexOf(file) > -1) return; if (stats.isFile()) { // read content of file let contents = fs.readFileSync(origFilePath, 'utf8'); contents = template.render(contents, { folderName }); // write file to destination folder const writePath = path.join(CURR_DIR, folderName, file); fs.writeFileSync(writePath, contents, 'utf8'); } else if (stats.isDirectory()) { // create folder in destination folder fs.mkdirSync(path.join(CURR_DIR, folderName, file)); // copy files/folder inside current folder recursively createDirectoryContents(path.join(templatePath, file), path.join(folderName, file)); } }); } const postProcess = (options: Options) => { const isNode = fs.existsSync(path.join(options.templatePath, 'package.json')); if (isNode) { shell.cd(options.tartgetPath); const result = shell.exec('npm install'); if (result.code !== 0) { return false; } } return true; }