UNPKG

mega-pkg

Version:

> This readme is written by the author of this package [amanuel](https://github.com/amanuel15)

100 lines (85 loc) 2.92 kB
const fs = require("fs"); const path = require("path"); const chalk = require("chalk"); // list of file/folder that should not be copied const SKIP_FILES = ["node_modules", ".template.json"]; const CURR_DIR = process.cwd(); function getCurrentDirectoryBase() { return process.cwd(); } function directoryExists(filePath) { return fs.existsSync(filePath); } function createProject(projectPath) { if (fs.existsSync(projectPath)) { console.log( chalk.red(`Folder ${projectPath} exists. Delete or use another name.`) ); return false; } fs.mkdirSync(projectPath); return true; } function createDirectoryContents(templatePath, projectName) { // read all files/folders (1 level) from template folder const filesToCreate = fs.readdirSync(templatePath); // loop each file/folder filesToCreate.forEach((file) => { const origFilePath = path.join(templatePath, file); // get stats about the current file const stats = fs.statSync(origFilePath); // skip files that should not be copied if (SKIP_FILES.indexOf(file) > -1) return; if (stats.isFile()) { // read file content and transform it using template engine let contents = fs.readFileSync(origFilePath, "utf8"); // write file to destination folder if (file === "index.js") { const writePath = path.join(CURR_DIR, projectName, `${projectName}.js`); fs.writeFileSync(writePath, contents, "utf8"); } else if (file === "package.json") { const newContent = contents .replace("<%= appName %>", projectName) .replace("<%= entery file %>", projectName); const writePath = path.join(CURR_DIR, projectName, file); fs.writeFileSync(writePath, newContent, "utf8"); } else { const writePath = path.join(CURR_DIR, projectName, file); fs.writeFileSync(writePath, contents, "utf8"); } } else if (stats.isDirectory()) { // create folder in destination folder fs.mkdirSync(path.join(CURR_DIR, projectName, file)); // copy files/folder inside current folder recursively createDirectoryContents( path.join(templatePath, file), path.join(projectName, file) ); } }); } function writeFile(projectName, fileName, content) { const filePath = path.join(getCurrentDirectoryBase(), projectName, fileName); fs.writeFileSync(filePath, content, "utf8"); } function createMdpDir() { if (!fs.existsSync(path.join(CURR_DIR, "mdp"))) fs.mkdirSync(path.join(CURR_DIR, "mdp")); fs.copyFileSync( path.join(CURR_DIR, "manifest.json"), path.join(CURR_DIR, "mdp", "manifest.json") ); } function getProjectName() { const manifest = fs.readFileSync(path.join(CURR_DIR, "manifest.json")); return JSON.parse(manifest).appName; } module.exports = { getCurrentDirectoryBase, directoryExists, createProject, createDirectoryContents, writeFile, createMdpDir, getProjectName, };