create-esmx
Version:
A scaffold tool for creating Esmx projects
47 lines (46 loc) • 1.8 kB
JavaScript
import { existsSync, mkdirSync } from "node:fs";
import { dirname, isAbsolute, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { cancel, confirm, isCancel } from "@clack/prompts";
import { copyTemplateFiles, isDirectoryEmpty } from "./template.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
export async function createProjectFromTemplate(targetDir, templateType, workingDir, force, variables) {
const templatePath = resolve(__dirname, "../template", templateType);
const targetPath = isAbsolute(targetDir) ? targetDir : targetDir === "." ? workingDir : resolve(workingDir, targetDir);
if (!existsSync(templatePath)) {
throw new Error(`Template "${templateType}" not found`);
}
if (targetDir !== "." && existsSync(targetPath)) {
if (!isDirectoryEmpty(targetPath)) {
if (!force) {
const shouldOverwrite = await confirm({
message: `Directory "${targetDir}" is not empty. Do you want to overwrite it?`
});
if (isCancel(shouldOverwrite)) {
cancel("Operation cancelled");
return;
}
if (!shouldOverwrite) {
throw new Error("Operation cancelled by user");
}
}
}
} else if (targetDir !== ".") {
mkdirSync(targetPath, { recursive: true });
}
if (targetDir === "." && !isDirectoryEmpty(targetPath)) {
if (!force) {
const shouldOverwrite = await confirm({
message: "Current directory is not empty. Do you want to overwrite existing files?"
});
if (isCancel(shouldOverwrite)) {
cancel("Operation cancelled");
return;
}
if (!shouldOverwrite) {
throw new Error("Operation cancelled by user");
}
}
}
copyTemplateFiles(templatePath, targetPath, variables);
}