@icebreakers/monorepo 3.2.18 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +181 -52
- package/bin/mo.js +2 -0
- package/bin/rc.js +2 -0
- package/bin/repo.js +2 -0
- package/bin/repoctl.js +2 -0
- package/dist/cli.mjs +1067 -76
- package/dist/commands-MPDw9wMy.mjs +2501 -0
- package/dist/config-BGCo7USv.mjs +120 -0
- package/dist/create-flow-BEHRojMs.mjs +179 -0
- package/dist/index-BBxViYZd.d.mts +1049 -0
- package/dist/index.d.mts +383 -713
- package/dist/index.mjs +6 -2
- package/dist/rolldown-runtime-twds-ZHy.mjs +14 -0
- package/dist/tooling-DyUe-eiv.mjs +427 -0
- package/dist/tooling-entry.d.mts +2 -0
- package/dist/tooling-entry.mjs +2 -0
- package/dist/types-CRtyTy2K.mjs +213 -0
- package/dist/workspace-DS6LAL71.mjs +118 -0
- package/package.json +43 -34
- package/resources/skills/icebreakers-monorepo-cli/SKILL.md +12 -10
- package/resources/skills/icebreakers-monorepo-cli/references/commands.md +166 -21
- package/resources/skills/icebreakers-monorepo-cli/references/config.md +13 -9
- package/resources/skills/icebreakers-monorepo-cli/references/templates.md +30 -5
- package/tsconfig.base.json +23 -0
- package/dist/cli.cjs +0 -116
- package/dist/cli.d.cts +0 -1
- package/dist/index.cjs +0 -82
- package/dist/index.d.cts +0 -918
- package/dist/upgrade-Beo3EoFO.cjs +0 -1850
- package/dist/upgrade-tD-PPMpL.mjs +0 -1513
|
@@ -0,0 +1,2501 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-twds-ZHy.mjs";
|
|
2
|
+
import { i as getWorkspacePackages, n as getWorkspaceData, r as getWorkspacePackageSummaries } from "./workspace-DS6LAL71.mjs";
|
|
3
|
+
import { _ as isIgnorableFsError, c as devDependencies$1, d as logger, g as fs$1, i as packageDir, l as name$1, n as assetsDir, o as templatesDir, s as dependencies, t as initToolingTargets, u as version$1 } from "./types-CRtyTy2K.mjs";
|
|
4
|
+
import { a as loadMonorepoConfig, c as resolveToolingConfig, i as getMonorepoConfigCandidates, o as loadMonorepoConfigDetails, s as resolveCommandConfig } from "./config-BGCo7USv.mjs";
|
|
5
|
+
import { f as defineTsconfigConfig } from "./tooling-DyUe-eiv.mjs";
|
|
6
|
+
import gitUrlParse from "git-url-parse";
|
|
7
|
+
import { simpleGit } from "simple-git";
|
|
8
|
+
import { findWorkspaceDir } from "@pnpm/find-workspace-dir";
|
|
9
|
+
import path from "pathe";
|
|
10
|
+
import process from "node:process";
|
|
11
|
+
import { readdir } from "node:fs/promises";
|
|
12
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
13
|
+
import fs from "node:fs";
|
|
14
|
+
import path$1 from "node:path";
|
|
15
|
+
import { checkbox, ensureTemplateAssetsPrepared, getAssetTargets, getTemplateChoices, isGitignoreFile, scaffoldTemplate, shouldSkipTemplatePath, suggestTemplateKey, templateChoices, toPublishGitignorePath, toWorkspaceGitignorePath } from "@icebreakers/monorepo-templates";
|
|
16
|
+
import YAML, { isSeq, parseDocument } from "yaml";
|
|
17
|
+
import crypto from "node:crypto";
|
|
18
|
+
import os from "node:os";
|
|
19
|
+
import pc from "picocolors";
|
|
20
|
+
import { coerce, gte, minVersion, satisfies } from "semver";
|
|
21
|
+
import { parse, stringify } from "comment-json";
|
|
22
|
+
import klaw from "klaw";
|
|
23
|
+
import { Buffer } from "node:buffer";
|
|
24
|
+
//#region src/core/git.ts
|
|
25
|
+
/**
|
|
26
|
+
* 对 simple-git 的轻量封装,集中处理配置缓存与常用查询。
|
|
27
|
+
*/
|
|
28
|
+
var GitClient = class {
|
|
29
|
+
client;
|
|
30
|
+
#config;
|
|
31
|
+
constructor(options = {}) {
|
|
32
|
+
this.client = simpleGit(options);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* 读取 Git 的 config 列表,原样返回 simple-git 的结果。
|
|
36
|
+
*/
|
|
37
|
+
listConfig() {
|
|
38
|
+
return this.client.listConfig();
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* 初始化配置缓存,避免多次访问 Git 产生的性能损耗。
|
|
42
|
+
*/
|
|
43
|
+
async init() {
|
|
44
|
+
const listConfig = await this.listConfig();
|
|
45
|
+
this.#config = listConfig.all;
|
|
46
|
+
return this.#config;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* 获取缓存的配置,若未初始化则自动触发 init。
|
|
50
|
+
*/
|
|
51
|
+
async getConfig() {
|
|
52
|
+
if (this.#config) return this.#config;
|
|
53
|
+
else return await this.init();
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* 解析 remote.origin.url,返回 git-url-parse 的结构,便于获取仓库元信息。
|
|
57
|
+
*/
|
|
58
|
+
async getGitUrl() {
|
|
59
|
+
const x = (await this.getConfig())["remote.origin.url"];
|
|
60
|
+
if (typeof x === "string") return gitUrlParse(x);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* 组合 owner/name,生成常用的仓库名表达。
|
|
64
|
+
*/
|
|
65
|
+
async getRepoName() {
|
|
66
|
+
const url = await this.getGitUrl();
|
|
67
|
+
if (url) return `${url.owner}/${url.name}`;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* 从 Git 配置中提取用户信息,用于填充 package.json author 字段。
|
|
71
|
+
*/
|
|
72
|
+
async getUser() {
|
|
73
|
+
const config = await this.getConfig();
|
|
74
|
+
return {
|
|
75
|
+
name: config["user.name"],
|
|
76
|
+
email: config["user.email"]
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* 获取当前仓库的顶层目录路径。
|
|
81
|
+
*/
|
|
82
|
+
async getRepoRoot() {
|
|
83
|
+
try {
|
|
84
|
+
const root = await this.client.revparse(["--show-toplevel"]);
|
|
85
|
+
return typeof root === "string" ? root.trim() : void 0;
|
|
86
|
+
} catch {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region src/commands/ai.ts
|
|
93
|
+
const agenticSections = [
|
|
94
|
+
"目标/产物",
|
|
95
|
+
"约束(性能/风格/兼容/不可改动范围)",
|
|
96
|
+
"验收标准(要跑的命令、预期输出/文件)",
|
|
97
|
+
"仓库路径",
|
|
98
|
+
"允许操作(可/不可写文件,可运行的命令清单,可否联网)",
|
|
99
|
+
"上下文线索(日志/文件/模块/相关 issue)",
|
|
100
|
+
"里程碑(根因→设计→实现→验证)"
|
|
101
|
+
];
|
|
102
|
+
const defaultAgenticBaseDir = "agentic/prompts";
|
|
103
|
+
function renderMarkdownTemplate() {
|
|
104
|
+
return `${agenticSections.map((title) => `## ${title}\n- `).join("\n\n")}\n`;
|
|
105
|
+
}
|
|
106
|
+
function renderJsonTemplate() {
|
|
107
|
+
const payload = {};
|
|
108
|
+
for (const title of agenticSections) payload[title] = "";
|
|
109
|
+
return `${JSON.stringify(payload, null, 2)}\n`;
|
|
110
|
+
}
|
|
111
|
+
function createTimestampFolderName(date = /* @__PURE__ */ new Date()) {
|
|
112
|
+
const pad = (value) => value.toString().padStart(2, "0");
|
|
113
|
+
return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}-${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* 生成 Agentic 任务提示词模板,默认写入 agentic/prompts/<timestamp>/prompt.md,可自定义输出路径。
|
|
117
|
+
*/
|
|
118
|
+
async function generateAgenticTemplate(options = {}) {
|
|
119
|
+
const cwd = options.cwd ?? process.cwd();
|
|
120
|
+
const format = options.format ?? "md";
|
|
121
|
+
const baseDir = options.baseDir ?? "agentic/prompts";
|
|
122
|
+
if (format !== "md" && format !== "json") throw new Error(`不支持的模板格式:${format}`);
|
|
123
|
+
const template = format === "md" ? renderMarkdownTemplate() : renderJsonTemplate();
|
|
124
|
+
const ext = format === "json" ? "json" : "md";
|
|
125
|
+
let outputPath = options.output;
|
|
126
|
+
if (!outputPath && options.name) outputPath = path.join(baseDir, `${options.name}.${ext}`);
|
|
127
|
+
if (!outputPath) {
|
|
128
|
+
const folderName = options.folderName ?? createTimestampFolderName();
|
|
129
|
+
outputPath = path.join(baseDir, folderName, `prompt.${ext}`);
|
|
130
|
+
}
|
|
131
|
+
const targetPath = path.resolve(cwd, outputPath);
|
|
132
|
+
const targetDir = path.dirname(targetPath);
|
|
133
|
+
await fs$1.ensureDir(targetDir);
|
|
134
|
+
const exists = await fs$1.pathExists(targetPath);
|
|
135
|
+
if (exists && !options.force) throw new Error(`目标文件已存在:${path.relative(cwd, targetPath)}`);
|
|
136
|
+
await fs$1.outputFile(targetPath, template, "utf8");
|
|
137
|
+
const actionLabel = exists ? "已覆盖模板" : "已生成模板";
|
|
138
|
+
logger.success(`${actionLabel}:${path.relative(cwd, targetPath)}`);
|
|
139
|
+
return template;
|
|
140
|
+
}
|
|
141
|
+
async function loadAgenticTasks(filePath, cwd) {
|
|
142
|
+
const fullPath = path.resolve(cwd, filePath);
|
|
143
|
+
const tasks = await fs$1.readJson(fullPath);
|
|
144
|
+
if (!Array.isArray(tasks)) throw new TypeError("任务清单需要是数组");
|
|
145
|
+
return tasks;
|
|
146
|
+
}
|
|
147
|
+
async function generateAgenticTemplates(tasks, defaults = {}) {
|
|
148
|
+
const results = [];
|
|
149
|
+
for (const task of tasks) {
|
|
150
|
+
const normalized = typeof task === "string" ? {
|
|
151
|
+
...defaults,
|
|
152
|
+
name: task
|
|
153
|
+
} : {
|
|
154
|
+
...defaults,
|
|
155
|
+
...task
|
|
156
|
+
};
|
|
157
|
+
results.push(await generateAgenticTemplate(normalized));
|
|
158
|
+
}
|
|
159
|
+
return results;
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/commands/verify/index.ts
|
|
163
|
+
const zeroSha = "0".repeat(40);
|
|
164
|
+
const typecheckExtensions = new Set([
|
|
165
|
+
".ts",
|
|
166
|
+
".tsx",
|
|
167
|
+
".mts",
|
|
168
|
+
".cts",
|
|
169
|
+
".vue"
|
|
170
|
+
]);
|
|
171
|
+
const whitespacePattern = /\s+/;
|
|
172
|
+
const gitDirName = ".git";
|
|
173
|
+
const defaultWorkspaceOrder = [
|
|
174
|
+
"packages/create-icebreaker",
|
|
175
|
+
"packages/monorepo",
|
|
176
|
+
"packages/monorepo-templates",
|
|
177
|
+
"packages/repoctl",
|
|
178
|
+
"templates/cli",
|
|
179
|
+
"templates/client",
|
|
180
|
+
"templates/server",
|
|
181
|
+
"templates/tsdown",
|
|
182
|
+
"templates/vitepress",
|
|
183
|
+
"templates/vue-lib"
|
|
184
|
+
].sort((left, right) => right.length - left.length);
|
|
185
|
+
function getPackageScripts(dir, cwd) {
|
|
186
|
+
const packageJsonPath = path$1.join(cwd, dir, "package.json");
|
|
187
|
+
if (!fs.existsSync(packageJsonPath)) return {};
|
|
188
|
+
return JSON.parse(fs.readFileSync(packageJsonPath, "utf8")).scripts ?? {};
|
|
189
|
+
}
|
|
190
|
+
function getRootLevelTasksForFile(filePath) {
|
|
191
|
+
const basename = path$1.basename(filePath);
|
|
192
|
+
if (filePath.startsWith(".github/")) return [
|
|
193
|
+
"build",
|
|
194
|
+
"test",
|
|
195
|
+
"tsd"
|
|
196
|
+
];
|
|
197
|
+
if (filePath.startsWith(".husky/")) return [
|
|
198
|
+
"build",
|
|
199
|
+
"test",
|
|
200
|
+
"tsd"
|
|
201
|
+
];
|
|
202
|
+
if (filePath === "package.json" || filePath === "pnpm-lock.yaml" || filePath === "turbo.json" || filePath === "pnpm-workspace.yaml") return [
|
|
203
|
+
"build",
|
|
204
|
+
"test",
|
|
205
|
+
"tsd"
|
|
206
|
+
];
|
|
207
|
+
if (basename.startsWith("tsconfig") || filePath === "commitlint.config.ts" || filePath === "eslint.config.js" || filePath === "lint-staged.config.js" || filePath === "stylelint.config.js" || filePath === "vitest.config.ts" || filePath.startsWith("scripts/")) return [
|
|
208
|
+
"build",
|
|
209
|
+
"test",
|
|
210
|
+
"tsd"
|
|
211
|
+
];
|
|
212
|
+
return [];
|
|
213
|
+
}
|
|
214
|
+
function resolveWorkspaceDir(filePath, workspaces) {
|
|
215
|
+
const normalized = filePath.split(path$1.sep).join("/");
|
|
216
|
+
for (const workspace of workspaces) if (normalized === workspace || normalized.startsWith(`${workspace}/`)) return workspace;
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
function getChangedFilesForRange(base, head, cwd, execFile) {
|
|
220
|
+
return execFile("git", [
|
|
221
|
+
"diff",
|
|
222
|
+
"--name-only",
|
|
223
|
+
"--diff-filter=ACMR",
|
|
224
|
+
`${base}...${head}`
|
|
225
|
+
], {
|
|
226
|
+
cwd,
|
|
227
|
+
encoding: "utf8"
|
|
228
|
+
}).split("\n").filter(Boolean);
|
|
229
|
+
}
|
|
230
|
+
function getChangedFilesForNewRemote(head, cwd, execFile) {
|
|
231
|
+
return execFile("git", [
|
|
232
|
+
"diff",
|
|
233
|
+
"--name-only",
|
|
234
|
+
"--diff-filter=ACMR",
|
|
235
|
+
execFile("git", [
|
|
236
|
+
"hash-object",
|
|
237
|
+
"-t",
|
|
238
|
+
"tree",
|
|
239
|
+
"--stdin"
|
|
240
|
+
], {
|
|
241
|
+
cwd,
|
|
242
|
+
encoding: "utf8",
|
|
243
|
+
input: ""
|
|
244
|
+
}).trim(),
|
|
245
|
+
head
|
|
246
|
+
], {
|
|
247
|
+
cwd,
|
|
248
|
+
encoding: "utf8"
|
|
249
|
+
}).split("\n").filter(Boolean);
|
|
250
|
+
}
|
|
251
|
+
function runPnpmCommand(cwd, label, args, spawn) {
|
|
252
|
+
process.stdout.write(`${label}\n`);
|
|
253
|
+
const result = spawn("pnpm", args, {
|
|
254
|
+
cwd,
|
|
255
|
+
stdio: "inherit"
|
|
256
|
+
});
|
|
257
|
+
if (result.status !== 0) process.exit(result.status ?? 1);
|
|
258
|
+
}
|
|
259
|
+
function runShellCommand(cwd, label, command, spawn) {
|
|
260
|
+
process.stdout.write(`${label}\n`);
|
|
261
|
+
const result = spawn("sh", ["-lc", command], {
|
|
262
|
+
cwd,
|
|
263
|
+
stdio: "inherit"
|
|
264
|
+
});
|
|
265
|
+
if (result.status !== 0) process.exit(result.status ?? 1);
|
|
266
|
+
}
|
|
267
|
+
async function readHookStdin() {
|
|
268
|
+
if (process.stdin.isTTY) return "";
|
|
269
|
+
process.stdin.setEncoding("utf8");
|
|
270
|
+
let output = "";
|
|
271
|
+
try {
|
|
272
|
+
for await (const chunk of process.stdin) output += chunk;
|
|
273
|
+
} catch (error) {
|
|
274
|
+
if (error.code !== "EAGAIN") throw error;
|
|
275
|
+
}
|
|
276
|
+
return output.trim();
|
|
277
|
+
}
|
|
278
|
+
function hasTypecheckScript(dir) {
|
|
279
|
+
const packageJsonPath = path$1.join(dir, "package.json");
|
|
280
|
+
if (!fs.existsSync(packageJsonPath)) return false;
|
|
281
|
+
try {
|
|
282
|
+
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
|
|
283
|
+
return typeof packageJson.scripts?.typecheck === "string" && packageJson.scripts.typecheck.length > 0;
|
|
284
|
+
} catch {
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
function findRepositoryRoot(startDir) {
|
|
289
|
+
let current = path$1.resolve(startDir);
|
|
290
|
+
while (true) {
|
|
291
|
+
if (fs.existsSync(path$1.join(current, gitDirName))) return current;
|
|
292
|
+
const next = path$1.dirname(current);
|
|
293
|
+
if (next === current) return path$1.resolve(startDir);
|
|
294
|
+
current = next;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
function resolveTypecheckWorkspaceDir(filePath, cwd) {
|
|
298
|
+
const workspaceRoot = findRepositoryRoot(cwd);
|
|
299
|
+
let current = path$1.dirname(path$1.resolve(cwd, filePath));
|
|
300
|
+
while (current.startsWith(workspaceRoot)) {
|
|
301
|
+
if (current !== cwd && hasTypecheckScript(current)) return current;
|
|
302
|
+
const next = path$1.dirname(current);
|
|
303
|
+
if (next === current) break;
|
|
304
|
+
current = next;
|
|
305
|
+
}
|
|
306
|
+
return workspaceRoot;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* 执行 pre-push 校验。
|
|
310
|
+
*
|
|
311
|
+
* 该函数会根据 push 范围内的改动文件,推导需要运行的 workspace 任务:
|
|
312
|
+
* - workspace 内改动:按包执行 `build` / `test` / `tsd`
|
|
313
|
+
* - 根级配置改动:在仓库根执行 `build` / `test` / `tsd`
|
|
314
|
+
* - 无论改动范围如何,都会强制在仓库根执行整仓 `lint` 与 `typecheck`
|
|
315
|
+
*
|
|
316
|
+
* @param options pre-push 运行参数
|
|
317
|
+
* @returns Promise<void>
|
|
318
|
+
*/
|
|
319
|
+
async function verifyPrePush(options = {}) {
|
|
320
|
+
const cwd = options.cwd ?? process.cwd();
|
|
321
|
+
const execFile = options.execFile ?? execFileSync;
|
|
322
|
+
const spawn = options.spawn ?? spawnSync;
|
|
323
|
+
const workspaces = options.workspaces ?? defaultWorkspaceOrder;
|
|
324
|
+
const hookStdin = options.stdinText ?? await readHookStdin();
|
|
325
|
+
const hookLines = hookStdin.length > 0 ? hookStdin.split("\n") : [];
|
|
326
|
+
const tasksByWorkspace = /* @__PURE__ */ new Map();
|
|
327
|
+
const rootTasks = new Set(["lint", "typecheck"]);
|
|
328
|
+
for (const line of hookLines) {
|
|
329
|
+
const [, localSha, , remoteSha] = line.trim().split(whitespacePattern);
|
|
330
|
+
if (!localSha || localSha === zeroSha) continue;
|
|
331
|
+
const changedFiles = remoteSha && remoteSha !== zeroSha ? getChangedFilesForRange(remoteSha, localSha, cwd, execFile) : getChangedFilesForNewRemote(localSha, cwd, execFile);
|
|
332
|
+
for (const file of changedFiles) {
|
|
333
|
+
const workspace = resolveWorkspaceDir(file, workspaces);
|
|
334
|
+
if (workspace) {
|
|
335
|
+
const tasks = tasksByWorkspace.get(workspace) ?? /* @__PURE__ */ new Set();
|
|
336
|
+
tasks.add("build");
|
|
337
|
+
tasks.add("test");
|
|
338
|
+
tasks.add("tsd");
|
|
339
|
+
tasksByWorkspace.set(workspace, tasks);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
for (const task of getRootLevelTasksForFile(file)) rootTasks.add(task);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
for (const [workspace, tasks] of tasksByWorkspace) {
|
|
346
|
+
const scripts = getPackageScripts(workspace, cwd);
|
|
347
|
+
for (const task of [...tasks]) if (typeof scripts[task] !== "string" || scripts[task].length === 0) tasks.delete(task);
|
|
348
|
+
}
|
|
349
|
+
if (tasksByWorkspace.size === 0 && rootTasks.size === 0) return;
|
|
350
|
+
for (const [workspace, tasks] of [...tasksByWorkspace.entries()].sort(([left], [right]) => left.localeCompare(right))) for (const task of [
|
|
351
|
+
"build",
|
|
352
|
+
"test",
|
|
353
|
+
"tsd"
|
|
354
|
+
]) {
|
|
355
|
+
if (!tasks.has(task)) continue;
|
|
356
|
+
runPnpmCommand(cwd, `[pre-push:${task}] ${workspace}`, [
|
|
357
|
+
"--dir",
|
|
358
|
+
workspace,
|
|
359
|
+
task
|
|
360
|
+
], spawn);
|
|
361
|
+
}
|
|
362
|
+
for (const task of [
|
|
363
|
+
"lint",
|
|
364
|
+
"typecheck",
|
|
365
|
+
"build",
|
|
366
|
+
"test",
|
|
367
|
+
"tsd"
|
|
368
|
+
]) {
|
|
369
|
+
if (!rootTasks.has(task)) continue;
|
|
370
|
+
runPnpmCommand(cwd, `[pre-push:${task}] .`, [task], spawn);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* 对暂存区中涉及类型检查的文件,按最近的 workspace 归属执行 `typecheck`。
|
|
375
|
+
*
|
|
376
|
+
* 当前识别的扩展名:`.ts`、`.tsx`、`.mts`、`.cts`、`.vue`。
|
|
377
|
+
*
|
|
378
|
+
* @param stagedFiles 暂存区文件路径列表
|
|
379
|
+
* @param options 运行参数
|
|
380
|
+
*/
|
|
381
|
+
function verifyStagedTypecheck(stagedFiles, options = {}) {
|
|
382
|
+
const cwd = options.cwd ?? process.cwd();
|
|
383
|
+
const spawn = options.spawn ?? spawnSync;
|
|
384
|
+
const workspaceDirs = [...new Set(stagedFiles.filter((file) => typecheckExtensions.has(path$1.extname(file))).map((file) => resolveTypecheckWorkspaceDir(file, cwd)))];
|
|
385
|
+
if (workspaceDirs.length === 0) return;
|
|
386
|
+
for (const workspaceDir of workspaceDirs) runPnpmCommand(cwd, `[lint-staged:typecheck] ${path$1.relative(cwd, workspaceDir) || "."}`, [
|
|
387
|
+
"--dir",
|
|
388
|
+
workspaceDir,
|
|
389
|
+
"typecheck"
|
|
390
|
+
], spawn);
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* 执行 commit-msg 校验。
|
|
394
|
+
*
|
|
395
|
+
* 优先读取 `tooling.husky.commitMsgCommand`;若未配置,则回退到
|
|
396
|
+
* `pnpm exec commitlint --edit <editFile>`。
|
|
397
|
+
*
|
|
398
|
+
* @param options commit-msg 运行参数
|
|
399
|
+
*/
|
|
400
|
+
async function verifyCommitMsg(options) {
|
|
401
|
+
const cwd = options.cwd ?? process.cwd();
|
|
402
|
+
const spawn = options.spawn ?? spawnSync;
|
|
403
|
+
const command = (await resolveToolingConfig(cwd)).husky?.commitMsgCommand?.replaceAll("{editFile}", options.editFile);
|
|
404
|
+
if (command) {
|
|
405
|
+
runShellCommand(cwd, `[commit-msg] ${options.editFile}`, command, spawn);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
runPnpmCommand(cwd, `[commit-msg] ${options.editFile}`, [
|
|
409
|
+
"exec",
|
|
410
|
+
"commitlint",
|
|
411
|
+
"--edit",
|
|
412
|
+
options.editFile
|
|
413
|
+
], spawn);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* 执行 pre-commit 校验。
|
|
417
|
+
*
|
|
418
|
+
* 优先读取 `tooling.husky.preCommitCommand`;若未配置,则回退到
|
|
419
|
+
* `pnpm exec lint-staged`。
|
|
420
|
+
*
|
|
421
|
+
* @param options pre-commit 运行参数
|
|
422
|
+
*/
|
|
423
|
+
async function verifyPreCommit(options = {}) {
|
|
424
|
+
const cwd = options.cwd ?? process.cwd();
|
|
425
|
+
const spawn = options.spawn ?? spawnSync;
|
|
426
|
+
const command = (await resolveToolingConfig(cwd)).husky?.preCommitCommand;
|
|
427
|
+
if (command) {
|
|
428
|
+
runShellCommand(cwd, "[pre-commit] lint-staged", command, spawn);
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
runPnpmCommand(cwd, "[pre-commit] lint-staged", ["exec", "lint-staged"], spawn);
|
|
432
|
+
}
|
|
433
|
+
//#endregion
|
|
434
|
+
//#region src/commands/check.ts
|
|
435
|
+
function resolveRecommendedCheckPlan(options) {
|
|
436
|
+
const { cwd, full, staged, editFile } = options;
|
|
437
|
+
if (editFile) return {
|
|
438
|
+
cwd,
|
|
439
|
+
mode: "commit-msg",
|
|
440
|
+
commands: [{
|
|
441
|
+
name: "commit-msg",
|
|
442
|
+
command: `repo verify commit-msg ${editFile}`,
|
|
443
|
+
description: "校验 commit message 文件是否符合提交规范。"
|
|
444
|
+
}]
|
|
445
|
+
};
|
|
446
|
+
if (full) return {
|
|
447
|
+
cwd,
|
|
448
|
+
mode: "full",
|
|
449
|
+
commands: [{
|
|
450
|
+
name: "pre-push",
|
|
451
|
+
command: "repo verify pre-push",
|
|
452
|
+
description: "执行完整 pre-push 校验,包含整仓 lint/typecheck,并按变更范围运行 build/test/tsd。"
|
|
453
|
+
}]
|
|
454
|
+
};
|
|
455
|
+
if (staged) return {
|
|
456
|
+
cwd,
|
|
457
|
+
mode: "staged",
|
|
458
|
+
commands: [{
|
|
459
|
+
name: "pre-commit",
|
|
460
|
+
command: "repo verify pre-commit",
|
|
461
|
+
description: "执行 pre-commit 校验。"
|
|
462
|
+
}, {
|
|
463
|
+
name: "staged-typecheck",
|
|
464
|
+
command: "repo verify staged-typecheck <staged files>",
|
|
465
|
+
description: "按暂存 TypeScript/Vue 文件所在 workspace 路由 typecheck。"
|
|
466
|
+
}]
|
|
467
|
+
};
|
|
468
|
+
return {
|
|
469
|
+
cwd,
|
|
470
|
+
mode: "default",
|
|
471
|
+
commands: [{
|
|
472
|
+
name: "pre-commit",
|
|
473
|
+
command: "repo verify pre-commit",
|
|
474
|
+
description: "执行默认轻量本地校验。"
|
|
475
|
+
}]
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
async function runRecommendedCheck(options) {
|
|
479
|
+
const { cwd, full, staged, editFile } = options;
|
|
480
|
+
if (editFile) {
|
|
481
|
+
await verifyCommitMsg({
|
|
482
|
+
cwd,
|
|
483
|
+
editFile
|
|
484
|
+
});
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (full) {
|
|
488
|
+
await verifyPrePush({ cwd });
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (staged) {
|
|
492
|
+
await verifyPreCommit({ cwd });
|
|
493
|
+
verifyStagedTypecheck([], { cwd });
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
await verifyPreCommit({ cwd });
|
|
497
|
+
}
|
|
498
|
+
//#endregion
|
|
499
|
+
//#region src/utils/github.ts
|
|
500
|
+
/**
|
|
501
|
+
* 将 Issue 模版里的 discussions 链接同步为当前仓库的 discussions 地址。
|
|
502
|
+
*/
|
|
503
|
+
function updateIssueTemplateConfig(source, repoName) {
|
|
504
|
+
if (!repoName) return source;
|
|
505
|
+
let doc;
|
|
506
|
+
try {
|
|
507
|
+
doc = parseDocument(source);
|
|
508
|
+
} catch {
|
|
509
|
+
return source;
|
|
510
|
+
}
|
|
511
|
+
const contactLinks = doc.get("contact_links");
|
|
512
|
+
if (!isSeq(contactLinks)) return source;
|
|
513
|
+
const nextUrl = `https://github.com/${repoName}/discussions`;
|
|
514
|
+
let changed = false;
|
|
515
|
+
contactLinks.items.forEach((_, index) => {
|
|
516
|
+
const url = doc.getIn([
|
|
517
|
+
"contact_links",
|
|
518
|
+
index,
|
|
519
|
+
"url"
|
|
520
|
+
]);
|
|
521
|
+
if (typeof url !== "string") return;
|
|
522
|
+
if (!url.includes("/discussions")) return;
|
|
523
|
+
if (url === nextUrl) return;
|
|
524
|
+
doc.setIn([
|
|
525
|
+
"contact_links",
|
|
526
|
+
index,
|
|
527
|
+
"url"
|
|
528
|
+
], nextUrl);
|
|
529
|
+
changed = true;
|
|
530
|
+
});
|
|
531
|
+
if (!changed) return source;
|
|
532
|
+
return doc.toString();
|
|
533
|
+
}
|
|
534
|
+
//#endregion
|
|
535
|
+
//#region src/utils/hash.ts
|
|
536
|
+
/**
|
|
537
|
+
* 生成给定内容的 md5 摘要。
|
|
538
|
+
*
|
|
539
|
+
* @param data 任意 `crypto.BinaryLike` 内容
|
|
540
|
+
* @returns 32 位十六进制 md5 字符串
|
|
541
|
+
*/
|
|
542
|
+
function getFileHash(data) {
|
|
543
|
+
const hashSum = crypto.createHash("md5");
|
|
544
|
+
hashSum.update(data);
|
|
545
|
+
return hashSum.digest("hex");
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* 对比两段内容的 md5,判断内容是否发生变化。
|
|
549
|
+
*
|
|
550
|
+
* @param src 当前内容
|
|
551
|
+
* @param dest 旧内容
|
|
552
|
+
* @returns 两者 md5 不一致时返回 `true`
|
|
553
|
+
*/
|
|
554
|
+
function isFileChanged(src, dest) {
|
|
555
|
+
try {
|
|
556
|
+
return getFileHash(src) !== getFileHash(dest);
|
|
557
|
+
} catch (err) {
|
|
558
|
+
logger.error("Error calculating file hash:", err);
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
//#endregion
|
|
563
|
+
//#region src/utils/object.ts
|
|
564
|
+
const arrayIndexPattern = /^\d+$/;
|
|
565
|
+
function isArrayIndex(value) {
|
|
566
|
+
return arrayIndexPattern.test(value);
|
|
567
|
+
}
|
|
568
|
+
function parsePath(input) {
|
|
569
|
+
const segments = [];
|
|
570
|
+
let current = "";
|
|
571
|
+
let escaped = false;
|
|
572
|
+
for (const char of input) {
|
|
573
|
+
if (escaped) {
|
|
574
|
+
current += char;
|
|
575
|
+
escaped = false;
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
if (char === "\\") {
|
|
579
|
+
escaped = true;
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
582
|
+
if (char === ".") {
|
|
583
|
+
segments.push(current);
|
|
584
|
+
current = "";
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
current += char;
|
|
588
|
+
}
|
|
589
|
+
segments.push(current);
|
|
590
|
+
return segments;
|
|
591
|
+
}
|
|
592
|
+
function setByPath(target, path, value) {
|
|
593
|
+
const segments = typeof path === "string" ? parsePath(path) : [...path];
|
|
594
|
+
if (!segments.length) return target;
|
|
595
|
+
let current = target;
|
|
596
|
+
for (let index = 0; index < segments.length - 1; index++) {
|
|
597
|
+
const segment = segments[index];
|
|
598
|
+
const nextSegment = segments[index + 1];
|
|
599
|
+
const key = Array.isArray(current) && isArrayIndex(segment) ? Number(segment) : segment;
|
|
600
|
+
const existing = current[key];
|
|
601
|
+
if (typeof existing !== "object" || existing === null) current[key] = isArrayIndex(nextSegment) ? [] : {};
|
|
602
|
+
current = current[key];
|
|
603
|
+
}
|
|
604
|
+
const lastSegment = segments.at(-1);
|
|
605
|
+
const lastKey = Array.isArray(current) && isArrayIndex(lastSegment) ? Number(lastSegment) : lastSegment;
|
|
606
|
+
current[lastKey] = value;
|
|
607
|
+
return target;
|
|
608
|
+
}
|
|
609
|
+
//#endregion
|
|
610
|
+
//#region src/utils/regexp.ts
|
|
611
|
+
const regexpSpecialCharacterPattern = /[|\\{}()[\]^$+*?.]/g;
|
|
612
|
+
const hyphenPattern = /-/g;
|
|
613
|
+
/**
|
|
614
|
+
* 逃逸正则表达式中所有特殊字符,避免被当做模式解析。
|
|
615
|
+
*/
|
|
616
|
+
function escapeStringRegexp(str) {
|
|
617
|
+
return str.replace(regexpSpecialCharacterPattern, "\\$&").replace(hyphenPattern, "\\x2d");
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* 判断字符串是否命中任意一个正则,用于过滤要同步的资产文件。
|
|
621
|
+
*/
|
|
622
|
+
function isMatch(str, arr) {
|
|
623
|
+
for (const reg of arr) if (reg.test(str)) return true;
|
|
624
|
+
return false;
|
|
625
|
+
}
|
|
626
|
+
//#endregion
|
|
627
|
+
//#region src/commands/skills.ts
|
|
628
|
+
/**
|
|
629
|
+
* 内置 skills 目录名称。
|
|
630
|
+
*/
|
|
631
|
+
const skillName = "icebreakers-monorepo-cli";
|
|
632
|
+
/**
|
|
633
|
+
* 当前支持的 skills 同步目标。
|
|
634
|
+
*/
|
|
635
|
+
const skillTargets = ["codex", "claude"];
|
|
636
|
+
/**
|
|
637
|
+
* 包内 skills 模板源目录。
|
|
638
|
+
*/
|
|
639
|
+
const skillSourceDir = path.join(packageDir, "resources", "skills", skillName);
|
|
640
|
+
/**
|
|
641
|
+
* 计算各个目标平台的 skills 安装路径。
|
|
642
|
+
*
|
|
643
|
+
* @param homeDir 用户 home 目录,默认取 `os.homedir()`
|
|
644
|
+
*/
|
|
645
|
+
function getSkillTargetPaths(homeDir = os.homedir()) {
|
|
646
|
+
return {
|
|
647
|
+
codex: path.join(homeDir, ".codex", "skills", skillName),
|
|
648
|
+
claude: path.join(homeDir, ".claude", "skills", skillName)
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
function normalizeTargets(values) {
|
|
652
|
+
if (!values?.length) return;
|
|
653
|
+
return [...new Set(values)];
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* 将内置 skills 同步到一个或多个目标平台目录。
|
|
657
|
+
*
|
|
658
|
+
* @param options 同步选项
|
|
659
|
+
* @returns 成功同步的目标及落盘路径列表
|
|
660
|
+
*/
|
|
661
|
+
async function syncSkills(options = {}) {
|
|
662
|
+
const cwd = options.cwd ?? process.cwd();
|
|
663
|
+
if (!await fs$1.pathExists(skillSourceDir)) {
|
|
664
|
+
const relative = path.relative(cwd, skillSourceDir);
|
|
665
|
+
throw new Error(`未找到技能目录:${relative || skillSourceDir}`);
|
|
666
|
+
}
|
|
667
|
+
let targets = normalizeTargets(options.targets);
|
|
668
|
+
if (!targets?.length) targets = normalizeTargets(await checkbox({
|
|
669
|
+
message: "请选择需要同步的技能目标",
|
|
670
|
+
choices: skillTargets.map((target) => ({
|
|
671
|
+
name: target,
|
|
672
|
+
value: target,
|
|
673
|
+
checked: true
|
|
674
|
+
}))
|
|
675
|
+
}));
|
|
676
|
+
if (!targets?.length) return [];
|
|
677
|
+
const targetPaths = getSkillTargetPaths();
|
|
678
|
+
const results = [];
|
|
679
|
+
for (const target of targets) {
|
|
680
|
+
const dest = targetPaths[target];
|
|
681
|
+
await fs$1.remove(dest);
|
|
682
|
+
await fs$1.ensureDir(path.dirname(dest));
|
|
683
|
+
await fs$1.copy(skillSourceDir, dest);
|
|
684
|
+
results.push({
|
|
685
|
+
target,
|
|
686
|
+
dest
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
return results;
|
|
690
|
+
}
|
|
691
|
+
//#endregion
|
|
692
|
+
//#region src/commands/clean.ts
|
|
693
|
+
const preferredPackageNames = ["repoctl", "@icebreakers/monorepo"];
|
|
694
|
+
function resolvePreferredToolPackageName$1(pkgJson) {
|
|
695
|
+
const devDependencies = pkgJson["devDependencies"];
|
|
696
|
+
if (!devDependencies || typeof devDependencies !== "object") return "repoctl";
|
|
697
|
+
for (const packageName of preferredPackageNames) if (Object.hasOwn(devDependencies, packageName)) return packageName;
|
|
698
|
+
return "repoctl";
|
|
699
|
+
}
|
|
700
|
+
function mergeCleanConfig(base, overrides) {
|
|
701
|
+
const normalizedBase = base ?? {};
|
|
702
|
+
if (!overrides) return normalizedBase;
|
|
703
|
+
const definedOverrides = Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== void 0));
|
|
704
|
+
return {
|
|
705
|
+
...normalizedBase,
|
|
706
|
+
...definedOverrides
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* 交互式清理被选中的包目录,同时重写根 package.json 中的 @icebreakers/monorepo 版本。
|
|
711
|
+
*/
|
|
712
|
+
async function cleanProjects(cwd, overrides) {
|
|
713
|
+
const cleanConfig = mergeCleanConfig(await resolveCommandConfig("clean", cwd), overrides);
|
|
714
|
+
const { packages, workspaceDir } = await getWorkspaceData(cwd, cleanConfig?.includePrivate ?? true ? { ignorePrivatePackage: false } : void 0);
|
|
715
|
+
const filteredPackages = packages.filter((pkg) => {
|
|
716
|
+
const name = pkg.manifest.name ?? "";
|
|
717
|
+
if (!name) return true;
|
|
718
|
+
if (!cleanConfig?.ignorePackages?.length) return true;
|
|
719
|
+
return !cleanConfig.ignorePackages.includes(name);
|
|
720
|
+
});
|
|
721
|
+
let cleanDirs = [];
|
|
722
|
+
if (cleanConfig?.autoConfirm) cleanDirs = filteredPackages.map((pkg) => pkg.rootDir);
|
|
723
|
+
else cleanDirs = await checkbox({
|
|
724
|
+
message: "请选择需要清理的目录",
|
|
725
|
+
choices: filteredPackages.map((x) => {
|
|
726
|
+
const baseChoice = {
|
|
727
|
+
name: path.relative(workspaceDir, x.rootDir),
|
|
728
|
+
value: x.rootDir,
|
|
729
|
+
checked: true
|
|
730
|
+
};
|
|
731
|
+
return x.manifest.name ? {
|
|
732
|
+
...baseChoice,
|
|
733
|
+
description: x.manifest.name
|
|
734
|
+
} : baseChoice;
|
|
735
|
+
})
|
|
736
|
+
});
|
|
737
|
+
const readmeZh = path.resolve(workspaceDir, "README.zh-CN.md");
|
|
738
|
+
const qoderDir = path.resolve(workspaceDir, ".qoder");
|
|
739
|
+
const docsPlansDir = path.resolve(workspaceDir, "docs/plans");
|
|
740
|
+
const skillTargets = Object.values(getSkillTargetPaths());
|
|
741
|
+
const candidates = [...new Set([
|
|
742
|
+
...cleanDirs.filter(Boolean),
|
|
743
|
+
readmeZh,
|
|
744
|
+
qoderDir,
|
|
745
|
+
docsPlansDir,
|
|
746
|
+
...skillTargets
|
|
747
|
+
])];
|
|
748
|
+
await Promise.all(candidates.map(async (dir) => {
|
|
749
|
+
if (await fs$1.pathExists(dir)) await fs$1.remove(dir);
|
|
750
|
+
}));
|
|
751
|
+
const name = path.resolve(workspaceDir, "package.json");
|
|
752
|
+
const pkgJson = await fs$1.readJson(name);
|
|
753
|
+
setByPath(pkgJson, `devDependencies.${resolvePreferredToolPackageName$1(pkgJson).replaceAll(".", "\\.")}`, cleanConfig?.pinnedVersion ?? "latest");
|
|
754
|
+
await fs$1.outputJson(name, pkgJson, { spaces: 2 });
|
|
755
|
+
}
|
|
756
|
+
//#endregion
|
|
757
|
+
//#region src/commands/config.ts
|
|
758
|
+
async function inspectMonorepoConfig(cwd) {
|
|
759
|
+
const { file, config } = await loadMonorepoConfigDetails(cwd);
|
|
760
|
+
return {
|
|
761
|
+
cwd,
|
|
762
|
+
file,
|
|
763
|
+
config
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
//#endregion
|
|
767
|
+
//#region src/commands/create/plan.ts
|
|
768
|
+
/**
|
|
769
|
+
* 内置模板映射表,source 指向 templates 根目录下的来源目录,target 为生成路径。
|
|
770
|
+
*/
|
|
771
|
+
const templateMap = {
|
|
772
|
+
"tsdown": {
|
|
773
|
+
source: "tsdown",
|
|
774
|
+
target: "packages/tsdown"
|
|
775
|
+
},
|
|
776
|
+
"vue-lib": {
|
|
777
|
+
source: "vue-lib",
|
|
778
|
+
target: "packages/vue-lib"
|
|
779
|
+
},
|
|
780
|
+
"hono-server": {
|
|
781
|
+
source: "server",
|
|
782
|
+
target: "apps/server"
|
|
783
|
+
},
|
|
784
|
+
"vue-hono": {
|
|
785
|
+
source: "client",
|
|
786
|
+
target: "apps/client"
|
|
787
|
+
},
|
|
788
|
+
"vitepress": {
|
|
789
|
+
source: "vitepress",
|
|
790
|
+
target: "apps/website"
|
|
791
|
+
},
|
|
792
|
+
"cli": {
|
|
793
|
+
source: "cli",
|
|
794
|
+
target: "apps/cli"
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
/**
|
|
798
|
+
* `createNewProject()` 默认使用的模板类型。
|
|
799
|
+
* @default 'tsdown'
|
|
800
|
+
*/
|
|
801
|
+
const defaultTemplate = "tsdown";
|
|
802
|
+
const baseChoices = templateChoices.map((choice) => {
|
|
803
|
+
const option = {
|
|
804
|
+
name: choice.label,
|
|
805
|
+
value: choice.key
|
|
806
|
+
};
|
|
807
|
+
if (choice.description) option.description = choice.description;
|
|
808
|
+
return option;
|
|
809
|
+
});
|
|
810
|
+
function normalizeTemplateDefinition(value) {
|
|
811
|
+
if (typeof value === "string") return {
|
|
812
|
+
source: value,
|
|
813
|
+
target: value
|
|
814
|
+
};
|
|
815
|
+
return value;
|
|
816
|
+
}
|
|
817
|
+
function formatUnknownTemplateError(template, availableTemplates) {
|
|
818
|
+
const suggestion = suggestTemplateKey(template, { keys: availableTemplates });
|
|
819
|
+
return `未知模板:${template}。${suggestion ? `你是不是想用 ${suggestion}? ` : ""}可用模板:${availableTemplates.join(", ")}`;
|
|
820
|
+
}
|
|
821
|
+
function getCreateChoices(choices) {
|
|
822
|
+
if (choices?.length) return choices;
|
|
823
|
+
return [...baseChoices];
|
|
824
|
+
}
|
|
825
|
+
function getTemplateMap(extra) {
|
|
826
|
+
const base = Object.fromEntries(Object.entries(templateMap).map(([key, value]) => [key, normalizeTemplateDefinition(value)]));
|
|
827
|
+
if (extra && Object.keys(extra).length) for (const [key, value] of Object.entries(extra)) base[key] = normalizeTemplateDefinition(value);
|
|
828
|
+
return base;
|
|
829
|
+
}
|
|
830
|
+
async function resolveCreateNewProjectPlan(options) {
|
|
831
|
+
const cwd = options?.cwd ?? process.cwd();
|
|
832
|
+
const createConfig = await resolveCommandConfig("create", cwd);
|
|
833
|
+
const renameJson = options?.renameJson ?? createConfig?.renameJson ?? false;
|
|
834
|
+
const rawName = options?.name ?? createConfig?.name;
|
|
835
|
+
const name = typeof rawName === "string" ? rawName.trim() : void 0;
|
|
836
|
+
const requestedTemplate = options?.type ?? createConfig?.type ?? createConfig?.defaultTemplate ?? "tsdown";
|
|
837
|
+
const templateDefinitions = getTemplateMap(createConfig?.templateMap);
|
|
838
|
+
const templatesRoot = createConfig?.templatesDir ? path.resolve(cwd, createConfig.templatesDir) : templatesDir;
|
|
839
|
+
const requestedTemplateName = String(requestedTemplate);
|
|
840
|
+
const availableTemplates = Object.keys(templateDefinitions).sort();
|
|
841
|
+
if (!templateDefinitions[requestedTemplateName]) throw new Error(formatUnknownTemplateError(requestedTemplateName, availableTemplates));
|
|
842
|
+
const template = requestedTemplateName;
|
|
843
|
+
const templateDefinition = templateDefinitions[template];
|
|
844
|
+
if (!templateDefinition) throw new Error(`未找到名为 ${template} 的模板,请检查 repoctl.config.ts 或 monorepo.config.ts`);
|
|
845
|
+
const sourceDir = path.join(templatesRoot, templateDefinition.source);
|
|
846
|
+
const targetName = name && name.length > 0 ? name : templateDefinition.target;
|
|
847
|
+
const targetDir = path.join(cwd, targetName);
|
|
848
|
+
const sourceJsonPath = path.resolve(sourceDir, "package.json");
|
|
849
|
+
const hasPackageJson = await fs$1.pathExists(sourceJsonPath);
|
|
850
|
+
const packageJsonFileName = renameJson ? "package.mock.json" : "package.json";
|
|
851
|
+
const packageName = name?.startsWith("@") ? name : path.basename(targetName);
|
|
852
|
+
return {
|
|
853
|
+
cwd,
|
|
854
|
+
requestedTemplate: requestedTemplateName,
|
|
855
|
+
template,
|
|
856
|
+
usedFallback: requestedTemplateName !== template,
|
|
857
|
+
sourceDir,
|
|
858
|
+
targetName,
|
|
859
|
+
targetDir,
|
|
860
|
+
targetExists: await fs$1.pathExists(targetDir),
|
|
861
|
+
renameJson,
|
|
862
|
+
hasPackageJson,
|
|
863
|
+
packageJsonFileName,
|
|
864
|
+
packageName,
|
|
865
|
+
templateDefinition
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
//#endregion
|
|
869
|
+
//#region src/commands/create/index.ts
|
|
870
|
+
const rootReferenceExtensions = new Set([
|
|
871
|
+
".cjs",
|
|
872
|
+
".cts",
|
|
873
|
+
".js",
|
|
874
|
+
".json",
|
|
875
|
+
".mjs",
|
|
876
|
+
".mts",
|
|
877
|
+
".ts"
|
|
878
|
+
]);
|
|
879
|
+
const rootReferenceReplacements = [{
|
|
880
|
+
from: "../../tsconfig.json",
|
|
881
|
+
to: "tsconfig.json"
|
|
882
|
+
}, {
|
|
883
|
+
from: "../../tooling/load-tooling-module.mjs",
|
|
884
|
+
to: "tooling/load-tooling-module.mjs"
|
|
885
|
+
}];
|
|
886
|
+
async function applyGitMetadata(pkgJson, repoDir, targetDir) {
|
|
887
|
+
try {
|
|
888
|
+
const git = new GitClient({ baseDir: repoDir });
|
|
889
|
+
const repoName = await git.getRepoName();
|
|
890
|
+
if (!repoName) return;
|
|
891
|
+
setByPath(pkgJson, ["bugs", "url"], `https://github.com/${repoName}/issues`);
|
|
892
|
+
const repository = {
|
|
893
|
+
type: "git",
|
|
894
|
+
url: `git+https://github.com/${repoName}.git`
|
|
895
|
+
};
|
|
896
|
+
const directoryBase = await git.getRepoRoot() ?? repoDir;
|
|
897
|
+
const relative = path.relative(directoryBase, targetDir);
|
|
898
|
+
if (relative && relative !== ".") repository.directory = relative.split(path.sep).join("/");
|
|
899
|
+
setByPath(pkgJson, "repository", repository);
|
|
900
|
+
const gitUser = await git.getUser();
|
|
901
|
+
if (gitUser?.name && gitUser?.email) setByPath(pkgJson, "author", `${gitUser.name} <${gitUser.email}>`);
|
|
902
|
+
} catch {}
|
|
903
|
+
}
|
|
904
|
+
function sanitizeTemplatePackageJson(pkgJson) {
|
|
905
|
+
delete pkgJson.author;
|
|
906
|
+
delete pkgJson.bugs;
|
|
907
|
+
delete pkgJson.homepage;
|
|
908
|
+
delete pkgJson.repository;
|
|
909
|
+
}
|
|
910
|
+
function normalizeRelativeSpecifier(fromDir, targetPath) {
|
|
911
|
+
const relativePath = path.relative(fromDir, targetPath).split(path.sep).join("/");
|
|
912
|
+
if (relativePath.startsWith(".")) return relativePath;
|
|
913
|
+
return `./${relativePath}`;
|
|
914
|
+
}
|
|
915
|
+
async function rewriteTemplateRootReferences(targetDir, workspaceDir) {
|
|
916
|
+
let entries;
|
|
917
|
+
try {
|
|
918
|
+
entries = await readdir(targetDir, { withFileTypes: true });
|
|
919
|
+
} catch (error) {
|
|
920
|
+
if (error.code === "ENOENT") return;
|
|
921
|
+
throw error;
|
|
922
|
+
}
|
|
923
|
+
await Promise.all(entries.map(async (entry) => {
|
|
924
|
+
const entryPath = path.join(targetDir, entry.name);
|
|
925
|
+
if (entry.isDirectory()) {
|
|
926
|
+
await rewriteTemplateRootReferences(entryPath, workspaceDir);
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
if (!entry.isFile() || !rootReferenceExtensions.has(path.extname(entry.name))) return;
|
|
930
|
+
const originalContent = await fs$1.readFile(entryPath, "utf8");
|
|
931
|
+
let nextContent = originalContent;
|
|
932
|
+
for (const replacement of rootReferenceReplacements) {
|
|
933
|
+
if (!nextContent.includes(replacement.from)) continue;
|
|
934
|
+
const targetPath = path.join(workspaceDir, replacement.to);
|
|
935
|
+
const rewrittenSpecifier = normalizeRelativeSpecifier(path.dirname(entryPath), targetPath);
|
|
936
|
+
nextContent = nextContent.replaceAll(replacement.from, rewrittenSpecifier);
|
|
937
|
+
}
|
|
938
|
+
if (nextContent !== originalContent) await fs$1.writeFile(entryPath, nextContent, "utf8");
|
|
939
|
+
}));
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* 根据模板生成一个新项目目录,并自动补写 `package.json` 常用字段。
|
|
943
|
+
*
|
|
944
|
+
* 默认行为:
|
|
945
|
+
* - 优先读取 `repoctl.config.ts -> commands.create`,兼容 `monorepo.config.ts`
|
|
946
|
+
* - 模板类型默认回退到 `'tsdown'`
|
|
947
|
+
* - 若目标目录已存在则直接抛错
|
|
948
|
+
* - 若模板包含 `package.json`,会自动写入 `name`、`version` 与 Git 仓库信息
|
|
949
|
+
*
|
|
950
|
+
* @param options 运行时覆盖项
|
|
951
|
+
* @returns Promise<void>
|
|
952
|
+
*/
|
|
953
|
+
async function createNewProject(options) {
|
|
954
|
+
const plan = await resolveCreateNewProjectPlan(options);
|
|
955
|
+
if (plan.targetExists) throw new Error(`${pc.red("目标目录已存在")}: ${path.relative(plan.cwd, plan.targetDir)}`);
|
|
956
|
+
await fs$1.ensureDir(plan.targetDir);
|
|
957
|
+
await scaffoldTemplate({
|
|
958
|
+
sourceDir: plan.sourceDir,
|
|
959
|
+
targetDir: plan.targetDir,
|
|
960
|
+
skipRootBasenames: ["package.json"]
|
|
961
|
+
});
|
|
962
|
+
await rewriteTemplateRootReferences(plan.targetDir, plan.cwd);
|
|
963
|
+
if (plan.hasPackageJson) {
|
|
964
|
+
const sourceJson = await fs$1.readJson(path.resolve(plan.sourceDir, "package.json"));
|
|
965
|
+
sanitizeTemplatePackageJson(sourceJson);
|
|
966
|
+
setByPath(sourceJson, "version", "0.0.0");
|
|
967
|
+
setByPath(sourceJson, "name", plan.packageName);
|
|
968
|
+
await applyGitMetadata(sourceJson, plan.cwd, plan.targetDir);
|
|
969
|
+
await fs$1.outputJson(path.resolve(plan.targetDir, plan.packageJsonFileName), sourceJson, { spaces: 2 });
|
|
970
|
+
}
|
|
971
|
+
logger.success(`${pc.bgGreenBright(pc.white(`[${plan.template}]`))} ${plan.targetName} 项目创建成功!`);
|
|
972
|
+
}
|
|
973
|
+
//#endregion
|
|
974
|
+
//#region src/commands/doctor.ts
|
|
975
|
+
function createCheck(check) {
|
|
976
|
+
return check;
|
|
977
|
+
}
|
|
978
|
+
function summarizeChecks(checks) {
|
|
979
|
+
return checks.reduce((summary, check) => {
|
|
980
|
+
summary[check.status] += 1;
|
|
981
|
+
return summary;
|
|
982
|
+
}, {
|
|
983
|
+
pass: 0,
|
|
984
|
+
warn: 0,
|
|
985
|
+
fail: 0
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
function resolveToolPackageName(pkgJson) {
|
|
989
|
+
return [
|
|
990
|
+
typeof pkgJson.devDependencies?.["repoctl"] === "string" ? {
|
|
991
|
+
name: "repoctl",
|
|
992
|
+
version: pkgJson.devDependencies["repoctl"]
|
|
993
|
+
} : null,
|
|
994
|
+
typeof pkgJson.devDependencies?.["@icebreakers/monorepo"] === "string" ? {
|
|
995
|
+
name: "@icebreakers/monorepo",
|
|
996
|
+
version: pkgJson.devDependencies["@icebreakers/monorepo"]
|
|
997
|
+
} : null,
|
|
998
|
+
typeof pkgJson.dependencies?.["repoctl"] === "string" ? {
|
|
999
|
+
name: "repoctl",
|
|
1000
|
+
version: pkgJson.dependencies["repoctl"]
|
|
1001
|
+
} : null,
|
|
1002
|
+
typeof pkgJson.dependencies?.["@icebreakers/monorepo"] === "string" ? {
|
|
1003
|
+
name: "@icebreakers/monorepo",
|
|
1004
|
+
version: pkgJson.dependencies["@icebreakers/monorepo"]
|
|
1005
|
+
} : null
|
|
1006
|
+
].find((value) => value !== null) ?? null;
|
|
1007
|
+
}
|
|
1008
|
+
function hasScript(pkgJson, name) {
|
|
1009
|
+
return typeof pkgJson.scripts?.[name] === "string" && pkgJson.scripts[name].length > 0;
|
|
1010
|
+
}
|
|
1011
|
+
async function runDoctor(cwd) {
|
|
1012
|
+
const workspaceDir = await findWorkspaceDir(cwd) ?? cwd;
|
|
1013
|
+
const packageJsonPath = `${workspaceDir}/package.json`;
|
|
1014
|
+
const workspaceManifestPath = `${workspaceDir}/pnpm-workspace.yaml`;
|
|
1015
|
+
const repoctlConfigPath = `${workspaceDir}/repoctl.config.ts`;
|
|
1016
|
+
const monorepoConfigPath = `${workspaceDir}/monorepo.config.ts`;
|
|
1017
|
+
const huskyPreCommitPath = `${workspaceDir}/.husky/pre-commit`;
|
|
1018
|
+
const lintStagedConfigPath = `${workspaceDir}/lint-staged.config.js`;
|
|
1019
|
+
const toolingLoaderPath = `${workspaceDir}/tooling/load-tooling-module.mjs`;
|
|
1020
|
+
const toolingEnsureBuiltPath = `${workspaceDir}/tooling/ensure-tooling-built.mjs`;
|
|
1021
|
+
const [hasPackageJson, hasWorkspaceManifest, hasRepoctlConfig, hasMonorepoConfig, hasHuskyPreCommit, hasLintStagedConfig, hasToolingLoader, hasToolingEnsureBuilt] = await Promise.all([
|
|
1022
|
+
fs$1.pathExists(packageJsonPath),
|
|
1023
|
+
fs$1.pathExists(workspaceManifestPath),
|
|
1024
|
+
fs$1.pathExists(repoctlConfigPath),
|
|
1025
|
+
fs$1.pathExists(monorepoConfigPath),
|
|
1026
|
+
fs$1.pathExists(huskyPreCommitPath),
|
|
1027
|
+
fs$1.pathExists(lintStagedConfigPath),
|
|
1028
|
+
fs$1.pathExists(toolingLoaderPath),
|
|
1029
|
+
fs$1.pathExists(toolingEnsureBuiltPath)
|
|
1030
|
+
]);
|
|
1031
|
+
const pkgJson = hasPackageJson ? await fs$1.readJson(packageJsonPath) : {};
|
|
1032
|
+
const packageCount = hasWorkspaceManifest ? (await getWorkspacePackages(workspaceDir, { ignorePrivatePackage: false })).length : 0;
|
|
1033
|
+
const checks = [hasPackageJson ? createCheck({
|
|
1034
|
+
id: "package-json",
|
|
1035
|
+
title: "package.json",
|
|
1036
|
+
status: "pass",
|
|
1037
|
+
detail: `已找到根 package.json:${packageJsonPath}`
|
|
1038
|
+
}) : createCheck({
|
|
1039
|
+
id: "package-json",
|
|
1040
|
+
title: "package.json",
|
|
1041
|
+
status: "fail",
|
|
1042
|
+
detail: "当前目录缺少根 package.json。",
|
|
1043
|
+
fix: "请在 monorepo 根目录执行命令,或先完成脚手架初始化。"
|
|
1044
|
+
}), hasWorkspaceManifest ? createCheck({
|
|
1045
|
+
id: "workspace-manifest",
|
|
1046
|
+
title: "pnpm workspace",
|
|
1047
|
+
status: "pass",
|
|
1048
|
+
detail: `已找到 pnpm workspace,当前识别到 ${packageCount} 个 workspace 包。`
|
|
1049
|
+
}) : createCheck({
|
|
1050
|
+
id: "workspace-manifest",
|
|
1051
|
+
title: "pnpm workspace",
|
|
1052
|
+
status: "fail",
|
|
1053
|
+
detail: "缺少 pnpm-workspace.yaml,当前目录不像一个完整的 pnpm monorepo 根目录。",
|
|
1054
|
+
fix: "补充 pnpm-workspace.yaml,或确认你当前就在仓库根目录。"
|
|
1055
|
+
})];
|
|
1056
|
+
const nodeRange = pkgJson.engines?.node;
|
|
1057
|
+
if (typeof nodeRange === "string" && nodeRange.length > 0) checks.push(satisfies(process.version, nodeRange) ? createCheck({
|
|
1058
|
+
id: "node-version",
|
|
1059
|
+
title: "Node 版本",
|
|
1060
|
+
status: "pass",
|
|
1061
|
+
detail: `当前 Node 版本 ${process.version} 满足要求 ${nodeRange}。`
|
|
1062
|
+
}) : createCheck({
|
|
1063
|
+
id: "node-version",
|
|
1064
|
+
title: "Node 版本",
|
|
1065
|
+
status: "fail",
|
|
1066
|
+
detail: `当前 Node 版本 ${process.version} 不满足要求 ${nodeRange}。`,
|
|
1067
|
+
fix: "切换到 package.json -> engines.node 要求的版本后再执行 install / build / check。"
|
|
1068
|
+
}));
|
|
1069
|
+
else checks.push(createCheck({
|
|
1070
|
+
id: "node-version",
|
|
1071
|
+
title: "Node 版本",
|
|
1072
|
+
status: "warn",
|
|
1073
|
+
detail: "根 package.json 未声明 engines.node,无法自动校验 Node 版本。",
|
|
1074
|
+
fix: "建议补充 package.json -> engines.node,避免团队成员使用不一致的运行时。"
|
|
1075
|
+
}));
|
|
1076
|
+
const toolPackage = resolveToolPackageName(pkgJson);
|
|
1077
|
+
checks.push(toolPackage ? createCheck({
|
|
1078
|
+
id: "tool-package",
|
|
1079
|
+
title: "repo CLI 依赖",
|
|
1080
|
+
status: "pass",
|
|
1081
|
+
detail: `已检测到 CLI 工具依赖:${toolPackage.name}@${toolPackage.version}`
|
|
1082
|
+
}) : createCheck({
|
|
1083
|
+
id: "tool-package",
|
|
1084
|
+
title: "repo CLI 依赖",
|
|
1085
|
+
status: "fail",
|
|
1086
|
+
detail: "根 package.json 中未发现 repoctl 或 @icebreakers/monorepo 依赖。",
|
|
1087
|
+
fix: "建议在 devDependencies 中安装 repoctl,或使用模板默认脚手架重新同步根配置。"
|
|
1088
|
+
}));
|
|
1089
|
+
const hasSetup = hasScript(pkgJson, "setup");
|
|
1090
|
+
const hasNew = hasScript(pkgJson, "new");
|
|
1091
|
+
const hasCheck = hasScript(pkgJson, "check");
|
|
1092
|
+
const hasDoctor = hasScript(pkgJson, "doctor");
|
|
1093
|
+
if (hasSetup && hasNew && hasCheck && hasDoctor) checks.push(createCheck({
|
|
1094
|
+
id: "root-scripts",
|
|
1095
|
+
title: "根快捷脚本",
|
|
1096
|
+
status: "pass",
|
|
1097
|
+
detail: "已检测到 setup / new / check / doctor 根脚本,可以直接使用 pnpm setup / pnpm new / pnpm check / pnpm doctor。"
|
|
1098
|
+
}));
|
|
1099
|
+
else {
|
|
1100
|
+
const missing = [
|
|
1101
|
+
!hasSetup ? "setup" : null,
|
|
1102
|
+
!hasNew ? "new" : null,
|
|
1103
|
+
!hasCheck ? "check" : null,
|
|
1104
|
+
!hasDoctor ? "doctor" : null
|
|
1105
|
+
].filter(Boolean).join(", ");
|
|
1106
|
+
checks.push(createCheck({
|
|
1107
|
+
id: "root-scripts",
|
|
1108
|
+
title: "根快捷脚本",
|
|
1109
|
+
status: "warn",
|
|
1110
|
+
detail: `缺少推荐的根脚本:${missing}。`,
|
|
1111
|
+
fix: "运行 repo upgrade 同步最新根脚本,或手动在 package.json 中补齐 setup / new / check / doctor。"
|
|
1112
|
+
}));
|
|
1113
|
+
}
|
|
1114
|
+
if (hasRepoctlConfig && hasMonorepoConfig) checks.push(createCheck({
|
|
1115
|
+
id: "config-file",
|
|
1116
|
+
title: "配置文件",
|
|
1117
|
+
status: "fail",
|
|
1118
|
+
detail: "同时存在 repoctl.config.ts 和 monorepo.config.ts,CLI 会拒绝加载。",
|
|
1119
|
+
fix: "保留一个配置文件即可,推荐只保留 repoctl.config.ts。"
|
|
1120
|
+
}));
|
|
1121
|
+
else if (hasRepoctlConfig || hasMonorepoConfig) checks.push(createCheck({
|
|
1122
|
+
id: "config-file",
|
|
1123
|
+
title: "配置文件",
|
|
1124
|
+
status: "pass",
|
|
1125
|
+
detail: `已检测到配置文件:${hasRepoctlConfig ? "repoctl.config.ts" : "monorepo.config.ts"}`
|
|
1126
|
+
}));
|
|
1127
|
+
else checks.push(createCheck({
|
|
1128
|
+
id: "config-file",
|
|
1129
|
+
title: "配置文件",
|
|
1130
|
+
status: "warn",
|
|
1131
|
+
detail: "当前仓库没有自定义配置文件,CLI 会完全使用默认行为。",
|
|
1132
|
+
fix: "如果你需要固定模板默认值、clean 规则或 upgrade 策略,建议添加 repoctl.config.ts。"
|
|
1133
|
+
}));
|
|
1134
|
+
if (hasHuskyPreCommit && hasLintStagedConfig) checks.push(createCheck({
|
|
1135
|
+
id: "commit-hooks",
|
|
1136
|
+
title: "提交链路",
|
|
1137
|
+
status: "pass",
|
|
1138
|
+
detail: "已检测到 .husky/pre-commit 与 lint-staged.config.js,提交前校验链路完整。"
|
|
1139
|
+
}));
|
|
1140
|
+
else if (hasHuskyPreCommit || hasLintStagedConfig) checks.push(createCheck({
|
|
1141
|
+
id: "commit-hooks",
|
|
1142
|
+
title: "提交链路",
|
|
1143
|
+
status: "warn",
|
|
1144
|
+
detail: "提交校验链路只配置了一半,Husky 与 lint-staged 没有同时就绪。",
|
|
1145
|
+
fix: "建议同时保留 .husky/pre-commit 与 lint-staged.config.js,或运行 repo upgrade 重新同步。"
|
|
1146
|
+
}));
|
|
1147
|
+
else checks.push(createCheck({
|
|
1148
|
+
id: "commit-hooks",
|
|
1149
|
+
title: "提交链路",
|
|
1150
|
+
status: "warn",
|
|
1151
|
+
detail: "当前仓库未检测到 Husky / lint-staged 提交校验入口。",
|
|
1152
|
+
fix: "如果你希望提交前自动做 eslint / stylelint / typecheck,建议运行 repo upgrade 或 repo init 同步默认配置。"
|
|
1153
|
+
}));
|
|
1154
|
+
if (hasToolingLoader && hasToolingEnsureBuilt) checks.push(createCheck({
|
|
1155
|
+
id: "tooling-loader",
|
|
1156
|
+
title: "根 tooling 目录",
|
|
1157
|
+
status: "pass",
|
|
1158
|
+
detail: "已检测到 tooling/load-tooling-module.mjs 与 tooling/ensure-tooling-built.mjs,模板内的 tooling wrapper 引用可正常工作。"
|
|
1159
|
+
}));
|
|
1160
|
+
else {
|
|
1161
|
+
const missing = [!hasToolingLoader ? "tooling/load-tooling-module.mjs" : null, !hasToolingEnsureBuilt ? "tooling/ensure-tooling-built.mjs" : null].filter(Boolean).join(", ");
|
|
1162
|
+
checks.push(createCheck({
|
|
1163
|
+
id: "tooling-loader",
|
|
1164
|
+
title: "根 tooling 目录",
|
|
1165
|
+
status: "warn",
|
|
1166
|
+
detail: `缺少模板依赖的根 tooling 文件:${missing}。`,
|
|
1167
|
+
fix: "建议运行 repo upgrade 同步根 tooling 目录,否则部分模板生成后的 eslint/vitest 配置可能引用到不存在的文件。"
|
|
1168
|
+
}));
|
|
1169
|
+
}
|
|
1170
|
+
return {
|
|
1171
|
+
cwd,
|
|
1172
|
+
workspaceDir,
|
|
1173
|
+
packageCount,
|
|
1174
|
+
checks,
|
|
1175
|
+
summary: summarizeChecks(checks)
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
//#endregion
|
|
1179
|
+
//#region src/commands/env.ts
|
|
1180
|
+
function readPnpmVersion() {
|
|
1181
|
+
try {
|
|
1182
|
+
return execFileSync("pnpm", ["--version"], {
|
|
1183
|
+
encoding: "utf8",
|
|
1184
|
+
stdio: [
|
|
1185
|
+
"ignore",
|
|
1186
|
+
"pipe",
|
|
1187
|
+
"ignore"
|
|
1188
|
+
]
|
|
1189
|
+
}).trim();
|
|
1190
|
+
} catch {
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
async function createEnvPathEntry(workspaceDir, targetPath) {
|
|
1195
|
+
return {
|
|
1196
|
+
path: targetPath,
|
|
1197
|
+
relativePath: path.relative(workspaceDir, targetPath) || ".",
|
|
1198
|
+
exists: await fs$1.pathExists(targetPath)
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
async function collectEnvInfo(cwd) {
|
|
1202
|
+
const workspace = await getWorkspacePackageSummaries(cwd, { ignorePrivatePackage: false });
|
|
1203
|
+
const packageJsonPath = path.join(workspace.workspaceDir, "package.json");
|
|
1204
|
+
const pkgJson = await fs$1.pathExists(packageJsonPath) ? await fs$1.readJson(packageJsonPath) : {};
|
|
1205
|
+
const pnpmVersion = readPnpmVersion();
|
|
1206
|
+
return {
|
|
1207
|
+
cwd: workspace.cwd,
|
|
1208
|
+
workspaceDir: workspace.workspaceDir,
|
|
1209
|
+
...pkgJson.packageManager ? { packageManager: pkgJson.packageManager } : {},
|
|
1210
|
+
nodeVersion: process.version,
|
|
1211
|
+
...pkgJson.engines?.node ? { nodeRange: pkgJson.engines.node } : {},
|
|
1212
|
+
...pnpmVersion ? { pnpmVersion } : {},
|
|
1213
|
+
platform: os.platform(),
|
|
1214
|
+
arch: os.arch(),
|
|
1215
|
+
packageCount: workspace.packages.length
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
async function collectEnvPaths(cwd) {
|
|
1219
|
+
const workspaceDir = await findWorkspaceDir(cwd) ?? cwd;
|
|
1220
|
+
const configCandidates = getMonorepoConfigCandidates(workspaceDir);
|
|
1221
|
+
const paths = {
|
|
1222
|
+
packageJson: path.join(workspaceDir, "package.json"),
|
|
1223
|
+
workspaceManifest: path.join(workspaceDir, "pnpm-workspace.yaml"),
|
|
1224
|
+
repoctlConfig: path.join(workspaceDir, "repoctl.config.ts"),
|
|
1225
|
+
legacyConfig: path.join(workspaceDir, "monorepo.config.ts"),
|
|
1226
|
+
toolingDir: path.join(workspaceDir, "tooling"),
|
|
1227
|
+
reportsDir: path.join(workspaceDir, "reports"),
|
|
1228
|
+
doctorReport: path.join(workspaceDir, "reports/doctor.json"),
|
|
1229
|
+
envReport: path.join(workspaceDir, "reports/env.json"),
|
|
1230
|
+
snapshotReport: path.join(workspaceDir, "reports/snapshot.json"),
|
|
1231
|
+
checkPlanReport: path.join(workspaceDir, "reports/check-plan.json")
|
|
1232
|
+
};
|
|
1233
|
+
return {
|
|
1234
|
+
cwd,
|
|
1235
|
+
workspaceDir,
|
|
1236
|
+
paths: {
|
|
1237
|
+
packageJson: await createEnvPathEntry(workspaceDir, paths.packageJson),
|
|
1238
|
+
workspaceManifest: await createEnvPathEntry(workspaceDir, paths.workspaceManifest),
|
|
1239
|
+
repoctlConfig: await createEnvPathEntry(workspaceDir, paths.repoctlConfig),
|
|
1240
|
+
repoctlConfigs: await Promise.all(configCandidates.repoctl.map((file) => createEnvPathEntry(workspaceDir, file))),
|
|
1241
|
+
legacyConfig: await createEnvPathEntry(workspaceDir, paths.legacyConfig),
|
|
1242
|
+
legacyConfigs: await Promise.all(configCandidates.monorepo.map((file) => createEnvPathEntry(workspaceDir, file))),
|
|
1243
|
+
toolingDir: await createEnvPathEntry(workspaceDir, paths.toolingDir),
|
|
1244
|
+
reportsDir: await createEnvPathEntry(workspaceDir, paths.reportsDir),
|
|
1245
|
+
doctorReport: await createEnvPathEntry(workspaceDir, paths.doctorReport),
|
|
1246
|
+
envReport: await createEnvPathEntry(workspaceDir, paths.envReport),
|
|
1247
|
+
snapshotReport: await createEnvPathEntry(workspaceDir, paths.snapshotReport),
|
|
1248
|
+
checkPlanReport: await createEnvPathEntry(workspaceDir, paths.checkPlanReport)
|
|
1249
|
+
}
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
async function collectEnvSnapshot(cwd, now = /* @__PURE__ */ new Date()) {
|
|
1253
|
+
const [env, doctor] = await Promise.all([collectEnvInfo(cwd), runDoctor(cwd)]);
|
|
1254
|
+
return {
|
|
1255
|
+
generatedAt: now.toISOString(),
|
|
1256
|
+
env,
|
|
1257
|
+
doctor,
|
|
1258
|
+
checkPlan: resolveRecommendedCheckPlan({ cwd })
|
|
1259
|
+
};
|
|
1260
|
+
}
|
|
1261
|
+
async function collectEnvSupportBundle(cwd, now = /* @__PURE__ */ new Date()) {
|
|
1262
|
+
const [env, paths, config, doctor] = await Promise.all([
|
|
1263
|
+
collectEnvInfo(cwd),
|
|
1264
|
+
collectEnvPaths(cwd),
|
|
1265
|
+
inspectMonorepoConfig(cwd),
|
|
1266
|
+
runDoctor(cwd)
|
|
1267
|
+
]);
|
|
1268
|
+
return {
|
|
1269
|
+
generatedAt: now.toISOString(),
|
|
1270
|
+
env,
|
|
1271
|
+
paths,
|
|
1272
|
+
config,
|
|
1273
|
+
doctor,
|
|
1274
|
+
checkPlan: resolveRecommendedCheckPlan({ cwd })
|
|
1275
|
+
};
|
|
1276
|
+
}
|
|
1277
|
+
//#endregion
|
|
1278
|
+
//#region src/core/context.ts
|
|
1279
|
+
/**
|
|
1280
|
+
* 构建命令执行上下文,封装常用的工作区、Git、配置等信息。
|
|
1281
|
+
*/
|
|
1282
|
+
async function createContext(cwd) {
|
|
1283
|
+
const { packages, workspaceDir } = await getWorkspaceData(cwd);
|
|
1284
|
+
const git = new GitClient({ baseDir: workspaceDir });
|
|
1285
|
+
const workspaceFilepath = path.resolve(workspaceDir, "pnpm-workspace.yaml");
|
|
1286
|
+
return {
|
|
1287
|
+
cwd,
|
|
1288
|
+
git,
|
|
1289
|
+
gitUrl: await git.getGitUrl(),
|
|
1290
|
+
gitUser: await git.getUser(),
|
|
1291
|
+
workspaceDir,
|
|
1292
|
+
workspaceFilepath,
|
|
1293
|
+
packages,
|
|
1294
|
+
config: await loadMonorepoConfig(workspaceDir)
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
//#endregion
|
|
1298
|
+
//#region src/commands/init/setChangeset.ts
|
|
1299
|
+
/**
|
|
1300
|
+
* 将 changeset 配置中的仓库地址指向当前项目,方便自动生成变更日志链接。
|
|
1301
|
+
*/
|
|
1302
|
+
async function setChangeset_default(ctx) {
|
|
1303
|
+
const { gitUrl, workspaceFilepath } = ctx;
|
|
1304
|
+
if (gitUrl && await fs$1.exists(workspaceFilepath)) {
|
|
1305
|
+
const changesetConfigPath = path.resolve(path.dirname(workspaceFilepath), ".changeset/config.json");
|
|
1306
|
+
if (await fs$1.exists(changesetConfigPath)) {
|
|
1307
|
+
const changesetConfig = await fs$1.readJson(changesetConfigPath);
|
|
1308
|
+
if (gitUrl.full_name) {
|
|
1309
|
+
setByPath(changesetConfig, "changelog.1.repo", gitUrl.full_name);
|
|
1310
|
+
await fs$1.outputJson(changesetConfigPath, changesetConfig, { spaces: 2 });
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
//#endregion
|
|
1316
|
+
//#region src/commands/init/setIssueTemplateConfig.ts
|
|
1317
|
+
/**
|
|
1318
|
+
* 同步 Issue 模版里的 discussions 链接到当前仓库。
|
|
1319
|
+
*/
|
|
1320
|
+
async function setIssueTemplateConfig_default(ctx) {
|
|
1321
|
+
const repoName = ctx.gitUrl?.full_name;
|
|
1322
|
+
if (!repoName) return;
|
|
1323
|
+
const configPath = path.resolve(ctx.cwd, ".github/ISSUE_TEMPLATE/config.yml");
|
|
1324
|
+
if (!await fs$1.pathExists(configPath)) return;
|
|
1325
|
+
const source = await fs$1.readFile(configPath, "utf8");
|
|
1326
|
+
const next = updateIssueTemplateConfig(source, repoName);
|
|
1327
|
+
if (next !== source) await fs$1.writeFile(configPath, next, "utf8");
|
|
1328
|
+
}
|
|
1329
|
+
//#endregion
|
|
1330
|
+
//#region src/commands/init/setPkgJson.ts
|
|
1331
|
+
/**
|
|
1332
|
+
* 根据当前仓库信息同步 package.json 的仓库、作者等字段。
|
|
1333
|
+
*/
|
|
1334
|
+
async function setPkgJson_default(ctx) {
|
|
1335
|
+
const { gitUrl, gitUser, packages, cwd, workspaceFilepath } = ctx;
|
|
1336
|
+
const workspaceExists = await fs$1.pathExists(workspaceFilepath);
|
|
1337
|
+
if (gitUrl && workspaceExists) await Promise.all(packages.map(async (pkg) => {
|
|
1338
|
+
if (!await fs$1.pathExists(pkg.pkgJsonPath)) return;
|
|
1339
|
+
const pkgJson = JSON.parse(JSON.stringify(pkg.manifest));
|
|
1340
|
+
const directory = path.relative(cwd, pkg.rootDir);
|
|
1341
|
+
setByPath(pkgJson, ["bugs", "url"], `https://github.com/${gitUrl.full_name}/issues`);
|
|
1342
|
+
const repository = {
|
|
1343
|
+
type: "git",
|
|
1344
|
+
url: `git+https://github.com/${gitUrl.full_name}.git`
|
|
1345
|
+
};
|
|
1346
|
+
if (directory) repository.directory = directory;
|
|
1347
|
+
setByPath(pkgJson, "repository", repository);
|
|
1348
|
+
if (gitUser?.name && gitUser?.email) setByPath(pkgJson, "author", `${gitUser.name} <${gitUser.email}>`);
|
|
1349
|
+
const nextContent = `${JSON.stringify(pkgJson, void 0, 2)}\n`;
|
|
1350
|
+
if (await fs$1.readFile(pkg.pkgJsonPath, "utf8") !== nextContent) await fs$1.writeFile(pkg.pkgJsonPath, nextContent, "utf8");
|
|
1351
|
+
}));
|
|
1352
|
+
}
|
|
1353
|
+
//#endregion
|
|
1354
|
+
//#region src/commands/init/setReadme.ts
|
|
1355
|
+
async function getRows(ctx) {
|
|
1356
|
+
const { packages, gitUrl, gitUser, cwd } = ctx;
|
|
1357
|
+
const rows = [];
|
|
1358
|
+
if (gitUrl) rows.push(`# ${gitUrl.name}\n`);
|
|
1359
|
+
rows.push("## Packages\n");
|
|
1360
|
+
const sortedPackages = packages.toSorted((a, b) => {
|
|
1361
|
+
const left = a.manifest.name ?? "";
|
|
1362
|
+
const right = b.manifest.name ?? "";
|
|
1363
|
+
return left.localeCompare(right);
|
|
1364
|
+
});
|
|
1365
|
+
for (const pkg of sortedPackages) {
|
|
1366
|
+
const p = path.relative(cwd, pkg.rootDirRealPath);
|
|
1367
|
+
if (p) {
|
|
1368
|
+
const description = pkg.manifest.description ? `- ${pkg.manifest.description}` : "";
|
|
1369
|
+
rows.push(`- [${pkg.manifest.name}](${p}) ${description}`);
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
if (gitUrl) {
|
|
1373
|
+
rows.push("\n## Contributing\n");
|
|
1374
|
+
rows.push("Contributions Welcome! You can contribute in the following ways.");
|
|
1375
|
+
rows.push("");
|
|
1376
|
+
rows.push("- Create an Issue - Propose a new feature. Report a bug.");
|
|
1377
|
+
rows.push("- Pull Request - Fix a bug and typo. Refactor the code.");
|
|
1378
|
+
rows.push("- Create third-party middleware - Instruct below.");
|
|
1379
|
+
rows.push("- Share - Share your thoughts on the Blog, X, and others.");
|
|
1380
|
+
rows.push(`- Make your application - Please try to use ${gitUrl.name}.`);
|
|
1381
|
+
rows.push("");
|
|
1382
|
+
rows.push("For more details, see [CONTRIBUTING.md](CONTRIBUTING.md).");
|
|
1383
|
+
rows.push("\n## Contributors\n");
|
|
1384
|
+
rows.push(`Thanks to [all contributors](https://github.com/${gitUrl.full_name}/graphs/contributors)!`);
|
|
1385
|
+
}
|
|
1386
|
+
rows.push("\n## Authors\n");
|
|
1387
|
+
if (gitUser?.name && gitUser?.email) rows.push(`${gitUser.name} <${gitUser.email}>`);
|
|
1388
|
+
rows.push("\n## License\n");
|
|
1389
|
+
rows.push("Distributed under the MIT License. See [LICENSE](LICENSE) for more information.");
|
|
1390
|
+
return rows;
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* 生成标准化的 README 草稿,列出所有子包并补充贡献者、作者信息。
|
|
1394
|
+
*/
|
|
1395
|
+
async function setReadme_default(ctx) {
|
|
1396
|
+
const rows = await getRows(ctx);
|
|
1397
|
+
await fs$1.writeFile(path.resolve(ctx.cwd, "README.md"), `${rows.join("\n")}\n`);
|
|
1398
|
+
}
|
|
1399
|
+
//#endregion
|
|
1400
|
+
//#region ../../package.json
|
|
1401
|
+
var devDependencies = {
|
|
1402
|
+
"@changesets/cli": "^2.31.0",
|
|
1403
|
+
"@commitlint/cli": "^20.5.3",
|
|
1404
|
+
"@icebreakers/changelog-github": "^1.0.2",
|
|
1405
|
+
"@icebreakers/commitlint-config": "^2.0.0",
|
|
1406
|
+
"@icebreakers/eslint-config": "^4.0.10",
|
|
1407
|
+
"@icebreakers/monorepo": "workspace:*",
|
|
1408
|
+
"@icebreakers/stylelint-config": "^3.0.6",
|
|
1409
|
+
"@types/node": "^25.6.0",
|
|
1410
|
+
"@types/semver": "^7.7.1",
|
|
1411
|
+
"@vitest/coverage-v8": "~4.1.5",
|
|
1412
|
+
"ci-info": "^4.4.0",
|
|
1413
|
+
"cross-env": "^10.1.0",
|
|
1414
|
+
"defu": "^6.1.7",
|
|
1415
|
+
"es-toolkit": "^1.46.1",
|
|
1416
|
+
"eslint": "^10.3.0",
|
|
1417
|
+
"husky": "^9.1.7",
|
|
1418
|
+
"lint-staged": "^16.4.0",
|
|
1419
|
+
"only-allow": "^1.2.2",
|
|
1420
|
+
"pathe": "^2.0.3",
|
|
1421
|
+
"pkg-types": "^2.3.1",
|
|
1422
|
+
"repoctl": "workspace:*",
|
|
1423
|
+
"stylelint": "^17.9.1",
|
|
1424
|
+
"tailwindcss": "^4.2.4",
|
|
1425
|
+
"tsd": "^0.33.0",
|
|
1426
|
+
"tsdown": "0.21.10",
|
|
1427
|
+
"tslib": "^2.8.1",
|
|
1428
|
+
"tsup": "^8.5.1",
|
|
1429
|
+
"tsx": "^4.21.0",
|
|
1430
|
+
"turbo": "^2.9.7",
|
|
1431
|
+
"type-fest": "^5.6.0",
|
|
1432
|
+
"typescript": "^6.0.3",
|
|
1433
|
+
"vitest": "~4.1.5",
|
|
1434
|
+
"yaml": "^2.8.4"
|
|
1435
|
+
};
|
|
1436
|
+
//#endregion
|
|
1437
|
+
//#region src/commands/init/tooling/presets.ts
|
|
1438
|
+
const packageDependencies = {
|
|
1439
|
+
...{
|
|
1440
|
+
name: "monorepo-template",
|
|
1441
|
+
type: "module",
|
|
1442
|
+
version: "0.0.0",
|
|
1443
|
+
"private": true,
|
|
1444
|
+
packageManager: "pnpm@10.33.2",
|
|
1445
|
+
author: "ice breaker <hi@sonofmagic.top>",
|
|
1446
|
+
repository: {
|
|
1447
|
+
"type": "git",
|
|
1448
|
+
"url": "git+https://github.com/sonofmagic/monorepo-template.git"
|
|
1449
|
+
},
|
|
1450
|
+
bugs: { "url": "https://github.com/sonofmagic/monorepo-template/issues" },
|
|
1451
|
+
engines: { "node": ">=20.0.0" },
|
|
1452
|
+
scripts: {
|
|
1453
|
+
"build": "turbo run build",
|
|
1454
|
+
"tooling:build": "turbo run build --filter=@icebreakers/monorepo --filter=repoctl",
|
|
1455
|
+
"dev": "turbo run dev --parallel",
|
|
1456
|
+
"test": "vitest run",
|
|
1457
|
+
"test:dev": "vitest",
|
|
1458
|
+
"lint": "turbo run lint",
|
|
1459
|
+
"tsd": "turbo run tsd",
|
|
1460
|
+
"audit": "pnpm audit --audit-level=moderate",
|
|
1461
|
+
"audit:fix": "pnpm audit --fix",
|
|
1462
|
+
"typecheck": "turbo run typecheck",
|
|
1463
|
+
"format": "eslint . --fix",
|
|
1464
|
+
"validate": "pnpm run build && pnpm run lint && pnpm run typecheck && pnpm run tsd && pnpm run test",
|
|
1465
|
+
"release": "changeset",
|
|
1466
|
+
"publish-packages": "turbo run build lint test && changeset version && changeset publish",
|
|
1467
|
+
"------": "--------------",
|
|
1468
|
+
"preinstall": "npx only-allow pnpm",
|
|
1469
|
+
"prepare": "husky",
|
|
1470
|
+
"commit": "commit",
|
|
1471
|
+
"commitlint": "commitlint --edit",
|
|
1472
|
+
"-------": "---------------",
|
|
1473
|
+
"setup": "repo setup",
|
|
1474
|
+
"new": "repo new",
|
|
1475
|
+
"check": "repo check",
|
|
1476
|
+
"doctor": "repo doctor",
|
|
1477
|
+
"sync": "repo sync",
|
|
1478
|
+
"clean:repo": "repo clean",
|
|
1479
|
+
"mirror": "repo mirror",
|
|
1480
|
+
"------simple": "--------------",
|
|
1481
|
+
"pr:alpha": "changeset pre enter alpha",
|
|
1482
|
+
"pr:beta": "changeset pre enter beta",
|
|
1483
|
+
"pr:rc": "changeset pre enter rc",
|
|
1484
|
+
"pr:exit": "changeset pre exit",
|
|
1485
|
+
"--------": "----------------",
|
|
1486
|
+
"script:init": "repo init",
|
|
1487
|
+
"script:sync": "repo sync",
|
|
1488
|
+
"script:clean": "repo clean",
|
|
1489
|
+
"script:mirror": "repo mirror"
|
|
1490
|
+
},
|
|
1491
|
+
devDependencies,
|
|
1492
|
+
publishConfig: {
|
|
1493
|
+
"access": "public",
|
|
1494
|
+
"registry": "https://registry.npmjs.org"
|
|
1495
|
+
}
|
|
1496
|
+
}.dependencies ?? {},
|
|
1497
|
+
...devDependencies ?? {},
|
|
1498
|
+
...dependencies ?? {},
|
|
1499
|
+
...devDependencies$1 ?? {}
|
|
1500
|
+
};
|
|
1501
|
+
function getDependencyVersion(name) {
|
|
1502
|
+
const version = packageDependencies[name];
|
|
1503
|
+
if (!version) throw new Error(`未找到依赖 ${name} 的版本信息`);
|
|
1504
|
+
return version;
|
|
1505
|
+
}
|
|
1506
|
+
function getToolingPackageVersion() {
|
|
1507
|
+
return `^${version$1}`;
|
|
1508
|
+
}
|
|
1509
|
+
function createConfigModule(functionName, source) {
|
|
1510
|
+
return [
|
|
1511
|
+
`import { ${functionName} } from '${source}'`,
|
|
1512
|
+
"",
|
|
1513
|
+
`export default await ${functionName}()`,
|
|
1514
|
+
""
|
|
1515
|
+
].join("\n");
|
|
1516
|
+
}
|
|
1517
|
+
function getToolingPackageDependency(toolingPackageName) {
|
|
1518
|
+
return { [toolingPackageName]: getToolingPackageVersion() };
|
|
1519
|
+
}
|
|
1520
|
+
function getRootDeps(pkgJson) {
|
|
1521
|
+
return {
|
|
1522
|
+
...pkgJson.dependencies ?? {},
|
|
1523
|
+
...pkgJson.devDependencies ?? {}
|
|
1524
|
+
};
|
|
1525
|
+
}
|
|
1526
|
+
function resolveToolingPackageName(pkgJson) {
|
|
1527
|
+
const deps = getRootDeps(pkgJson);
|
|
1528
|
+
if (typeof deps["repoctl"] === "string" && deps["repoctl"].length > 0) return "repoctl";
|
|
1529
|
+
if (typeof deps["@icebreakers/monorepo"] === "string" && deps["@icebreakers/monorepo"].length > 0) return "@icebreakers/monorepo";
|
|
1530
|
+
return "repoctl";
|
|
1531
|
+
}
|
|
1532
|
+
function resolveToolingImportSource(toolingPackageName) {
|
|
1533
|
+
return toolingPackageName === "repoctl" ? "repoctl/tooling" : "@icebreakers/monorepo/tooling";
|
|
1534
|
+
}
|
|
1535
|
+
const initToolingPresets = {
|
|
1536
|
+
"commitlint": {
|
|
1537
|
+
target: "commitlint",
|
|
1538
|
+
filepath: "commitlint.config.ts",
|
|
1539
|
+
getContent: ({ toolingImportSource }) => createConfigModule("defineCommitlintConfig", toolingImportSource),
|
|
1540
|
+
getDependencies: ({ toolingPackageName }) => ({
|
|
1541
|
+
...getToolingPackageDependency(toolingPackageName),
|
|
1542
|
+
"@commitlint/cli": getDependencyVersion("@commitlint/cli"),
|
|
1543
|
+
"@icebreakers/commitlint-config": getDependencyVersion("@icebreakers/commitlint-config")
|
|
1544
|
+
})
|
|
1545
|
+
},
|
|
1546
|
+
"eslint": {
|
|
1547
|
+
target: "eslint",
|
|
1548
|
+
filepath: "eslint.config.js",
|
|
1549
|
+
getContent: ({ toolingImportSource }) => createConfigModule("defineEslintConfig", toolingImportSource),
|
|
1550
|
+
getDependencies: ({ toolingPackageName }) => ({
|
|
1551
|
+
...getToolingPackageDependency(toolingPackageName),
|
|
1552
|
+
"@icebreakers/eslint-config": getDependencyVersion("@icebreakers/eslint-config"),
|
|
1553
|
+
"eslint": getDependencyVersion("eslint")
|
|
1554
|
+
})
|
|
1555
|
+
},
|
|
1556
|
+
"stylelint": {
|
|
1557
|
+
target: "stylelint",
|
|
1558
|
+
filepath: "stylelint.config.js",
|
|
1559
|
+
getContent: ({ toolingImportSource }) => createConfigModule("defineStylelintConfig", toolingImportSource),
|
|
1560
|
+
getDependencies: ({ toolingPackageName }) => ({
|
|
1561
|
+
...getToolingPackageDependency(toolingPackageName),
|
|
1562
|
+
"@icebreakers/stylelint-config": getDependencyVersion("@icebreakers/stylelint-config"),
|
|
1563
|
+
"stylelint": getDependencyVersion("stylelint")
|
|
1564
|
+
})
|
|
1565
|
+
},
|
|
1566
|
+
"lint-staged": {
|
|
1567
|
+
target: "lint-staged",
|
|
1568
|
+
filepath: "lint-staged.config.js",
|
|
1569
|
+
getContent: ({ toolingImportSource }) => createConfigModule("defineLintStagedConfig", toolingImportSource),
|
|
1570
|
+
getDependencies: ({ toolingPackageName }) => ({
|
|
1571
|
+
...getToolingPackageDependency(toolingPackageName),
|
|
1572
|
+
"lint-staged": getDependencyVersion("lint-staged")
|
|
1573
|
+
})
|
|
1574
|
+
},
|
|
1575
|
+
"tsconfig": {
|
|
1576
|
+
target: "tsconfig",
|
|
1577
|
+
filepath: "tsconfig.json",
|
|
1578
|
+
getContent: async ({ cwd }) => {
|
|
1579
|
+
const config = await defineTsconfigConfig({ cwd });
|
|
1580
|
+
return `${JSON.stringify(config, void 0, 2)}\n`;
|
|
1581
|
+
},
|
|
1582
|
+
getDependencies: ({ toolingPackageName }) => ({
|
|
1583
|
+
...getToolingPackageDependency(toolingPackageName),
|
|
1584
|
+
typescript: getDependencyVersion("typescript")
|
|
1585
|
+
})
|
|
1586
|
+
},
|
|
1587
|
+
"vitest": {
|
|
1588
|
+
target: "vitest",
|
|
1589
|
+
filepath: "vitest.config.ts",
|
|
1590
|
+
getContent: ({ toolingImportSource }) => [
|
|
1591
|
+
`import { defineVitestConfig } from '${toolingImportSource}'`,
|
|
1592
|
+
`import { defineConfig } from 'vitest/config'`,
|
|
1593
|
+
"",
|
|
1594
|
+
"export default defineConfig(async () => await defineVitestConfig())",
|
|
1595
|
+
""
|
|
1596
|
+
].join("\n"),
|
|
1597
|
+
getDependencies: ({ toolingPackageName }) => ({
|
|
1598
|
+
...getToolingPackageDependency(toolingPackageName),
|
|
1599
|
+
"@vitest/coverage-v8": getDependencyVersion("@vitest/coverage-v8"),
|
|
1600
|
+
"vitest": getDependencyVersion("vitest")
|
|
1601
|
+
})
|
|
1602
|
+
}
|
|
1603
|
+
};
|
|
1604
|
+
//#endregion
|
|
1605
|
+
//#region src/commands/init/tooling/index.ts
|
|
1606
|
+
function sortRecord(input) {
|
|
1607
|
+
return Object.fromEntries(Object.entries(input).filter((entry) => typeof entry[1] === "string" && entry[1].length > 0).sort(([left], [right]) => left.localeCompare(right)));
|
|
1608
|
+
}
|
|
1609
|
+
function mergeDevDependencies(pkgJson, additions) {
|
|
1610
|
+
const current = { ...pkgJson.devDependencies ?? {} };
|
|
1611
|
+
let changed = false;
|
|
1612
|
+
for (const [name, version] of Object.entries(additions)) {
|
|
1613
|
+
if (!version) continue;
|
|
1614
|
+
if (current[name] === version) continue;
|
|
1615
|
+
current[name] = version;
|
|
1616
|
+
changed = true;
|
|
1617
|
+
}
|
|
1618
|
+
if (!changed && pkgJson.devDependencies) return false;
|
|
1619
|
+
pkgJson.devDependencies = sortRecord(current);
|
|
1620
|
+
return true;
|
|
1621
|
+
}
|
|
1622
|
+
function resolveTargets(options) {
|
|
1623
|
+
if (options.all) return [...initToolingTargets];
|
|
1624
|
+
const inputTargets = options.targets ?? [];
|
|
1625
|
+
return [...new Set(inputTargets)].filter((target) => {
|
|
1626
|
+
return initToolingTargets.includes(target);
|
|
1627
|
+
});
|
|
1628
|
+
}
|
|
1629
|
+
function normalizeInitToolingTargets(input) {
|
|
1630
|
+
const unknown = input.filter((item) => !initToolingTargets.includes(item));
|
|
1631
|
+
if (unknown.length > 0) throw new Error(`未知的 init tooling 目标: ${unknown.join(", ")}`);
|
|
1632
|
+
return input;
|
|
1633
|
+
}
|
|
1634
|
+
async function initTooling(cwd, options = {}) {
|
|
1635
|
+
const selectedTargets = resolveTargets(options);
|
|
1636
|
+
if (selectedTargets.length === 0) return {
|
|
1637
|
+
selectedTargets: [],
|
|
1638
|
+
writtenFiles: [],
|
|
1639
|
+
skippedFiles: [],
|
|
1640
|
+
updatedPackageJson: false
|
|
1641
|
+
};
|
|
1642
|
+
const pkgJsonPath = path.resolve(cwd, "package.json");
|
|
1643
|
+
if (!await fs$1.pathExists(pkgJsonPath)) throw new Error(`未找到 package.json,无法初始化 tooling: ${pkgJsonPath}`);
|
|
1644
|
+
const packageJson = await fs$1.readJson(pkgJsonPath);
|
|
1645
|
+
const toolingPackageName = resolveToolingPackageName(packageJson);
|
|
1646
|
+
const toolingImportSource = resolveToolingImportSource(toolingPackageName);
|
|
1647
|
+
const additions = {};
|
|
1648
|
+
const writtenFiles = [];
|
|
1649
|
+
const skippedFiles = [];
|
|
1650
|
+
for (const target of selectedTargets) {
|
|
1651
|
+
const preset = initToolingPresets[target];
|
|
1652
|
+
const filepath = path.resolve(cwd, preset.filepath);
|
|
1653
|
+
const exists = await fs$1.pathExists(filepath);
|
|
1654
|
+
Object.assign(additions, preset.getDependencies({
|
|
1655
|
+
cwd,
|
|
1656
|
+
packageJson,
|
|
1657
|
+
toolingPackageName,
|
|
1658
|
+
toolingImportSource
|
|
1659
|
+
}));
|
|
1660
|
+
if (exists && !options.force) {
|
|
1661
|
+
skippedFiles.push(preset.filepath);
|
|
1662
|
+
logger.info(`skip existing init target: ${preset.filepath}`);
|
|
1663
|
+
continue;
|
|
1664
|
+
}
|
|
1665
|
+
const content = await preset.getContent({
|
|
1666
|
+
cwd,
|
|
1667
|
+
packageJson,
|
|
1668
|
+
toolingPackageName,
|
|
1669
|
+
toolingImportSource
|
|
1670
|
+
});
|
|
1671
|
+
await fs$1.outputFile(filepath, content, "utf8");
|
|
1672
|
+
writtenFiles.push(preset.filepath);
|
|
1673
|
+
}
|
|
1674
|
+
const updatedPackageJson = mergeDevDependencies(packageJson, additions);
|
|
1675
|
+
if (updatedPackageJson) await fs$1.writeFile(pkgJsonPath, `${JSON.stringify(packageJson, void 0, 2)}\n`, "utf8");
|
|
1676
|
+
return {
|
|
1677
|
+
selectedTargets,
|
|
1678
|
+
writtenFiles,
|
|
1679
|
+
skippedFiles,
|
|
1680
|
+
updatedPackageJson
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
//#endregion
|
|
1684
|
+
//#region src/commands/init/index.ts
|
|
1685
|
+
const presetToolingMap = {
|
|
1686
|
+
minimal: ["tsconfig"],
|
|
1687
|
+
standard: [...initToolingTargets]
|
|
1688
|
+
};
|
|
1689
|
+
async function runInitMetadata(cwd) {
|
|
1690
|
+
const ctx = await createContext(cwd);
|
|
1691
|
+
const initConfig = ctx.config.commands?.init ?? {};
|
|
1692
|
+
if (!initConfig.skipChangeset) await setChangeset_default(ctx);
|
|
1693
|
+
if (!initConfig.skipPkgJson) await setPkgJson_default(ctx);
|
|
1694
|
+
if (!initConfig.skipReadme) await setReadme_default(ctx);
|
|
1695
|
+
if (!initConfig.skipIssueTemplateConfig) await setIssueTemplateConfig_default(ctx);
|
|
1696
|
+
return {
|
|
1697
|
+
ctx,
|
|
1698
|
+
initConfig
|
|
1699
|
+
};
|
|
1700
|
+
}
|
|
1701
|
+
async function initMetadata(cwd) {
|
|
1702
|
+
await runInitMetadata(cwd);
|
|
1703
|
+
}
|
|
1704
|
+
/**
|
|
1705
|
+
* 初始化命令入口,根据配置逐步生成基础文件。
|
|
1706
|
+
*/
|
|
1707
|
+
async function init(cwd, options = {}) {
|
|
1708
|
+
const { initConfig } = await runInitMetadata(cwd);
|
|
1709
|
+
const preset = options.preset ?? initConfig.preset;
|
|
1710
|
+
const presetTargets = preset ? presetToolingMap[preset] : void 0;
|
|
1711
|
+
const configuredTargets = initConfig.tooling ?? [];
|
|
1712
|
+
const runtimeTargets = options.tooling?.length ? [...options.tooling] : presetTargets ?? configuredTargets;
|
|
1713
|
+
await initTooling(cwd, {
|
|
1714
|
+
targets: options.all ? [...initToolingTargets] : normalizeInitToolingTargets(runtimeTargets),
|
|
1715
|
+
force: options.force ?? initConfig.force ?? false,
|
|
1716
|
+
...options.all !== void 0 ? { all: options.all } : {}
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
//#endregion
|
|
1720
|
+
//#region src/commands/mirror/sources.ts
|
|
1721
|
+
const chinaMirrorsEnvs = {
|
|
1722
|
+
COREPACK_NPM_REGISTRY: "https://registry.npmmirror.com",
|
|
1723
|
+
EDGEDRIVER_CDNURL: "https://npmmirror.com/mirrors/edgedriver",
|
|
1724
|
+
NODEJS_ORG_MIRROR: "https://cdn.npmmirror.com/binaries/node",
|
|
1725
|
+
NVM_NODEJS_ORG_MIRROR: "https://cdn.npmmirror.com/binaries/node",
|
|
1726
|
+
PHANTOMJS_CDNURL: "https://cdn.npmmirror.com/binaries/phantomjs",
|
|
1727
|
+
CHROMEDRIVER_CDNURL: "https://cdn.npmmirror.com/binaries/chromedriver",
|
|
1728
|
+
OPERADRIVER_CDNURL: "https://cdn.npmmirror.com/binaries/operadriver",
|
|
1729
|
+
CYPRESS_DOWNLOAD_PATH_TEMPLATE: "https://cdn.npmmirror.com/binaries/cypress/${version}/${platform}-${arch}/cypress.zip",
|
|
1730
|
+
ELECTRON_MIRROR: "https://cdn.npmmirror.com/binaries/electron/",
|
|
1731
|
+
ELECTRON_BUILDER_BINARIES_MIRROR: "https://cdn.npmmirror.com/binaries/electron-builder-binaries/",
|
|
1732
|
+
SASS_BINARY_SITE: "https://cdn.npmmirror.com/binaries/node-sass",
|
|
1733
|
+
SWC_BINARY_SITE: "https://cdn.npmmirror.com/binaries/node-swc",
|
|
1734
|
+
NWJS_URLBASE: "https://cdn.npmmirror.com/binaries/nwjs/v",
|
|
1735
|
+
PUPPETEER_DOWNLOAD_HOST: "https://cdn.npmmirror.com/binaries/chrome-for-testing",
|
|
1736
|
+
PUPPETEER_DOWNLOAD_BASE_URL: "https://cdn.npmmirror.com/binaries/chrome-for-testing",
|
|
1737
|
+
PLAYWRIGHT_DOWNLOAD_HOST: "https://cdn.npmmirror.com/binaries/playwright",
|
|
1738
|
+
SENTRYCLI_CDNURL: "https://cdn.npmmirror.com/binaries/sentry-cli",
|
|
1739
|
+
SAUCECTL_INSTALL_BINARY_MIRROR: "https://cdn.npmmirror.com/binaries/saucectl",
|
|
1740
|
+
RE2_DOWNLOAD_MIRROR: "https://cdn.npmmirror.com/binaries/node-re2",
|
|
1741
|
+
RE2_DOWNLOAD_SKIP_PATH: "true",
|
|
1742
|
+
PRISMA_ENGINES_MIRROR: "https://cdn.npmmirror.com/binaries/prisma",
|
|
1743
|
+
npm_config_better_sqlite3_binary_host: "https://cdn.npmmirror.com/binaries/better-sqlite3",
|
|
1744
|
+
npm_config_keytar_binary_host: "https://cdn.npmmirror.com/binaries/keytar",
|
|
1745
|
+
npm_config_sharp_binary_host: "https://cdn.npmmirror.com/binaries/sharp",
|
|
1746
|
+
npm_config_sharp_libvips_binary_host: "https://cdn.npmmirror.com/binaries/sharp-libvips",
|
|
1747
|
+
npm_config_robotjs_binary_host: "https://cdn.npmmirror.com/binaries/robotjs"
|
|
1748
|
+
};
|
|
1749
|
+
//#endregion
|
|
1750
|
+
//#region src/commands/mirror/utils.ts
|
|
1751
|
+
/**
|
|
1752
|
+
* 在 vscode 里面设置镜像下载地址的环境变量,避免下载缓慢
|
|
1753
|
+
*/
|
|
1754
|
+
function setMirror(obj, envs = chinaMirrorsEnvs) {
|
|
1755
|
+
const platforms = [
|
|
1756
|
+
"linux",
|
|
1757
|
+
"windows",
|
|
1758
|
+
"osx"
|
|
1759
|
+
];
|
|
1760
|
+
const prefix = "terminal.integrated.env";
|
|
1761
|
+
if (typeof obj === "object" && obj) for (const platform of platforms) setByPath(obj, [prefix, platform].join(".").replaceAll(".", "\\."), envs);
|
|
1762
|
+
}
|
|
1763
|
+
//#endregion
|
|
1764
|
+
//#region src/commands/mirror/binaryMirror.ts
|
|
1765
|
+
/**
|
|
1766
|
+
* 根据中国大陆镜像源,自动向 VSCode settings.json 注入终端环境变量。
|
|
1767
|
+
*/
|
|
1768
|
+
async function setVscodeBinaryMirror(cwd) {
|
|
1769
|
+
const mirrorConfig = await resolveCommandConfig("mirror", cwd);
|
|
1770
|
+
const targetJsonPath = path.resolve(cwd, ".vscode/settings.json");
|
|
1771
|
+
await fs$1.ensureFile(targetJsonPath);
|
|
1772
|
+
const json = parse(await fs$1.readFile(targetJsonPath, "utf8"), void 0, false);
|
|
1773
|
+
const env = mirrorConfig?.env ? {
|
|
1774
|
+
...chinaMirrorsEnvs,
|
|
1775
|
+
...mirrorConfig.env
|
|
1776
|
+
} : chinaMirrorsEnvs;
|
|
1777
|
+
json && typeof json === "object" && setMirror(json, env);
|
|
1778
|
+
await fs$1.writeFile(targetJsonPath, `${stringify(json, void 0, 2)}\n`, "utf8");
|
|
1779
|
+
}
|
|
1780
|
+
//#endregion
|
|
1781
|
+
//#region src/commands/templates.ts
|
|
1782
|
+
async function collectFiles(rootDir) {
|
|
1783
|
+
const files = [];
|
|
1784
|
+
async function walk(currentDir) {
|
|
1785
|
+
const entries = await readdir(currentDir, { withFileTypes: true });
|
|
1786
|
+
await Promise.all(entries.map(async (entry) => {
|
|
1787
|
+
const entryPath = path.join(currentDir, entry.name);
|
|
1788
|
+
if (entry.isDirectory()) {
|
|
1789
|
+
await walk(entryPath);
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
if (entry.isFile()) files.push(entryPath);
|
|
1793
|
+
}));
|
|
1794
|
+
}
|
|
1795
|
+
await walk(rootDir);
|
|
1796
|
+
return files;
|
|
1797
|
+
}
|
|
1798
|
+
function summarizeTemplateChecks(checks) {
|
|
1799
|
+
return checks.reduce((summary, check) => {
|
|
1800
|
+
summary[check.status] += 1;
|
|
1801
|
+
return summary;
|
|
1802
|
+
}, {
|
|
1803
|
+
pass: 0,
|
|
1804
|
+
warn: 0,
|
|
1805
|
+
fail: 0
|
|
1806
|
+
});
|
|
1807
|
+
}
|
|
1808
|
+
function checkDuplicates(choices, field) {
|
|
1809
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1810
|
+
const duplicates = [];
|
|
1811
|
+
for (const choice of choices) {
|
|
1812
|
+
const value = choice[field];
|
|
1813
|
+
const previous = seen.get(value);
|
|
1814
|
+
if (previous) {
|
|
1815
|
+
duplicates.push([
|
|
1816
|
+
value,
|
|
1817
|
+
previous,
|
|
1818
|
+
choice.key
|
|
1819
|
+
]);
|
|
1820
|
+
continue;
|
|
1821
|
+
}
|
|
1822
|
+
seen.set(value, choice.key);
|
|
1823
|
+
}
|
|
1824
|
+
return duplicates;
|
|
1825
|
+
}
|
|
1826
|
+
async function checkTemplates(options = {}) {
|
|
1827
|
+
const templatesDir$1 = options.templatesDir ?? templatesDir;
|
|
1828
|
+
const choices = getTemplateChoices();
|
|
1829
|
+
const checks = [];
|
|
1830
|
+
const sourceDuplicates = checkDuplicates(choices, "source");
|
|
1831
|
+
checks.push(sourceDuplicates.length ? {
|
|
1832
|
+
id: "unique-source",
|
|
1833
|
+
status: "fail",
|
|
1834
|
+
title: "模板 source 唯一性",
|
|
1835
|
+
detail: `存在重复 source:${sourceDuplicates.map(([value, first, second]) => `${value} (${first}, ${second})`).join(", ")}`,
|
|
1836
|
+
fix: "调整 template-data.mjs,确保每个模板 key 指向独立 source。"
|
|
1837
|
+
} : {
|
|
1838
|
+
id: "unique-source",
|
|
1839
|
+
status: "pass",
|
|
1840
|
+
title: "模板 source 唯一性",
|
|
1841
|
+
detail: "所有模板 source 都是唯一的。"
|
|
1842
|
+
});
|
|
1843
|
+
const targetDuplicates = checkDuplicates(choices, "target");
|
|
1844
|
+
checks.push(targetDuplicates.length ? {
|
|
1845
|
+
id: "unique-target",
|
|
1846
|
+
status: "fail",
|
|
1847
|
+
title: "模板 target 唯一性",
|
|
1848
|
+
detail: `存在重复 target:${targetDuplicates.map(([value, first, second]) => `${value} (${first}, ${second})`).join(", ")}`,
|
|
1849
|
+
fix: "调整 template-data.mjs,避免多个模板默认写入同一目标目录。"
|
|
1850
|
+
} : {
|
|
1851
|
+
id: "unique-target",
|
|
1852
|
+
status: "pass",
|
|
1853
|
+
title: "模板 target 唯一性",
|
|
1854
|
+
detail: "所有模板 target 都是唯一的。"
|
|
1855
|
+
});
|
|
1856
|
+
for (const choice of choices) {
|
|
1857
|
+
const sourceDir = path.join(templatesDir$1, choice.source);
|
|
1858
|
+
const packageJsonPath = path.join(sourceDir, "package.json");
|
|
1859
|
+
const sourceExists = await fs$1.pathExists(sourceDir);
|
|
1860
|
+
checks.push(sourceExists ? {
|
|
1861
|
+
id: "source-dir",
|
|
1862
|
+
template: choice.key,
|
|
1863
|
+
status: "pass",
|
|
1864
|
+
title: "模板目录",
|
|
1865
|
+
detail: `${choice.key} source exists: ${path.relative(templatesDir$1, sourceDir)}`
|
|
1866
|
+
} : {
|
|
1867
|
+
id: "source-dir",
|
|
1868
|
+
template: choice.key,
|
|
1869
|
+
status: "fail",
|
|
1870
|
+
title: "模板目录",
|
|
1871
|
+
detail: `${choice.key} 缺少 source 目录:${sourceDir}`,
|
|
1872
|
+
fix: "补齐模板目录,或修正 template-data.mjs 中的 source。"
|
|
1873
|
+
});
|
|
1874
|
+
checks.push(await fs$1.pathExists(packageJsonPath) ? {
|
|
1875
|
+
id: "package-json",
|
|
1876
|
+
template: choice.key,
|
|
1877
|
+
status: "pass",
|
|
1878
|
+
title: "模板 package.json",
|
|
1879
|
+
detail: `${choice.key} 包含 package.json。`
|
|
1880
|
+
} : {
|
|
1881
|
+
id: "package-json",
|
|
1882
|
+
template: choice.key,
|
|
1883
|
+
status: "fail",
|
|
1884
|
+
title: "模板 package.json",
|
|
1885
|
+
detail: `${choice.key} 缺少 package.json。`,
|
|
1886
|
+
fix: "模板根目录应包含 package.json,脚手架会基于它重写 name/version/repository。"
|
|
1887
|
+
});
|
|
1888
|
+
checks.push(choice.category && choice.description ? {
|
|
1889
|
+
id: "metadata",
|
|
1890
|
+
template: choice.key,
|
|
1891
|
+
status: "pass",
|
|
1892
|
+
title: "模板元数据",
|
|
1893
|
+
detail: `${choice.key} 已声明 category 和 description。`
|
|
1894
|
+
} : {
|
|
1895
|
+
id: "metadata",
|
|
1896
|
+
template: choice.key,
|
|
1897
|
+
status: "warn",
|
|
1898
|
+
title: "模板元数据",
|
|
1899
|
+
detail: `${choice.key} 缺少 category 或 description。`,
|
|
1900
|
+
fix: "补充 template-data.mjs 中的 category 和 description,方便 CLI 和文档展示。"
|
|
1901
|
+
});
|
|
1902
|
+
if (!sourceExists) continue;
|
|
1903
|
+
const skippedFiles = (await collectFiles(sourceDir)).filter((file) => shouldSkipTemplatePath(sourceDir, file)).map((file) => path.relative(sourceDir, file));
|
|
1904
|
+
checks.push(skippedFiles.length ? {
|
|
1905
|
+
id: "filtered-files",
|
|
1906
|
+
template: choice.key,
|
|
1907
|
+
status: "fail",
|
|
1908
|
+
title: "模板临时文件",
|
|
1909
|
+
detail: `${choice.key} 包含会被脚手架过滤的文件:${skippedFiles.join(", ")}`,
|
|
1910
|
+
fix: "删除模板源目录里的临时、缓存或生成文件。"
|
|
1911
|
+
} : {
|
|
1912
|
+
id: "filtered-files",
|
|
1913
|
+
template: choice.key,
|
|
1914
|
+
status: "pass",
|
|
1915
|
+
title: "模板临时文件",
|
|
1916
|
+
detail: `${choice.key} 没有检测到会被过滤的临时文件。`
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1919
|
+
return {
|
|
1920
|
+
templatesDir: templatesDir$1,
|
|
1921
|
+
templateCount: choices.length,
|
|
1922
|
+
checks,
|
|
1923
|
+
summary: summarizeTemplateChecks(checks)
|
|
1924
|
+
};
|
|
1925
|
+
}
|
|
1926
|
+
//#endregion
|
|
1927
|
+
//#region src/commands/upgrade/agents.ts
|
|
1928
|
+
const crlfPattern$1 = /\r\n/g;
|
|
1929
|
+
const h2HeadingPrefixPattern = /^##\s+/;
|
|
1930
|
+
function normalizeEol$1(input) {
|
|
1931
|
+
return input.replace(crlfPattern$1, "\n");
|
|
1932
|
+
}
|
|
1933
|
+
function normalizeComparableContent(input) {
|
|
1934
|
+
return normalizeEol$1(input).trimEnd();
|
|
1935
|
+
}
|
|
1936
|
+
function normalizeHeadingKey(line) {
|
|
1937
|
+
return line.replace(h2HeadingPrefixPattern, "").trim().toLowerCase();
|
|
1938
|
+
}
|
|
1939
|
+
function trimEdgeEmptyLines(lines) {
|
|
1940
|
+
const next = [...lines];
|
|
1941
|
+
while (next.length) {
|
|
1942
|
+
const first = next[0];
|
|
1943
|
+
if (first === void 0 || first.trim().length > 0) break;
|
|
1944
|
+
next.shift();
|
|
1945
|
+
}
|
|
1946
|
+
while (next.length) {
|
|
1947
|
+
const last = next.at(-1);
|
|
1948
|
+
if (last === void 0 || last.trim().length > 0) break;
|
|
1949
|
+
next.pop();
|
|
1950
|
+
}
|
|
1951
|
+
return next;
|
|
1952
|
+
}
|
|
1953
|
+
function parseMarkdownByH2(content) {
|
|
1954
|
+
const lines = normalizeEol$1(content).split("\n");
|
|
1955
|
+
const preamble = [];
|
|
1956
|
+
const sections = [];
|
|
1957
|
+
let current;
|
|
1958
|
+
for (const line of lines) {
|
|
1959
|
+
if (h2HeadingPrefixPattern.test(line)) {
|
|
1960
|
+
if (current) sections.push(current);
|
|
1961
|
+
current = {
|
|
1962
|
+
key: normalizeHeadingKey(line),
|
|
1963
|
+
lines: [line]
|
|
1964
|
+
};
|
|
1965
|
+
continue;
|
|
1966
|
+
}
|
|
1967
|
+
if (current) {
|
|
1968
|
+
current.lines.push(line);
|
|
1969
|
+
continue;
|
|
1970
|
+
}
|
|
1971
|
+
preamble.push(line);
|
|
1972
|
+
}
|
|
1973
|
+
if (current) sections.push(current);
|
|
1974
|
+
return {
|
|
1975
|
+
preamble,
|
|
1976
|
+
sections
|
|
1977
|
+
};
|
|
1978
|
+
}
|
|
1979
|
+
function mergePlainText(source, target) {
|
|
1980
|
+
const sourceLines = trimEdgeEmptyLines(normalizeEol$1(source).split("\n"));
|
|
1981
|
+
const result = trimEdgeEmptyLines(normalizeEol$1(target).split("\n"));
|
|
1982
|
+
const seen = new Set(result);
|
|
1983
|
+
for (const line of sourceLines) {
|
|
1984
|
+
if (!line.trim()) continue;
|
|
1985
|
+
if (seen.has(line)) continue;
|
|
1986
|
+
seen.add(line);
|
|
1987
|
+
result.push(line);
|
|
1988
|
+
}
|
|
1989
|
+
return `${result.join("\n")}\n`;
|
|
1990
|
+
}
|
|
1991
|
+
function getSectionSignature(section) {
|
|
1992
|
+
return `${section.key}\n${trimEdgeEmptyLines(section.lines).join("\n")}`;
|
|
1993
|
+
}
|
|
1994
|
+
/**
|
|
1995
|
+
* Merge AGENTS instructions by keeping existing sections and filling missing sections
|
|
1996
|
+
* from source defaults. This avoids destructive overwrite while still syncing updates.
|
|
1997
|
+
*/
|
|
1998
|
+
function mergeAgentsMarkdown(source, target) {
|
|
1999
|
+
const sourceParsed = parseMarkdownByH2(source);
|
|
2000
|
+
const targetParsed = parseMarkdownByH2(target);
|
|
2001
|
+
if (!sourceParsed.sections.length || !targetParsed.sections.length) return mergePlainText(source, target);
|
|
2002
|
+
const sourceSectionKeys = new Set(sourceParsed.sections.map((section) => section.key));
|
|
2003
|
+
const targetSectionMap = new Map(targetParsed.sections.map((section) => [section.key, section]));
|
|
2004
|
+
const mergedSections = [];
|
|
2005
|
+
for (const section of sourceParsed.sections) mergedSections.push(targetSectionMap.get(section.key) ?? section);
|
|
2006
|
+
const seenTargetOnlySectionSignatures = /* @__PURE__ */ new Set();
|
|
2007
|
+
for (const section of targetParsed.sections) if (!sourceSectionKeys.has(section.key)) {
|
|
2008
|
+
const signature = getSectionSignature(section);
|
|
2009
|
+
if (seenTargetOnlySectionSignatures.has(signature)) continue;
|
|
2010
|
+
seenTargetOnlySectionSignatures.add(signature);
|
|
2011
|
+
mergedSections.push(section);
|
|
2012
|
+
}
|
|
2013
|
+
const preamble = trimEdgeEmptyLines(targetParsed.preamble.length ? targetParsed.preamble : sourceParsed.preamble);
|
|
2014
|
+
const blocks = [];
|
|
2015
|
+
if (preamble.length) blocks.push(preamble.join("\n"));
|
|
2016
|
+
for (const section of mergedSections) blocks.push(trimEdgeEmptyLines(section.lines).join("\n"));
|
|
2017
|
+
return `${blocks.filter(Boolean).join("\n\n")}\n`;
|
|
2018
|
+
}
|
|
2019
|
+
/**
|
|
2020
|
+
* Compare AGENTS markdown with normalized EOL and trailing newline differences ignored.
|
|
2021
|
+
*/
|
|
2022
|
+
function isAgentsMarkdownEquivalent(left, right) {
|
|
2023
|
+
return normalizeComparableContent(left) === normalizeComparableContent(right);
|
|
2024
|
+
}
|
|
2025
|
+
//#endregion
|
|
2026
|
+
//#region src/commands/upgrade/overwrite.ts
|
|
2027
|
+
function asBuffer(data) {
|
|
2028
|
+
return typeof data === "string" ? Buffer.from(data) : data;
|
|
2029
|
+
}
|
|
2030
|
+
async function evaluateWriteIntent(targetPath, options) {
|
|
2031
|
+
const { skipOverwrite, source } = options;
|
|
2032
|
+
if (!await fs$1.pathExists(targetPath)) return {
|
|
2033
|
+
type: "write",
|
|
2034
|
+
reason: "missing"
|
|
2035
|
+
};
|
|
2036
|
+
if (skipOverwrite) return {
|
|
2037
|
+
type: "skip",
|
|
2038
|
+
reason: "skipOverwrite"
|
|
2039
|
+
};
|
|
2040
|
+
const src = asBuffer(source);
|
|
2041
|
+
let destSize = 0;
|
|
2042
|
+
try {
|
|
2043
|
+
destSize = (await fs$1.stat(targetPath)).size;
|
|
2044
|
+
} catch {
|
|
2045
|
+
return {
|
|
2046
|
+
type: "write",
|
|
2047
|
+
reason: "missing"
|
|
2048
|
+
};
|
|
2049
|
+
}
|
|
2050
|
+
if (destSize !== src.length) return {
|
|
2051
|
+
type: "prompt",
|
|
2052
|
+
reason: "changed"
|
|
2053
|
+
};
|
|
2054
|
+
if (!isFileChanged(src, await fs$1.readFile(targetPath))) return {
|
|
2055
|
+
type: "skip",
|
|
2056
|
+
reason: "identical"
|
|
2057
|
+
};
|
|
2058
|
+
return {
|
|
2059
|
+
type: "prompt",
|
|
2060
|
+
reason: "changed"
|
|
2061
|
+
};
|
|
2062
|
+
}
|
|
2063
|
+
async function scheduleOverwrite(intent, options) {
|
|
2064
|
+
const { relPath, targetPath, action, pending } = options;
|
|
2065
|
+
if (intent.type === "write") {
|
|
2066
|
+
await action();
|
|
2067
|
+
return;
|
|
2068
|
+
}
|
|
2069
|
+
if (intent.type === "prompt") pending.push({
|
|
2070
|
+
relPath,
|
|
2071
|
+
targetPath,
|
|
2072
|
+
action
|
|
2073
|
+
});
|
|
2074
|
+
}
|
|
2075
|
+
async function flushPendingOverwrites(pending) {
|
|
2076
|
+
if (!pending.length) return;
|
|
2077
|
+
const selected = await checkbox({
|
|
2078
|
+
message: "检测到以下文件内容与当前仓库不同,选择需要覆盖的文件",
|
|
2079
|
+
choices: pending.map((item) => ({
|
|
2080
|
+
name: pc.greenBright(item.relPath),
|
|
2081
|
+
value: item.targetPath,
|
|
2082
|
+
checked: false
|
|
2083
|
+
})),
|
|
2084
|
+
loop: false
|
|
2085
|
+
});
|
|
2086
|
+
const selectedSet = new Set(selected);
|
|
2087
|
+
for (const item of pending) if (selectedSet.has(item.targetPath)) await item.action();
|
|
2088
|
+
}
|
|
2089
|
+
const scriptsEntries = Object.entries({
|
|
2090
|
+
"setup": "repo setup",
|
|
2091
|
+
"new": "repo new",
|
|
2092
|
+
"check": "repo check",
|
|
2093
|
+
"doctor": "repo doctor",
|
|
2094
|
+
"sync": "repo sync",
|
|
2095
|
+
"clean:repo": "repo clean",
|
|
2096
|
+
"mirror": "repo mirror",
|
|
2097
|
+
"script:init": "repo init",
|
|
2098
|
+
"script:sync": "repo sync",
|
|
2099
|
+
"script:clean": "repo clean",
|
|
2100
|
+
"script:mirror": "repo mirror",
|
|
2101
|
+
"commitlint": "commitlint --edit"
|
|
2102
|
+
});
|
|
2103
|
+
//#endregion
|
|
2104
|
+
//#region src/commands/upgrade/pkg-json.ts
|
|
2105
|
+
const NON_OVERRIDABLE_PREFIXES = ["workspace:", "catalog:"];
|
|
2106
|
+
const toolPackageNames = ["repoctl", name$1];
|
|
2107
|
+
function parseVersion(input) {
|
|
2108
|
+
if (typeof input !== "string" || input.trim().length === 0) return null;
|
|
2109
|
+
try {
|
|
2110
|
+
return minVersion(input) ?? coerce(input);
|
|
2111
|
+
} catch {
|
|
2112
|
+
return null;
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
function hasNonOverridablePrefix(version) {
|
|
2116
|
+
if (typeof version !== "string") return false;
|
|
2117
|
+
return NON_OVERRIDABLE_PREFIXES.some((prefix) => version.startsWith(prefix));
|
|
2118
|
+
}
|
|
2119
|
+
function shouldAssignVersion(currentVersion, nextVersion) {
|
|
2120
|
+
if (typeof currentVersion !== "string" || currentVersion.trim().length === 0) return true;
|
|
2121
|
+
if (currentVersion === nextVersion) return false;
|
|
2122
|
+
const current = parseVersion(currentVersion);
|
|
2123
|
+
const next = parseVersion(nextVersion);
|
|
2124
|
+
if (!current || !next) return true;
|
|
2125
|
+
return !gte(current, next);
|
|
2126
|
+
}
|
|
2127
|
+
function resolvePreferredToolPackageName(sourceDevDeps, targetDevDeps) {
|
|
2128
|
+
for (const depName of toolPackageNames) if (typeof targetDevDeps[depName] === "string" && targetDevDeps[depName].length > 0) return depName;
|
|
2129
|
+
for (const depName of toolPackageNames) if (typeof sourceDevDeps[depName] === "string" && sourceDevDeps[depName].length > 0) return depName;
|
|
2130
|
+
return "repoctl";
|
|
2131
|
+
}
|
|
2132
|
+
/**
|
|
2133
|
+
* 将内置 package.json 内容合并进目标工程:
|
|
2134
|
+
* - 同步依赖(保留 workspace: 前缀的版本)
|
|
2135
|
+
* - 确保 @icebreakers/monorepo 使用最新版本
|
|
2136
|
+
* - 写入预置脚本
|
|
2137
|
+
*/
|
|
2138
|
+
function setPkgJson(sourcePkgJson, targetPkgJson, options) {
|
|
2139
|
+
const packageManager = sourcePkgJson.packageManager ?? "";
|
|
2140
|
+
const sourceDeps = sourcePkgJson.dependencies ?? {};
|
|
2141
|
+
const sourceDevDeps = sourcePkgJson.devDependencies ?? {};
|
|
2142
|
+
const targetDeps = { ...targetPkgJson.dependencies ?? {} };
|
|
2143
|
+
const targetDevDeps = { ...targetPkgJson.devDependencies ?? {} };
|
|
2144
|
+
const preferredToolPackageName = resolvePreferredToolPackageName(sourceDevDeps, targetDevDeps);
|
|
2145
|
+
if (packageManager) targetPkgJson.packageManager = packageManager;
|
|
2146
|
+
for (const [depName, depVersion] of Object.entries(sourceDeps)) {
|
|
2147
|
+
if (typeof depVersion !== "string") continue;
|
|
2148
|
+
const targetVersion = targetDeps[depName];
|
|
2149
|
+
if (hasNonOverridablePrefix(targetVersion)) continue;
|
|
2150
|
+
if (shouldAssignVersion(targetVersion, depVersion)) targetDeps[depName] = depVersion;
|
|
2151
|
+
}
|
|
2152
|
+
if (Object.keys(targetDeps).length) targetPkgJson.dependencies = targetDeps;
|
|
2153
|
+
for (const [depName, depVersion] of Object.entries(sourceDevDeps)) {
|
|
2154
|
+
if (typeof depVersion !== "string") continue;
|
|
2155
|
+
if (toolPackageNames.includes(depName)) {
|
|
2156
|
+
if (depName !== preferredToolPackageName) continue;
|
|
2157
|
+
const nextVersion = `^${version$1}`;
|
|
2158
|
+
const targetVersion = targetDevDeps[depName];
|
|
2159
|
+
if (!hasNonOverridablePrefix(targetVersion) && shouldAssignVersion(targetVersion, nextVersion)) targetDevDeps[depName] = nextVersion;
|
|
2160
|
+
} else {
|
|
2161
|
+
const targetVersion = targetDevDeps[depName];
|
|
2162
|
+
if (hasNonOverridablePrefix(targetVersion)) continue;
|
|
2163
|
+
if (shouldAssignVersion(targetVersion, depVersion)) targetDevDeps[depName] = depVersion;
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
for (const depName of toolPackageNames) if (depName !== preferredToolPackageName && depName in targetDevDeps && preferredToolPackageName in targetDevDeps) delete targetDevDeps[depName];
|
|
2167
|
+
if (Object.keys(targetDevDeps).length) targetPkgJson.devDependencies = targetDevDeps;
|
|
2168
|
+
const scriptPairs = options?.scripts ? Object.entries(options.scripts) : scriptsEntries;
|
|
2169
|
+
if (scriptPairs.length) {
|
|
2170
|
+
const scripts = { ...targetPkgJson.scripts ?? {} };
|
|
2171
|
+
for (const [scriptName, scriptCmd] of scriptPairs) scripts[scriptName] = scriptCmd;
|
|
2172
|
+
targetPkgJson.scripts = scripts;
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
//#endregion
|
|
2176
|
+
//#region src/commands/upgrade/workspace.ts
|
|
2177
|
+
function isPlainObject(value) {
|
|
2178
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2179
|
+
}
|
|
2180
|
+
function normalizeQuotedString(value) {
|
|
2181
|
+
const trimmed = value.trim();
|
|
2182
|
+
const first = trimmed[0];
|
|
2183
|
+
if ((first === "'" || first === "\"") && trimmed.endsWith(first)) return trimmed.slice(1, -1);
|
|
2184
|
+
return trimmed;
|
|
2185
|
+
}
|
|
2186
|
+
function normalizeWorkspaceManifest(manifest) {
|
|
2187
|
+
if (isPlainObject(manifest)) return { ...manifest };
|
|
2188
|
+
return {};
|
|
2189
|
+
}
|
|
2190
|
+
function mergeUniqueArray(target, source) {
|
|
2191
|
+
const seen = new Set(target.map((item) => {
|
|
2192
|
+
return typeof item === "string" ? normalizeQuotedString(item) : item;
|
|
2193
|
+
}));
|
|
2194
|
+
const result = [...target];
|
|
2195
|
+
for (const item of source) {
|
|
2196
|
+
const key = typeof item === "string" ? normalizeQuotedString(item) : item;
|
|
2197
|
+
if (!seen.has(key)) {
|
|
2198
|
+
seen.add(key);
|
|
2199
|
+
result.push(item);
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
return result;
|
|
2203
|
+
}
|
|
2204
|
+
/**
|
|
2205
|
+
* Merge pnpm workspace manifests by filling missing fields only.
|
|
2206
|
+
* Existing values take precedence; arrays are deduped while keeping target order.
|
|
2207
|
+
*/
|
|
2208
|
+
function mergeWorkspaceManifest(source, target) {
|
|
2209
|
+
const normalizedSource = normalizeWorkspaceManifest(source);
|
|
2210
|
+
const normalizedTarget = normalizeWorkspaceManifest(target);
|
|
2211
|
+
const result = { ...normalizedTarget };
|
|
2212
|
+
for (const [key, value] of Object.entries(normalizedSource)) {
|
|
2213
|
+
const current = normalizedTarget[key];
|
|
2214
|
+
if (current === void 0) {
|
|
2215
|
+
result[key] = value;
|
|
2216
|
+
continue;
|
|
2217
|
+
}
|
|
2218
|
+
if (Array.isArray(current) && Array.isArray(value)) {
|
|
2219
|
+
result[key] = mergeUniqueArray(current, value);
|
|
2220
|
+
continue;
|
|
2221
|
+
}
|
|
2222
|
+
if (isPlainObject(current) && isPlainObject(value)) {
|
|
2223
|
+
result[key] = mergeWorkspaceManifest(value, current);
|
|
2224
|
+
continue;
|
|
2225
|
+
}
|
|
2226
|
+
result[key] = current;
|
|
2227
|
+
}
|
|
2228
|
+
return result;
|
|
2229
|
+
}
|
|
2230
|
+
//#endregion
|
|
2231
|
+
//#region src/commands/upgrade/index.ts
|
|
2232
|
+
const crlfPattern = /\r\n/g;
|
|
2233
|
+
function normalizeEol(input) {
|
|
2234
|
+
return input.replace(crlfPattern, "\n");
|
|
2235
|
+
}
|
|
2236
|
+
function normalizeGitignoreLine(line) {
|
|
2237
|
+
const trimmed = line.trim();
|
|
2238
|
+
if (!trimmed) return "";
|
|
2239
|
+
if (trimmed.startsWith("#")) return `#${trimmed.slice(1).trim()}`;
|
|
2240
|
+
return trimmed;
|
|
2241
|
+
}
|
|
2242
|
+
function isTextEquivalent(left, right) {
|
|
2243
|
+
return normalizeEol(left).trimEnd() === normalizeEol(right).trimEnd();
|
|
2244
|
+
}
|
|
2245
|
+
function mergeGitignore(source, target) {
|
|
2246
|
+
const sourceLines = normalizeEol(source).split("\n");
|
|
2247
|
+
const result = normalizeEol(target).split("\n");
|
|
2248
|
+
const seen = new Set(result.map((line) => normalizeGitignoreLine(line)).filter(Boolean));
|
|
2249
|
+
for (const line of sourceLines) {
|
|
2250
|
+
const normalized = normalizeGitignoreLine(line);
|
|
2251
|
+
if (!normalized || seen.has(normalized)) continue;
|
|
2252
|
+
seen.add(normalized);
|
|
2253
|
+
result.push(line);
|
|
2254
|
+
}
|
|
2255
|
+
while (result.length) {
|
|
2256
|
+
const last = result.at(-1);
|
|
2257
|
+
if (last === void 0 || last.trim().length > 0) break;
|
|
2258
|
+
result.pop();
|
|
2259
|
+
}
|
|
2260
|
+
return `${result.join("\n")}\n`;
|
|
2261
|
+
}
|
|
2262
|
+
/**
|
|
2263
|
+
* 将 assets 目录的模版文件同步到工程中,实现一键升级脚手架能力。
|
|
2264
|
+
*/
|
|
2265
|
+
async function upgradeMonorepo(opts) {
|
|
2266
|
+
await ensureTemplateAssetsPrepared();
|
|
2267
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
2268
|
+
const upgradeConfig = await resolveCommandConfig("upgrade", cwd);
|
|
2269
|
+
const merged = {
|
|
2270
|
+
cwd,
|
|
2271
|
+
outDir: "",
|
|
2272
|
+
...upgradeConfig ?? {},
|
|
2273
|
+
...opts
|
|
2274
|
+
};
|
|
2275
|
+
const outDir = merged.outDir ?? "";
|
|
2276
|
+
const absOutDir = path.isAbsolute(outDir) ? outDir : path.join(cwd, outDir);
|
|
2277
|
+
const repoName = await new GitClient({ baseDir: cwd }).getRepoName();
|
|
2278
|
+
const useCoreAssets = merged.core ?? false;
|
|
2279
|
+
merged.core = useCoreAssets;
|
|
2280
|
+
const baseTargets = getAssetTargets(useCoreAssets);
|
|
2281
|
+
const configTargets = upgradeConfig?.targets ?? [];
|
|
2282
|
+
const mergeTargets = upgradeConfig?.mergeTargets;
|
|
2283
|
+
let targets = configTargets.length ? mergeTargets === false ? [...configTargets] : [...new Set([...baseTargets, ...configTargets])] : baseTargets;
|
|
2284
|
+
if (merged.interactive) targets = await checkbox({
|
|
2285
|
+
message: "选择你需要的文件",
|
|
2286
|
+
choices: targets.map((x) => {
|
|
2287
|
+
return {
|
|
2288
|
+
value: x,
|
|
2289
|
+
checked: true
|
|
2290
|
+
};
|
|
2291
|
+
})
|
|
2292
|
+
});
|
|
2293
|
+
const regexpArr = targets.map((x) => {
|
|
2294
|
+
return new RegExp(`^${escapeStringRegexp(x)}`);
|
|
2295
|
+
});
|
|
2296
|
+
const skipChangesetMarkdown = upgradeConfig?.skipChangesetMarkdown ?? true;
|
|
2297
|
+
const scriptOverrides = upgradeConfig?.scripts;
|
|
2298
|
+
const skipOverwrite = merged.skipOverwrite;
|
|
2299
|
+
const buildWriteIntentOptions = (source) => {
|
|
2300
|
+
return skipOverwrite === void 0 ? { source } : {
|
|
2301
|
+
skipOverwrite,
|
|
2302
|
+
source
|
|
2303
|
+
};
|
|
2304
|
+
};
|
|
2305
|
+
const pendingOverwrites = [];
|
|
2306
|
+
for await (const file of klaw(assetsDir, { filter(p) {
|
|
2307
|
+
return isMatch(toWorkspaceGitignorePath(path.relative(assetsDir, p)), regexpArr);
|
|
2308
|
+
} })) {
|
|
2309
|
+
if (!file.stats.isFile()) continue;
|
|
2310
|
+
const relPath = toWorkspaceGitignorePath(path.relative(assetsDir, file.path));
|
|
2311
|
+
if (skipChangesetMarkdown && relPath.startsWith(".changeset/") && relPath.endsWith(".md")) continue;
|
|
2312
|
+
const targetPath = path.resolve(absOutDir, relPath);
|
|
2313
|
+
try {
|
|
2314
|
+
if (relPath === "package.json") {
|
|
2315
|
+
if (!await fs$1.pathExists(targetPath)) continue;
|
|
2316
|
+
const sourcePkgJson = await fs$1.readJson(file.path);
|
|
2317
|
+
const targetPkgJson = await fs$1.readJson(targetPath);
|
|
2318
|
+
setPkgJson(sourcePkgJson, targetPkgJson, scriptOverrides ? { scripts: scriptOverrides } : void 0);
|
|
2319
|
+
const data = `${JSON.stringify(targetPkgJson, void 0, 2)}\n`;
|
|
2320
|
+
const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
|
|
2321
|
+
const action = async () => {
|
|
2322
|
+
await fs$1.outputFile(targetPath, data, "utf8");
|
|
2323
|
+
logger.success(targetPath);
|
|
2324
|
+
};
|
|
2325
|
+
await scheduleOverwrite(intent, {
|
|
2326
|
+
relPath,
|
|
2327
|
+
targetPath,
|
|
2328
|
+
action,
|
|
2329
|
+
pending: pendingOverwrites
|
|
2330
|
+
});
|
|
2331
|
+
continue;
|
|
2332
|
+
}
|
|
2333
|
+
if (relPath === "pnpm-workspace.yaml") {
|
|
2334
|
+
const sourceManifest = normalizeWorkspaceManifest(YAML.parse(await fs$1.readFile(file.path, "utf8")));
|
|
2335
|
+
const exists = await fs$1.pathExists(targetPath);
|
|
2336
|
+
const targetManifest = exists ? normalizeWorkspaceManifest(YAML.parse(await fs$1.readFile(targetPath, "utf8"))) : normalizeWorkspaceManifest({});
|
|
2337
|
+
const mergedManifest = exists ? mergeWorkspaceManifest(sourceManifest, targetManifest) : sourceManifest;
|
|
2338
|
+
const data = YAML.stringify(mergedManifest, { singleQuote: true });
|
|
2339
|
+
const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
|
|
2340
|
+
const action = async () => {
|
|
2341
|
+
await fs$1.outputFile(targetPath, data, "utf8");
|
|
2342
|
+
logger.success(targetPath);
|
|
2343
|
+
};
|
|
2344
|
+
await scheduleOverwrite(intent, {
|
|
2345
|
+
relPath,
|
|
2346
|
+
targetPath,
|
|
2347
|
+
action,
|
|
2348
|
+
pending: pendingOverwrites
|
|
2349
|
+
});
|
|
2350
|
+
continue;
|
|
2351
|
+
}
|
|
2352
|
+
if (relPath === ".gitignore") {
|
|
2353
|
+
const source = await fs$1.readFile(file.path, "utf8");
|
|
2354
|
+
const exists = await fs$1.pathExists(targetPath);
|
|
2355
|
+
const target = exists ? await fs$1.readFile(targetPath, "utf8") : "";
|
|
2356
|
+
const data = exists ? mergeGitignore(source, target) : source;
|
|
2357
|
+
if (exists && isTextEquivalent(target, data)) continue;
|
|
2358
|
+
const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
|
|
2359
|
+
const action = async () => {
|
|
2360
|
+
await fs$1.outputFile(targetPath, data, "utf8");
|
|
2361
|
+
logger.success(targetPath);
|
|
2362
|
+
};
|
|
2363
|
+
await scheduleOverwrite(intent, {
|
|
2364
|
+
relPath,
|
|
2365
|
+
targetPath,
|
|
2366
|
+
action,
|
|
2367
|
+
pending: pendingOverwrites
|
|
2368
|
+
});
|
|
2369
|
+
continue;
|
|
2370
|
+
}
|
|
2371
|
+
if (relPath === "AGENTS.md") {
|
|
2372
|
+
const source = await fs$1.readFile(file.path, "utf8");
|
|
2373
|
+
const exists = await fs$1.pathExists(targetPath);
|
|
2374
|
+
const target = exists ? await fs$1.readFile(targetPath, "utf8") : "";
|
|
2375
|
+
const data = exists ? mergeAgentsMarkdown(source, target) : source;
|
|
2376
|
+
if (exists && isAgentsMarkdownEquivalent(target, data)) continue;
|
|
2377
|
+
const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
|
|
2378
|
+
const action = async () => {
|
|
2379
|
+
await fs$1.outputFile(targetPath, data, "utf8");
|
|
2380
|
+
logger.success(targetPath);
|
|
2381
|
+
};
|
|
2382
|
+
await scheduleOverwrite(intent, {
|
|
2383
|
+
relPath,
|
|
2384
|
+
targetPath,
|
|
2385
|
+
action,
|
|
2386
|
+
pending: pendingOverwrites
|
|
2387
|
+
});
|
|
2388
|
+
continue;
|
|
2389
|
+
}
|
|
2390
|
+
if (relPath === ".changeset/config.json" && repoName) {
|
|
2391
|
+
const changesetJson = await fs$1.readJson(file.path);
|
|
2392
|
+
setByPath(changesetJson, "changelog.1.repo", repoName);
|
|
2393
|
+
const data = `${JSON.stringify(changesetJson, void 0, 2)}\n`;
|
|
2394
|
+
const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
|
|
2395
|
+
const action = async () => {
|
|
2396
|
+
await fs$1.outputFile(targetPath, data, "utf8");
|
|
2397
|
+
logger.success(targetPath);
|
|
2398
|
+
};
|
|
2399
|
+
await scheduleOverwrite(intent, {
|
|
2400
|
+
relPath,
|
|
2401
|
+
targetPath,
|
|
2402
|
+
action,
|
|
2403
|
+
pending: pendingOverwrites
|
|
2404
|
+
});
|
|
2405
|
+
continue;
|
|
2406
|
+
}
|
|
2407
|
+
if (relPath === "LICENSE") {
|
|
2408
|
+
const source = await fs$1.readFile(file.path);
|
|
2409
|
+
const intent = await evaluateWriteIntent(targetPath, {
|
|
2410
|
+
skipOverwrite: true,
|
|
2411
|
+
source
|
|
2412
|
+
});
|
|
2413
|
+
const action = async () => {
|
|
2414
|
+
await fs$1.outputFile(targetPath, source);
|
|
2415
|
+
logger.success(targetPath);
|
|
2416
|
+
};
|
|
2417
|
+
await scheduleOverwrite(intent, {
|
|
2418
|
+
relPath,
|
|
2419
|
+
targetPath,
|
|
2420
|
+
action,
|
|
2421
|
+
pending: pendingOverwrites
|
|
2422
|
+
});
|
|
2423
|
+
continue;
|
|
2424
|
+
}
|
|
2425
|
+
if (relPath === ".github/ISSUE_TEMPLATE/config.yml") {
|
|
2426
|
+
const data = updateIssueTemplateConfig(await fs$1.readFile(file.path, "utf8"), repoName);
|
|
2427
|
+
const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(data));
|
|
2428
|
+
const action = async () => {
|
|
2429
|
+
await fs$1.outputFile(targetPath, data);
|
|
2430
|
+
logger.success(targetPath);
|
|
2431
|
+
};
|
|
2432
|
+
await scheduleOverwrite(intent, {
|
|
2433
|
+
relPath,
|
|
2434
|
+
targetPath,
|
|
2435
|
+
action,
|
|
2436
|
+
pending: pendingOverwrites
|
|
2437
|
+
});
|
|
2438
|
+
continue;
|
|
2439
|
+
}
|
|
2440
|
+
const source = await fs$1.readFile(file.path);
|
|
2441
|
+
const intent = await evaluateWriteIntent(targetPath, buildWriteIntentOptions(source));
|
|
2442
|
+
const action = async () => {
|
|
2443
|
+
await fs$1.outputFile(targetPath, source);
|
|
2444
|
+
logger.success(targetPath);
|
|
2445
|
+
};
|
|
2446
|
+
await scheduleOverwrite(intent, {
|
|
2447
|
+
relPath,
|
|
2448
|
+
targetPath,
|
|
2449
|
+
action,
|
|
2450
|
+
pending: pendingOverwrites
|
|
2451
|
+
});
|
|
2452
|
+
} catch (error) {
|
|
2453
|
+
if (isIgnorableFsError(error)) continue;
|
|
2454
|
+
throw error;
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
await flushPendingOverwrites(pendingOverwrites);
|
|
2458
|
+
}
|
|
2459
|
+
//#endregion
|
|
2460
|
+
//#region src/commands/index.ts
|
|
2461
|
+
var commands_exports = /* @__PURE__ */ __exportAll({
|
|
2462
|
+
GitClient: () => GitClient,
|
|
2463
|
+
checkTemplates: () => checkTemplates,
|
|
2464
|
+
cleanProjects: () => cleanProjects,
|
|
2465
|
+
collectEnvInfo: () => collectEnvInfo,
|
|
2466
|
+
collectEnvPaths: () => collectEnvPaths,
|
|
2467
|
+
collectEnvSnapshot: () => collectEnvSnapshot,
|
|
2468
|
+
collectEnvSupportBundle: () => collectEnvSupportBundle,
|
|
2469
|
+
createNewProject: () => createNewProject,
|
|
2470
|
+
createTimestampFolderName: () => createTimestampFolderName,
|
|
2471
|
+
defaultAgenticBaseDir: () => defaultAgenticBaseDir,
|
|
2472
|
+
generateAgenticTemplate: () => generateAgenticTemplate,
|
|
2473
|
+
generateAgenticTemplates: () => generateAgenticTemplates,
|
|
2474
|
+
getCreateChoices: () => getCreateChoices,
|
|
2475
|
+
getSkillTargetPaths: () => getSkillTargetPaths,
|
|
2476
|
+
getTemplateMap: () => getTemplateMap,
|
|
2477
|
+
getWorkspaceData: () => getWorkspaceData,
|
|
2478
|
+
getWorkspacePackages: () => getWorkspacePackages,
|
|
2479
|
+
init: () => init,
|
|
2480
|
+
initMetadata: () => initMetadata,
|
|
2481
|
+
initTooling: () => initTooling,
|
|
2482
|
+
initToolingTargets: () => initToolingTargets,
|
|
2483
|
+
inspectMonorepoConfig: () => inspectMonorepoConfig,
|
|
2484
|
+
loadAgenticTasks: () => loadAgenticTasks,
|
|
2485
|
+
normalizeInitToolingTargets: () => normalizeInitToolingTargets,
|
|
2486
|
+
resolveCreateNewProjectPlan: () => resolveCreateNewProjectPlan,
|
|
2487
|
+
resolveRecommendedCheckPlan: () => resolveRecommendedCheckPlan,
|
|
2488
|
+
runDoctor: () => runDoctor,
|
|
2489
|
+
runRecommendedCheck: () => runRecommendedCheck,
|
|
2490
|
+
setVscodeBinaryMirror: () => setVscodeBinaryMirror,
|
|
2491
|
+
skillTargets: () => skillTargets,
|
|
2492
|
+
syncSkills: () => syncSkills,
|
|
2493
|
+
templateMap: () => templateMap,
|
|
2494
|
+
upgradeMonorepo: () => upgradeMonorepo,
|
|
2495
|
+
verifyCommitMsg: () => verifyCommitMsg,
|
|
2496
|
+
verifyPreCommit: () => verifyPreCommit,
|
|
2497
|
+
verifyPrePush: () => verifyPrePush,
|
|
2498
|
+
verifyStagedTypecheck: () => verifyStagedTypecheck
|
|
2499
|
+
});
|
|
2500
|
+
//#endregion
|
|
2501
|
+
export { isFileChanged as A, verifyStagedTypecheck as B, getSkillTargetPaths as C, isMatch as D, escapeStringRegexp as E, resolveRecommendedCheckPlan as F, loadAgenticTasks as G, defaultAgenticBaseDir as H, runRecommendedCheck as I, GitClient as K, verifyCommitMsg as L, toPublishGitignorePath as M, toWorkspaceGitignorePath as N, setByPath as O, updateIssueTemplateConfig as P, verifyPreCommit as R, cleanProjects as S, syncSkills as T, generateAgenticTemplate as U, createTimestampFolderName as V, generateAgenticTemplates as W, getCreateChoices as _, init as a, templateMap as b, normalizeInitToolingTargets as c, collectEnvPaths as d, collectEnvSnapshot as f, defaultTemplate as g, createNewProject as h, setVscodeBinaryMirror as i, isGitignoreFile as j, getFileHash as k, createContext as l, runDoctor as m, upgradeMonorepo as n, initMetadata as o, collectEnvSupportBundle as p, checkTemplates as r, initTooling as s, commands_exports as t, collectEnvInfo as u, getTemplateMap as v, skillTargets as w, inspectMonorepoConfig as x, resolveCreateNewProjectPlan as y, verifyPrePush as z };
|