overture-cli
Version:
CLI to scaffold Overture admin template from Gitee
144 lines (125 loc) • 3.61 kB
JavaScript
const { spawnSync } = require("child_process")
const fs = require("fs")
const path = require("path")
const minimist = require("minimist")
// 1. 解析命令行参数
const args = minimist(process.argv.slice(2), {
string: ["branch"], // 支持 --branch 参数指定分支
boolean: ["version", "help"],
alias: {
v: "version",
h: "help",
b: "branch"
},
default: {
branch: "master" // 默认使用 master 分支
}
})
// 2. 显示版本号
if (args.version) {
const pkg = require("../package.json")
console.log(`overture-cli v${pkg.version}`)
process.exit(0)
}
// 3. 显示帮助信息
if (args.help) {
console.log(`
Usage: create-overture [options] <project-name>
Options:
-v, --version 输出版本号
-h, --help 显示帮助信息
-b, --branch 指定模板分支(默认:main)
Examples:
create-overture my-project
create-overture my-project --branch dev
`)
process.exit(0)
}
// 4. 获取项目名称
const projectName = args._[0]
if (!projectName) {
console.error("\x1b[31m%s\x1b[0m", "❌ 错误:请指定项目名称")
console.log(" 用法:create-overture my-project")
process.exit(1)
}
// 5. 配置
const GITEE_REPO = "https://gitee.com/lsuipaiy/overture-template.git"
const BRANCH = args.branch
const targetDir = path.join(process.cwd(), projectName)
// 6. 检查目录是否已存在
if (fs.existsSync(targetDir)) {
console.error("\x1b[31m%s\x1b[0m", `❌ 错误:目录 ${projectName} 已存在`)
process.exit(1)
}
try {
// 7. 检查 Git 是否安装
const gitCheck = spawnSync("git", ["--version"], { stdio: "ignore" })
if (gitCheck.status !== 0) {
throw new Error(
"未找到 Git 命令,请先安装 Git:https://git-scm.com/downloads"
)
}
// 8. 克隆仓库(带 -b 参数)
console.log(
"\x1b[34m%s\x1b[0m",
`🚀 正在拉取模板:${GITEE_REPO}(分支:${BRANCH})`
)
const clone = spawnSync(
"git",
[
"clone",
"-b",
BRANCH,
"--depth",
"1", // 浅克隆,只拉取最新提交
GITEE_REPO,
targetDir
],
{
stdio: "inherit",
shell: true
}
)
if (clone.status !== 0) {
throw new Error(`Git 克隆失败:
1. 检查仓库地址是否正确
2. 确认分支 ${BRANCH} 是否存在
3. 检查网络连接是否正常
4. 尝试手动执行:git clone -b ${BRANCH} ${GITEE_REPO}`)
}
// 9. 删除 .git 目录
console.log("\x1b[34m%s\x1b[0m", "🧹 清理模板仓库信息...")
fs.rmSync(path.join(targetDir, ".git"), { recursive: true, force: true })
// 10. 自动安装依赖
console.log("\x1b[34m%s\x1b[0m", "📦 正在安装依赖...")
let pkgManager = "npm"
// 检测可用的包管理器(pnpm > yarn > npm)
if (spawnSync("pnpm", ["--version"], { stdio: "ignore" }).status === 0) {
pkgManager = "pnpm"
} else if (
spawnSync("yarn", ["--version"], { stdio: "ignore" }).status === 0
) {
pkgManager = "yarn"
}
const install = spawnSync(pkgManager, ["install"], {
cwd: targetDir,
stdio: "inherit"
})
if (install.status !== 0) {
console.warn(
"\x1b[33m%s\x1b[0m",
`⚠️ 依赖安装失败,请手动执行:cd ${projectName} && ${pkgManager} install`
)
}
// 11. 成功提示
console.log(`
\x1b[32m✅ 项目创建成功!\x1b[0m
请执行以下命令启动开发环境:
cd ${projectName}
${pkgManager} run dev
`)
} catch (err) {
console.error("\x1b[31m%s\x1b[0m", `❌ 错误:${err.message}`)
process.exit(1)
}