create.ts
7.14 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
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);
}
}
}