UNPKG

@tecfancy/init

Version:
88 lines 3.18 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const path_1 = __importDefault(require("path")); const fs_extra_1 = __importDefault(require("fs-extra")); const log_1 = __importDefault(require("@tecfancy/log")); /** * Get the working directory * @param projectName project name * @returns working directory */ function getWorkingDir(projectName) { return projectName ? path_1.default.join(process.cwd(), projectName) : process.cwd(); } /** * Prompt whether to empty the existing directory * @returns {Promise<boolean>} true: empty, false: cancel */ async function emptyDirPrompt() { const inquirer = (await import("inquirer")).default; const answers = await inquirer.prompt([ { type: "confirm", name: "empty", message: "The directory is not empty, do you want to empty it?", }, ]); return answers.empty; } /** * Empty the directory * @param dirPath {string} directory path */ async function emptyDir(dirPath) { try { await fs_extra_1.default.emptyDir(dirPath); log_1.default.info("", `The directory at ${dirPath} has been emptied successfully.`); } catch (error) { log_1.default.error("", `Failed to empty the directory at ${dirPath}: ${error}`); throw new Error(`Failed to empty the directory at ${dirPath}: ${error}`); // Propagate the exception to be handled by the caller } } /** * Create a directory * @param dirPath {string} directory path */ async function mkdir(dirPath) { try { await fs_extra_1.default.mkdir(dirPath); log_1.default.info("", `The directory at ${dirPath} has been created successfully.`); } catch (error) { log_1.default.error("", `Failed to create the directory at ${dirPath}: ${error}`); throw new Error(`Failed to create the directory at ${dirPath}: ${error}`); // Propagate the exception to be handled by the caller } } /** * Create a directory if it does not exist, or empty it if it does * @param dirPath directory path * @param force whether to force emptying the directory */ async function createWorkingDir(force) { const workingDir = getWorkingDir(); if (fs_extra_1.default.existsSync(workingDir)) { // Check if the directory is not empty if (fs_extra_1.default.readdirSync(workingDir).length > 0) { let proceed = force; // If force is true, proceed without prompt if (!proceed) { // If not forcing, ask the user to confirm overwriting proceed = await emptyDirPrompt(); } if (proceed) { await emptyDir(workingDir); } else { log_1.default.info("", "Operation cancelled."); // If user chooses not to overwrite, cancel the operation } } } else { await mkdir(workingDir); // If the directory does not exist, create it } } exports.default = createWorkingDir; //# sourceMappingURL=createDir.js.map