index.ts 3.15 KB
import type { CreateOptions, Flags } from "./types";

import process from "node:process";

import { runBuild } from "./commands/build";
import { executeCreate } from "./commands/create";
import { runListTemplates } from "./commands/list-templates";
import { runCreateInteractive } from "./interactive/prompts";
import { parseArgs } from "./utils/args";

export const version = "0.0.1";

function printHelp() {
	const lines = [
		"Venus CLI",
		"",
		"用法:",
		"  venus create <name> [--template react|vue] [--dir <path>] [--root <path>] [--no-install] [--axios] [--router] [--store] [--ui <name>] [--eslint] [--force]",
		"  venus build",
		"  venus ls-templates",
		"",
		"选项:",
		"  --template <name>   选择模板 (react|vue),默认 react",
		"  --dir <path>        自定义生成目录前缀,最终 <dir>/<name>",
		"  --root <path>       指定作为生成根目录,默认当前工作目录",
		"  --no-install        跳过依赖安装",
		"  --axios             注入 HTTP 请求库",
		"  --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"));
}

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"],
		axios: !!flags.axios,
		router: !!flags.router,
		store: !!flags.store,
		ui: typeof flags.ui === "string" ? flags.ui : undefined,
		eslint: !!flags.eslint,
		force: !!flags.force,
	};

	await executeCreate(options);
}

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().then(executeCreate) : 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 --axios --router --store --ui antd --eslint",
	);
}

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