index.ts 15.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
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 { cancel, confirm, isCancel, select, text } from "@clack/prompts";

export const version = "0.0.1";
type Flags = Record<string, boolean | string>;
type JsonPrimitive = boolean | null | number | string;
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
function parseArgs(argv: string[]): Flags {
	const out: Flags = {};
	for (let i = 0; i < argv.length; i++) {
		const token = argv[i];
		if (!token || !token.startsWith("--")) continue;
		const withoutDashes = token.slice(2);
		if (withoutDashes.includes("=")) {
			const [ rawKey, rawVal ] = withoutDashes.split("=");
			if (rawKey) {
				out[rawKey.trim()] = (rawVal ?? "").trim() || true;
			}
			continue;
		}
		const key = withoutDashes.trim();
		const next = argv[i + 1];
		if (next && !next.startsWith("--")) {
			out[key] = next.trim();
			i++;
		} else {
			out[key] = true;
		}
	}
	return out;
}

function printHelp() {
	const lines = [
		"Venus CLI",
		"",
		"用法:",
		"  venus create <name> [--template react|vue] [--dir <path>] [--root <path>] [--no-install] [--router] [--store] [--ui <name>] [--eslint] [--force]",
		"  venus build",
		"  venus ls-templates",
		"",
		"选项:",
		"  --template <name>   选择模板 (react|vue),默认 react",
		"  --dir <path>        自定义生成目录前缀,最终 <dir>/<name>",
		"  --root <path>       指定作为生成根目录,默认当前工作目录",
		"  --no-install        跳过依赖安装",
		"  --router            注入路由",
		"  --store             注入状态管理",
		"  --ui <name>         注入 UI 库 (react: antd | vue: element-plus)",
		"  --eslint            注入 ESLint 配置",
		"  --force             目标目录非空时强制写入",
		"  --help, -h          显示帮助",
		"  --version, -v       显示版本",
		"",
		"默认目录策略:",
		"  react -> apps/frontend/react/<name>",
		"  vue   -> apps/frontend/vue/<name>",
	];
	console.log(lines.join("\n"));
}

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

async function ensureDir(dir: string) {
	await fsp.mkdir(dir, { recursive: true });
}

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);
		}
	}
}

async function mergeJson(targetPath: string, mergeObj: Record<string, JsonValue>) {
	const exists = fs.existsSync(targetPath);
	const targetObj: JsonValue = exists ? (JSON.parse(await fsp.readFile(targetPath, "utf8")) as JsonValue) : {};
	const merged = deepMerge(targetObj, mergeObj);
	await fsp.writeFile(targetPath, JSON.stringify(merged, null, 2));
}

function deepMerge(a: JsonValue, b: JsonValue | undefined): JsonValue {
	if (b === undefined) return a;
	if (Array.isArray(a) && Array.isArray(b)) {
		return [ ...new Set([ ...a, ...b ]) ];
	}
	if (isPlainObject(a) && isPlainObject(b)) {
		const aObj = a as Record<string, JsonValue>;
		const bObj = b as Record<string, JsonValue>;
		const out: Record<string, JsonValue> = { ...aObj };
		for (const key of Object.keys(bObj)) {
			const aValue = aObj[key];
			const bValue = bObj[key];
			if (bValue !== undefined) {
				out[key] = key in aObj && aValue !== undefined ? deepMerge(aValue, bValue) : bValue;
			}
		}
		return out;
	}
	return b;
}

function isPlainObject(v: unknown): v is Record<string, JsonValue> {
	return !!v && typeof v === "object" && !Array.isArray(v);
}

async function replacePlaceholders(destRoot: string, replacements: Record<string, string>) {
	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);
}

async function applyOptionalFeature(destRoot: string, tplRoot: string, featurePath: string) {
	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);
	}
}

interface CreateOptions {
	dir?: string;
	eslint?: boolean;
	force?: boolean;
	name: string;
	noInstall?: boolean;
	root?: string;
	router?: boolean;
	store?: boolean;
	template: string;
	ui?: string;
}

