file.ts 2.29 KB
import fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";

export function isTextFile(file: string): boolean {
	const ext = path.extname(file).toLowerCase();
	return [ ".css", ".html", ".js", ".json", ".jsx", ".less", ".md", ".scss", ".ts", ".tsx", ".vue" ].includes(ext);
}

export async function ensureDir(dir: string): Promise<void> {
	await fsp.mkdir(dir, { recursive: true });
}

export async function copyDir(
	src: string,
	dest: string,
	options?: { skip?: (relPath: string) => boolean },
): Promise<void> {
	const entries = await fsp.readdir(src, { withFileTypes: true });
	for (const entry of entries) {
		const srcPath = path.join(src, entry.name);
		const rel = path.relative(src, srcPath);
		if (options?.skip?.(rel)) continue;
		const destPath = path.join(dest, entry.name);
		if (entry.isDirectory()) {
			await ensureDir(destPath);
			await copyDir(srcPath, destPath, options);
		} else if (entry.isFile()) {
			await ensureDir(path.dirname(destPath));
			await fsp.copyFile(srcPath, destPath);
		}
	}
}

export async function replacePlaceholders(destRoot: string, replacements: Record<string, string>): Promise<void> {
	const walk = async (dir: string) => {
		const entries = await fsp.readdir(dir, { withFileTypes: true });
		for (const entry of entries) {
			const full = path.join(dir, entry.name);
			if (entry.isDirectory()) await walk(full);
			else if (entry.isFile() && isTextFile(full)) {
				let content = await fsp.readFile(full, "utf8");
				for (const [ from, to ] of Object.entries(replacements)) {
					content = content.split(from).join(to);
				}
				await fsp.writeFile(full, content);
			}
		}
	};
	await walk(destRoot);
}

export async function applyOptionalFeature(
	destRoot: string,
	tplRoot: string,
	featurePath: string,
	mergeJson: (targetPath: string, mergeObj: Record<string, any>) => Promise<void>,
): Promise<void> {
	const src = path.join(tplRoot, featurePath);
	if (!fs.existsSync(src)) return;
	// Copy files excluding merge manifest
	await copyDir(src, destRoot, {
		skip: (rel) => rel.endsWith("_package.merge.json"),
	});
	const mergeFile = path.join(src, "_package.merge.json");
	if (fs.existsSync(mergeFile)) {
		const mergeObj = JSON.parse(await fsp.readFile(mergeFile, "utf8"));
		await mergeJson(path.join(destRoot, "package.json"), mergeObj);
	}
}