create.ts 7.14 KB
import type { CreateOptions, JsonValue } from "../types";

import child_process from "node:child_process";
import fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";

import { applyOptionalFeature, ensureDir, replacePlaceholders } from "../utils/file";
import { mergeJson } from "../utils/merge";
import { analyzeProjectDependencies, findWorkspaceRoot } from "../utils/workspace";

export async function executeCreate(options: CreateOptions): Promise<void> {
	const {
		name,
		template,
		dir,
		root,
		noInstall = false,
		axios = false,
		router = false,
		store = false,
		ui = "",
		eslint = false,
		force = false,
	} = options;

	const cwd = process.cwd();
	const rootDir = root ? path.resolve(cwd, root) : cwd;
	const defaultDirPrefix = (() => {
		if (template === "react") return path.join("apps", "frontend", "react");
		if (template === "vue") return path.join("apps", "frontend", "vue");
		if (template === "mobile") return path.join("apps", "frontend", "mobile");
		return "";
	})();
	const dirPrefix = dir || defaultDirPrefix;
	const destRoot = path.resolve(rootDir, dirPrefix ? path.join(dirPrefix, name) : name);

	const runtimeDir = path.dirname(fileURLToPath(import.meta.url));
	const tplRoot = path.resolve(runtimeDir, "../templates", template);

	if (!fs.existsSync(tplRoot)) {
		throw new Error(`模板不存在: ${template},路径: ${tplRoot}`);
	}

	// 非空目录保护
	if (fs.existsSync(destRoot)) {
		const stat = fs.statSync(destRoot);
		if (stat.isDirectory()) {
			const files = await fsp.readdir(destRoot);
			if (files.length > 0 && !force) {
				throw new Error(`目标目录已存在且非空: ${destRoot}。如需覆盖请添加 --force`);
			}
			if (force && files.length > 0) {
				for (const file of files) {
					if (file === "node_modules") continue;
					await fsp.rm(path.join(destRoot, file), { recursive: true, force: true });
				}
			}
		} else {
			throw new Error(`目标路径已存在且不是目录: ${destRoot}`);
		}
	}
	await ensureDir(destRoot);

	// Copy base template excluding optional directory and any stray merge manifests
	await copyDir(tplRoot, destRoot, {
		skip: (rel) => rel.startsWith("optional") || path.basename(rel) === "_package.merge.json",
	});

	// Apply optional features
	if (axios) await applyOptionalFeature(destRoot, tplRoot, "optional/axios", mergeJson);
	if (router) await applyOptionalFeature(destRoot, tplRoot, "optional/router", mergeJson);
	if (store) await applyOptionalFeature(destRoot, tplRoot, "optional/store", mergeJson);
	if (eslint) await applyOptionalFeature(destRoot, tplRoot, "optional/eslint", mergeJson);
	if (ui) await applyOptionalFeature(destRoot, tplRoot, path.join("optional/ui", ui), mergeJson);

	// Replace placeholders
	await replacePlaceholders(destRoot, { __APP_NAME__: name });

	// Update package.json name to @venus/<project-name>
	const packageJsonPath = path.join(destRoot, "package.json");
	if (fs.existsSync(packageJsonPath)) {
		const packageJson = JSON.parse(await fsp.readFile(packageJsonPath, "utf8")) as Record<string, JsonValue>;
		packageJson.name = `@venus/${name}`;
		await fsp.writeFile(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`);
	}

	if (!noInstall) {
		console.log("正在检测项目环境...");

		const workspaceRoot = findWorkspaceRoot(destRoot);
		const packageJsonPath = path.join(destRoot, "package.json");
		const dependencyAnalysis = analyzeProjectDependencies(packageJsonPath);

		if (workspaceRoot) {
			console.log(`✓ 检测到 pnpm workspace: ${workspaceRoot}`);
		} else {
			console.log(`✓ 当前目录不在 workspace 中`);
		}

		console.log(`✓ 依赖分析: ${dependencyAnalysis.hasCatalogDeps ? "包含 catalog: 依赖" : "无 catalog: 依赖"}, ${dependencyAnalysis.hasRegularDeps ? "包含常规版本依赖" : "无常规版本依赖"}`);

		// 根据依赖分析结果选择安装策略
		const installStrategies: Array<{ description: string; dir: string }> = [];

		if (workspaceRoot && dependencyAnalysis.hasCatalogDeps) {
			installStrategies.push({
				dir: workspaceRoot,
				description: "在 workspace 根目录安装(处理 catalog: 依赖)",
			});
		}

		if (dependencyAnalysis.hasRegularDeps) {
			installStrategies.push({
				dir: destRoot,
				description: dependencyAnalysis.hasCatalogDeps ? "在项目目录安装(处理常规版本依赖)" : "在项目目录安装所有依赖",
			});
		}

		// 如果没有依赖,跳过安装
		if (installStrategies.length === 0) {
			console.log("项目没有依赖,跳过安装");
		} else {
			// 执行安装策略
			for (const strategy of installStrategies) {
				console.log(`\n${strategy.description}...`);
				console.log(`安装目录: ${strategy.dir}`);

				try {
					child_process.execSync("pnpm install", {
						stdio: "inherit",
						cwd: strategy.dir,
						shell: process.platform === "win32" ? "powershell.exe" : "/bin/sh",
					});
					console.log("✓ 依赖安装完成");
				} catch {
					console.warn(`✗ 在 ${strategy.dir} 处的依赖安装失败`);
					console.warn("  请手动执行以下命令:");
					console.warn(`  cd ${strategy.dir}`);
					console.warn("  pnpm install");
				}
			}
		}
	}

	console.log(`项目创建成功: ${destRoot}`);
	console.log(`模板: ${template}`);
	console.log(
		`可选功能: axios=${axios ? "on" : "off"}, router=${router ? "on" : "off"}, store=${store ? "on" : "off"}, eslint=${eslint ? "on" : "off"}, ui=${ui || "none"}`,
	);
	console.log("下一步:");

	// 进入项目目录
	console.log(`  cd ${destRoot}`);

	// 根据安装情况提供后续命令
	if (noInstall) {
		// 如果没有自动安装,需要手动安装
		const workspaceRoot = findWorkspaceRoot(destRoot);
		const dependencyAnalysis = analyzeProjectDependencies(path.join(destRoot, "package.json"));

		if (workspaceRoot) {
			console.log(`  # 检测到 workspace: ${workspaceRoot}`);
			if (dependencyAnalysis.hasCatalogDeps) {
				console.log(`  # 项目使用 catalog: 依赖,建议在 workspace 根目录安装:`);
				console.log(`  cd ${workspaceRoot}`);
				console.log("  pnpm install");
				console.log(`  # 然后返回项目目录:`);
				console.log(`  cd ${destRoot}`);
			}
			if (dependencyAnalysis.hasRegularDeps) {
				if (dependencyAnalysis.hasCatalogDeps) {
					console.log(`  # 项目同时包含常规版本依赖,在项目目录安装:`);
				} else {
					console.log(`  # 项目使用常规版本依赖,在项目目录安装:`);
				}
				console.log("  pnpm install");
			}
		} else {
			console.log("  pnpm install");
		}
	}

	console.log("  pnpm run dev");
}

async function copyDir(src: string, dest: string, options?: { skip?: (relPath: string) => boolean }) {
	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);
		}
	}
}