async function executeCreate(options: CreateOptions) {
	const {
		name,
		template,
		dir,
		root,
		noInstall = 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");
		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`);
			}
		} 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 (router) await applyOptionalFeature(destRoot, tplRoot, "optional/router");
	if (store) await applyOptionalFeature(destRoot, tplRoot, "optional/store");
	if (eslint) await applyOptionalFeature(destRoot, tplRoot, "optional/eslint");
	if (ui) await applyOptionalFeature(destRoot, tplRoot, path.join("optional/ui", ui));

	// 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("安装依赖中 (pnpm install)...");
		try {
			child_process.execSync("pnpm install", {
				stdio: "inherit",
				cwd: destRoot,
				shell: process.platform === "win32" ? "powershell.exe" : "/bin/sh",
			});
		} catch {
			console.warn("依赖安装失败,请手动在项目目录执行 pnpm install。");
		}
	}

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

async function runCreate(argv: string[]) {
	const name = argv[3];
	const rest = argv.slice(4);
	const flags = parseArgs(rest);
	if (!name) {
		printHelp();
		throw new Error("请输入项目名称,例如: venus create my-app --template react");
	}

	const options: CreateOptions = {
		name,
		template: String(flags.template || "react"),
		dir: typeof flags.dir === "string" ? String(flags.dir) : undefined,
		root: typeof flags.root === "string" ? String(flags.root) : undefined,
		noInstall: !!flags["no-install"],
		router: !!flags.router,
		store: !!flags.store,
		ui: typeof flags.ui === "string" ? flags.ui : undefined,
		eslint: !!flags.eslint,
		force: !!flags.force,
	};

	await executeCreate(options);
}
// 进入构建项目执行流程
async function runCreateInteractive() {
	// 步骤1: 输入项目名
	const projectName = await text({
		message: "请输入项目名称:",
		placeholder: "venus-my-app",
		validate(value) {
			if (!value || value.trim().length === 0) {
				return "项目名称不能为空";
			}
			if (!/^[a-z0-9-]+$/.test(value)) {
				return "项目名称只能包含小写字母、数字和连字符";
			}
		},
	});
	if (!projectName) {
		cancel("项目名称不能为空");
		throw new Error("项目名称不能为空");
	}
	if (isCancel(projectName)) {
		cancel("操作已取消");
		throw new Error("操作已取消");
	}

	// 步骤2: 选择模板类型
	const template = await select<string>({
		message: "请选择模板类型:",
		options: [
			{ value: "react", label: "React" },
			{ value: "vue", label: "Vue" },
		],
	});

	if (isCancel(template) || typeof template !== "string") {
		cancel("操作已取消");
		throw new Error("操作已取消");
	}

	// 步骤3: 输入构建目录
	const defaultDirPrefix =
		template === "react" ? path.join("apps", "frontend", "react") : path.join("apps", "frontend", "vue");
	const dirInput = await text({
		message: "请输入构建目录前缀:",
		placeholder: defaultDirPrefix,
		initialValue: defaultDirPrefix,
	});

	if (isCancel(dirInput)) {
		cancel("操作已取消");
		throw new Error("操作已取消");
	}

	// 步骤4: 选择是否安装依赖
	const shouldInstall = await confirm({
		message: "是否立即安装依赖?",
		initialValue: true,
	});

	if (isCancel(shouldInstall)) {
		cancel("操作已取消");
		throw new Error("操作已取消");
	}

	// 步骤5: 选择可选功能 - Router
	const hasRouter = await confirm({
		message: "是否启用路由 (Router)?",
		initialValue: false,
	});

	if (isCancel(hasRouter)) {
		cancel("操作已取消");
		throw new Error("操作已取消");
	}

	// 步骤6: 选择可选功能 - Store
	const hasStore = await confirm({
		message: "是否启用状态管理 (Store)?",
		initialValue: false,
	});

	if (isCancel(hasStore)) {
		cancel("操作已取消");
		throw new Error("操作已取消");
	}

	// 步骤7: 选择 UI 库
	const runtimeDir = path.dirname(fileURLToPath(import.meta.url));
	const tplRoot = path.resolve(runtimeDir, "../templates", template);
	const uiDir = path.join(tplRoot, "optional", "ui");
	let selectedUi: string | undefined;

	if (fs.existsSync(uiDir)) {
		const uiOptions = await fsp.readdir(uiDir, { withFileTypes: true });
		const availableUis = uiOptions.filter((u) => u.isDirectory()).map((u) => ({ value: u.name, label: u.name }));

		if (availableUis.length > 0) {
			const uiChoice = await select<string>({
				message: "请选择 UI 库 (可选):",
				options: [ { value: "", label: "不使用 UI 库" }, ...availableUis ],
			});

			if (isCancel(uiChoice) || typeof uiChoice !== "string") {
				cancel("操作已取消");
				throw new Error("操作已取消");
			}

			selectedUi = uiChoice === "" ? undefined : uiChoice;
		}
	}

	// 步骤8: 选择 ESLint
	const hasEslint = await confirm({
		message: "是否启用 ESLint?",
		initialValue: false,
	});

	if (isCancel(hasEslint)) {
		cancel("操作已取消");
		throw new Error("操作已取消");
	}

	// 执行创建
	const options: CreateOptions = {
		name: String(projectName),
		template: String(template),
		dir: dirInput ? String(dirInput) : undefined,
		noInstall: !shouldInstall,
		router: Boolean(hasRouter),
		store: Boolean(hasStore),
		ui: selectedUi,
		eslint: Boolean(hasEslint),
	};

	await executeCreate(options);
}

async function runBuild() {
	const buildScript = path.resolve(process.cwd(), "scripts/build.js");
	if (!fs.existsSync(buildScript)) {
		throw new Error("未找到 scripts/build.js,请在 Venus 仓库根目录执行该命令。");
	}
	try {
		child_process.execSync(`node ${JSON.stringify(buildScript)}`, {
			stdio: "inherit",
			shell: process.platform === "win32" ? "powershell.exe" : "/bin/sh",
		});
	} catch {
		throw new Error("构建失败");
	}
}

export async function main() {
	const cmdOrFlag = process.argv[2];
	if (!cmdOrFlag || cmdOrFlag === "--help" || cmdOrFlag === "-h") {
		printHelp();
		return;
	}
	if (cmdOrFlag === "--version" || cmdOrFlag === "-v") {
		console.log(version);
		return;
	}
	const cmd = cmdOrFlag;
	if (cmd === "create") {
		// 如果没有提供项目名,则进入交互式模式
		const name = process.argv[3];
		await (!name || name.startsWith("--") ? runCreateInteractive() : runCreate(process.argv));
		return;
	}
	if (cmd === "build") {
		await runBuild();
		return;
	}
	if (cmd === "ls-templates") {
		await runListTemplates();
		return;
	}
	console.log("可用命令: create, build");
	console.log(
		"示例: venus create my-app --template react --no-install --dir apps/customflags --router --store --ui antd --eslint",
	);
}

// 自动执行
if (process !== undefined && process.argv && process.argv[1]) {
	// 在作为 bin 执行时运行 main
	main();
}

async function runListTemplates() {
	const runtimeDir = path.dirname(fileURLToPath(import.meta.url));
	const base = path.resolve(runtimeDir, "../templates");
	if (!fs.existsSync(base)) {
		throw new Error("未找到模板目录");
	}
	const templates = await fsp.readdir(base, { withFileTypes: true });
	for (const t of templates) {
		if (!t.isDirectory()) continue;
		const name = t.name;
		const optionalDir = path.join(base, name, "optional");
		const features: string[] = [];
		if (fs.existsSync(optionalDir)) {
			const items = await fsp.readdir(optionalDir, { withFileTypes: true });
			for (const it of items) {
				if (!it.isDirectory()) continue;
				if (it.name === "ui") {
					const uiDir = path.join(optionalDir, "ui");
					if (fs.existsSync(uiDir)) {
						const uis = await fsp.readdir(uiDir, { withFileTypes: true });
						const uiNames = uis
							.filter((u) => u.isDirectory())
							.map((u) => u.name)
							.join(", ");
						features.push(`ui: [${uiNames}]`);
					}
				} else {
					features.push(it.name);
				}
			}
		}
		console.log(`- ${name}: ${features.length > 0 ? features.join("; ") : "(无可选特性)"}`);
	}
}