@icebreakers/monorepo 5.6.0 → 5.7.1
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 +2 -0
- package/dist/baseline-CRCTiMNM.mjs +146 -0
- package/dist/bundle-B9vRch4R.mjs +49 -0
- package/dist/catalog-D0Sk385O.mjs +299 -0
- package/dist/cli.mjs +1487 -156
- package/dist/commands-Bj0sX3R9.mjs +13849 -0
- package/dist/config-Dg-voj8q.mjs +66 -0
- package/dist/{create-flow-CXRhfGbb.mjs → create-flow-BWFWDWR4.mjs} +90 -24
- package/dist/deps-BbykICqB.mjs +47 -0
- package/dist/execute-D2GlX018.mjs +68 -0
- package/dist/execute-DI1mgVLv.mjs +663 -0
- package/dist/format-Dbs0fupU.mjs +28 -0
- package/dist/index-CoCTFWZJ.d.mts +2150 -0
- package/dist/index.d.mts +1738 -112
- package/dist/index.mjs +60 -7
- package/dist/inputs-BKtLcrQ9.mjs +50 -0
- package/dist/npm-Bh6HBy5V.mjs +82 -0
- package/dist/plan-CxySMaLN.mjs +75 -0
- package/dist/run-D_bceMqf.mjs +165 -0
- package/dist/save-DzIWKs0T.mjs +79 -0
- package/dist/scan-B_-E6BWh.mjs +293 -0
- package/dist/template-drift-D0hKxixr.mjs +2740 -0
- package/dist/tooling-entry.d.mts +1 -1
- package/dist/tooling-entry.mjs +2 -2
- package/dist/transaction-DFam8_dp.mjs +168 -0
- package/dist/tsconfig-BZ6E1fBA.mjs +1483 -0
- package/dist/{vitest-Blzbh8xZ.mjs → vitest-XbNmiloj.mjs} +1 -1
- package/dist/workspace-tasks-C5W-QwWj.mjs +4435 -0
- package/package.json +22 -4
- package/resources/api-report/runner.cjs +76 -0
- package/resources/devcontainer/setup.mjs +36 -0
- package/resources/knip/reporter.mjs +46 -0
- package/resources/maintenance/migration-lanes.mjs +141 -0
- package/resources/maintenance/migration-lock.mjs +119 -0
- package/resources/maintenance/migrations.mjs +215 -0
- package/resources/maintenance/presets.mjs +130 -0
- package/resources/maintenance/validate.mjs +233 -0
- package/resources/maintenance/workflow.yml +151 -0
- package/resources/skills/repoctl/SKILL.md +2 -0
- package/resources/skills/repoctl/references/commands.md +224 -13
- package/resources/skills/repoctl/references/config.md +70 -6
- package/resources/skills/repoctl/references/dependencies.md +37 -0
- package/resources/skills/repoctl/references/knip.md +34 -0
- package/resources/skills/repoctl/references/templates.md +23 -0
- package/dist/commands-D4xZQ5t-.mjs +0 -5685
- package/dist/config-p842Knhq.mjs +0 -114
- package/dist/index-Bl_PB2Ch.d.mts +0 -1039
- package/dist/tsconfig-BrjI_5yI.mjs +0 -75
- package/dist/types-MAUIQpfp.mjs +0 -499
- package/dist/workspace-MCKewElu.mjs +0 -123
package/dist/cli.mjs
CHANGED
|
@@ -1,24 +1,64 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { Ct as message, Et as supportedLocales, J as getWorkspaceGraph, Q as whyWorkspaceDependency, St as localize, Z as getWorkspaceImpact, a as inspectWorkspaceOwners, i as planCodeowners, jt as fs$1, n as locateWorkspace, r as applyCodeownersPlan, t as getWorkspaceTaskCatalog, vt as cliName, wt as repoctlLocale } from "./workspace-tasks-C5W-QwWj.mjs";
|
|
2
|
+
import { f as logger } from "./execute-DI1mgVLv.mjs";
|
|
3
|
+
import { C as applyOrganizationPresetAssets, D as applyInstallSecurityPreset, Dt as createTemplateCatalog, Et as resolveRemoteTemplateSource, F as upgradeMonorepo, I as formatUpgradePlan, M as applyPublicApiUpdate, Mt as explainMonorepoConfig, N as planPublicApiUpdate, Nt as sanitizeConfigReport, O as planInstallSecurityPreset, Ot as resolveTemplateCatalog, P as formatPublicApiReport, Pt as validateConfigFile, _ as applyProjectReferencesPlan, a as planWorkspaceMove, b as getMaintenanceWorkflow, c as applyToolingCapability, d as planTemplateValidation, f as releaseSnapshot, g as syncProjectReferences, gt as planUpgrade, h as checkProjectReferences, i as applyWorkspaceMovePlan, j as checkPublicApi, k as checkPeerDependencies, kt as loadTemplateCatalogContext, l as planToolingCapability, m as createReleasePlan, n as applyWorkspaceRemovalPlan, o as applyWorkspaceArtifactPlan, r as planWorkspaceRemoval, s as planWorkspaceArtifact, st as initToolingTargets, tt as renderReleasePullRequest, u as validateTemplate, v as planProjectReferences, vt as applyUpgradePlan, w as planOrganizationPresetAssets, x as prepareMaintenanceUpgrade, y as checkPackages } from "./commands-Bj0sX3R9.mjs";
|
|
4
|
+
import { S as canonicalDirectory, W as splitConfigPath, _ as listToolingCapabilities, d as loadMonorepoConfig, f as loadMonorepoConfigDetails, j as ConfigValidationError, k as version, p as resolveCommandConfig } from "./tsconfig-BZ6E1fBA.mjs";
|
|
5
|
+
import { s as resolveCommandValues } from "./scan-B_-E6BWh.mjs";
|
|
6
|
+
import { S as checkDependencyAdmission, f as inspectInstallSecurity, x as checkWorkspaceBoundaries } from "./template-drift-D0hKxixr.mjs";
|
|
7
|
+
import { findWorkspaceDir } from "@pnpm/find-workspace-dir";
|
|
3
8
|
import path from "pathe";
|
|
4
9
|
import process from "node:process";
|
|
10
|
+
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
5
11
|
import path$1 from "node:path";
|
|
6
|
-
import
|
|
12
|
+
import { select } from "@icebreakers/monorepo-templates";
|
|
7
13
|
import pc from "picocolors";
|
|
14
|
+
import os from "node:os";
|
|
8
15
|
import { Command, Option } from "commander";
|
|
16
|
+
//#region src/cli/config-preflight.ts
|
|
17
|
+
function registerConfigPreflight(program, cwd) {
|
|
18
|
+
program.hook("preAction", async (_parent, action) => {
|
|
19
|
+
if (action.name() === "templates" && action.parent === program) return;
|
|
20
|
+
if (action.name() === "snapshot" && action.parent?.name() === "release" && action.parent.parent === program) return;
|
|
21
|
+
let command = action;
|
|
22
|
+
while (command) {
|
|
23
|
+
if (command.name() === "config") return;
|
|
24
|
+
command = command.parent;
|
|
25
|
+
}
|
|
26
|
+
await loadMonorepoConfigDetails(cwd);
|
|
27
|
+
const root = await findWorkspaceDir(cwd);
|
|
28
|
+
if (root && root !== cwd) await loadMonorepoConfigDetails(root);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function reportCliFailure(error) {
|
|
32
|
+
if (!(error instanceof ConfigValidationError)) throw error;
|
|
33
|
+
const output = process.argv.includes("--json") ? JSON.stringify({
|
|
34
|
+
schemaVersion: 1,
|
|
35
|
+
valid: false,
|
|
36
|
+
diagnostics: error.diagnostics
|
|
37
|
+
}) : error.message;
|
|
38
|
+
process.stderr.write(`${output}\n`);
|
|
39
|
+
process.exitCode = 1;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
9
42
|
//#region src/cli/commands/ai.ts
|
|
10
43
|
async function handleAiPromptCreate(cwd, opts) {
|
|
11
44
|
const [{ input }, { createTimestampFolderName, defaultAgenticBaseDir, generateAgenticTemplate, generateAgenticTemplates, loadAgenticTasks }, { resolveCommandConfig }] = await Promise.all([
|
|
12
45
|
import("@icebreakers/monorepo-templates"),
|
|
13
|
-
import("./commands-
|
|
14
|
-
import("./
|
|
46
|
+
import("./commands-Bj0sX3R9.mjs").then((n) => n.t),
|
|
47
|
+
import("./tsconfig-BZ6E1fBA.mjs").then((n) => n.c)
|
|
15
48
|
]);
|
|
16
49
|
const aiConfig = await resolveCommandConfig("ai", cwd);
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
50
|
+
const resolved = resolveCommandValues("ai", aiConfig, {
|
|
51
|
+
format: opts.format,
|
|
52
|
+
force: opts.force,
|
|
53
|
+
output: opts.output,
|
|
54
|
+
baseDir: opts.dir,
|
|
55
|
+
tasksFile: opts.tasks
|
|
56
|
+
}).values;
|
|
57
|
+
const format = resolved.format;
|
|
58
|
+
const force = resolved.force;
|
|
59
|
+
const output = resolved.output;
|
|
60
|
+
const baseDir = resolved.baseDir ?? defaultAgenticBaseDir;
|
|
61
|
+
const tasksFile = resolved.tasksFile;
|
|
22
62
|
const templateName = opts.name;
|
|
23
63
|
if (Boolean(tasksFile && !opts.output && !opts.name)) {
|
|
24
64
|
if (!tasksFile) throw new Error(localize("A tasks file path is required when using tasks mode.", "使用 tasks 模式时必须提供任务文件路径。"));
|
|
@@ -55,6 +95,57 @@ function registerAiCommands(program, cwd) {
|
|
|
55
95
|
});
|
|
56
96
|
}
|
|
57
97
|
//#endregion
|
|
98
|
+
//#region src/cli/commands/config-explanation.ts
|
|
99
|
+
function parseConfigOverrides(inputs = []) {
|
|
100
|
+
const result = {};
|
|
101
|
+
for (const input of inputs) {
|
|
102
|
+
const split = input.indexOf("=");
|
|
103
|
+
const parts = input.slice(0, split).split(".");
|
|
104
|
+
if (split < 1 || parts.some((part) => !/^[\w-]+$/.test(part) || [
|
|
105
|
+
"__proto__",
|
|
106
|
+
"constructor",
|
|
107
|
+
"prototype"
|
|
108
|
+
].includes(part))) throw invalidOverride();
|
|
109
|
+
let value;
|
|
110
|
+
try {
|
|
111
|
+
value = JSON.parse(input.slice(split + 1));
|
|
112
|
+
} catch {
|
|
113
|
+
throw invalidOverride();
|
|
114
|
+
}
|
|
115
|
+
let current = result;
|
|
116
|
+
for (const part of parts.slice(0, -1)) {
|
|
117
|
+
if (current[part] !== void 0 && (!current[part] || typeof current[part] !== "object" || Array.isArray(current[part]))) throw invalidOverride();
|
|
118
|
+
current[part] ??= {};
|
|
119
|
+
current = current[part];
|
|
120
|
+
}
|
|
121
|
+
current[parts.at(-1)] = value;
|
|
122
|
+
}
|
|
123
|
+
return result;
|
|
124
|
+
}
|
|
125
|
+
function invalidOverride() {
|
|
126
|
+
return new ConfigValidationError([{
|
|
127
|
+
id: "config.invalid-value",
|
|
128
|
+
path: "overrides",
|
|
129
|
+
actualType: "string",
|
|
130
|
+
expected: "field=JSON",
|
|
131
|
+
suggestion: "Use a command field path followed by = and a JSON value; quote it for your shell."
|
|
132
|
+
}]);
|
|
133
|
+
}
|
|
134
|
+
function formatConfigExplanation(report) {
|
|
135
|
+
if (!report.valid) return report.diagnostics.map((item) => `${item.id}: ${item.path || "<root>"} (${item.actualType}); ${item.suggestion}`).join("\n");
|
|
136
|
+
if (!report.effective) return "";
|
|
137
|
+
const { command, values, origins } = report.effective;
|
|
138
|
+
return [`context: ${command}`, ...Object.entries(origins).map(([field, source]) => {
|
|
139
|
+
let value = values;
|
|
140
|
+
for (const part of splitConfigPath(field)) {
|
|
141
|
+
if (value === "[redacted]") break;
|
|
142
|
+
value = value && typeof value === "object" && !Array.isArray(value) ? value[part] : null;
|
|
143
|
+
}
|
|
144
|
+
const identity = report.effective?.sources[field];
|
|
145
|
+
return `${field}: ${JSON.stringify(value)} (${identity?.kind === "preset" ? `${identity.packageName}@${identity.version}` : source})`;
|
|
146
|
+
})].join("\n");
|
|
147
|
+
}
|
|
148
|
+
//#endregion
|
|
58
149
|
//#region src/cli/commands/config.ts
|
|
59
150
|
function formatConfigInspection(inspection) {
|
|
60
151
|
const commandKeys = Object.keys(inspection.config.commands ?? {});
|
|
@@ -63,7 +154,8 @@ function formatConfigInspection(inspection) {
|
|
|
63
154
|
localize(`cwd: ${inspection.cwd}`, `当前目录:${inspection.cwd}`),
|
|
64
155
|
localize(`file: ${inspection.file ?? "-"}`, `文件:${inspection.file ?? "-"}`),
|
|
65
156
|
localize(`commands: ${commandKeys.length > 0 ? commandKeys.join(", ") : "-"}`, `命令:${commandKeys.length > 0 ? commandKeys.join(", ") : "-"}`),
|
|
66
|
-
localize(`tooling: ${toolingKeys.length > 0 ? toolingKeys.join(", ") : "-"}`, `Tooling:${toolingKeys.length > 0 ? toolingKeys.join(", ") : "-"}`)
|
|
157
|
+
localize(`tooling: ${toolingKeys.length > 0 ? toolingKeys.join(", ") : "-"}`, `Tooling:${toolingKeys.length > 0 ? toolingKeys.join(", ") : "-"}`),
|
|
158
|
+
...(inspection.layers ?? []).map((layer) => `layer: ${layer.source.kind === "preset" ? `${layer.source.packageName}@${layer.source.version}` : layer.source.file ?? "project"}`)
|
|
67
159
|
].join("\n");
|
|
68
160
|
}
|
|
69
161
|
function formatMarkdownTable$5(rows) {
|
|
@@ -112,21 +204,184 @@ function redactConfigInspection(inspection) {
|
|
|
112
204
|
[os.homedir(), "<home>"]
|
|
113
205
|
].filter(([search], index, entries) => search.length > 0 && entries.findIndex(([value]) => value === search) === index).sort(([left], [right]) => right.length - left.length));
|
|
114
206
|
}
|
|
115
|
-
async function emitConfigInspection(inspection, opts, cwd) {
|
|
116
|
-
const
|
|
117
|
-
|
|
207
|
+
async function emitConfigInspection(inspection, opts, cwd, explanation) {
|
|
208
|
+
const safe = {
|
|
209
|
+
...inspection,
|
|
210
|
+
...explanation,
|
|
211
|
+
config: sanitizeConfigReport(inspection.config)
|
|
212
|
+
};
|
|
213
|
+
const outputInspection = opts.redact ? redactConfigInspection(safe) : safe;
|
|
214
|
+
const detail = explanation ? formatConfigExplanation(opts.redact ? redactConfigInspection(explanation) : explanation) : "";
|
|
215
|
+
const content = opts.json ? JSON.stringify(outputInspection, null, 2) : opts.markdown ? `${formatConfigInspectionMarkdown(outputInspection)}${detail ? `\n\n${detail}` : ""}` : `${formatConfigInspection(outputInspection)}${detail ? `\n${detail}` : ""}`;
|
|
118
216
|
if (!opts.out) {
|
|
119
|
-
|
|
217
|
+
process.stdout.write(`${content}\n`);
|
|
120
218
|
return;
|
|
121
219
|
}
|
|
122
220
|
const outFile = path.resolve(cwd, opts.out);
|
|
123
|
-
await fs.outputFile(outFile, `${content}\n`, "utf8");
|
|
221
|
+
await fs$1.outputFile(outFile, `${content}\n`, "utf8");
|
|
124
222
|
logger.success(localize(`Wrote ${path.relative(cwd, outFile)}`, `已写入 ${path.relative(cwd, outFile)}`));
|
|
125
223
|
}
|
|
126
224
|
function registerConfigCommands(program, cwd) {
|
|
127
|
-
program.command("config").alias("cfg").description(localize("Configuration commands", "配置命令"))
|
|
128
|
-
|
|
129
|
-
|
|
225
|
+
const configCommand = program.command("config").alias("cfg").description(localize("Configuration commands", "配置命令"));
|
|
226
|
+
configCommand.command("inspect").description(localize("Show the active repoctl config file and resolved configuration", "输出当前 repoctl 配置文件和已解析配置")).alias("i").option("--json", localize("Output JSON for scripts", "输出 JSON,方便脚本消费")).option("--markdown", localize("Output Markdown", "输出 Markdown,方便粘贴到 issue 或 PR")).option("--out <file>", localize("Write output to a file", "把当前输出写入文件")).option("--redact", localize("Redact cwd, configDir, and home paths", "脱敏 cwd/configDir/home 绝对路径后再输出")).option("--command <context>", localize("Explain effective ai/clean/create/deps/doctor/env/init/mirror/release/upgrade values", "解释 ai/clean/create/deps/doctor/env/init/mirror/release/upgrade 的最终配置")).option("--set <field=JSON>", localize("Preview a config override; repeatable", "预览配置覆盖,可重复使用"), (value, previous) => [...previous, value], []).action(async (opts) => {
|
|
227
|
+
try {
|
|
228
|
+
if (opts.command || opts.set?.length) {
|
|
229
|
+
const report = await explainMonorepoConfig(cwd, {
|
|
230
|
+
...opts.command ? { command: opts.command } : {},
|
|
231
|
+
overrides: parseConfigOverrides(opts.set)
|
|
232
|
+
});
|
|
233
|
+
if (!report.valid) throw new ConfigValidationError(report.diagnostics);
|
|
234
|
+
await emitConfigInspection(report, opts, cwd, report);
|
|
235
|
+
} else {
|
|
236
|
+
const { inspectMonorepoConfig } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
237
|
+
await emitConfigInspection(await inspectMonorepoConfig(cwd), opts, cwd);
|
|
238
|
+
}
|
|
239
|
+
} catch (error) {
|
|
240
|
+
if (!(error instanceof ConfigValidationError)) throw error;
|
|
241
|
+
if (opts.json) process.stdout.write(`${JSON.stringify({
|
|
242
|
+
schemaVersion: 1,
|
|
243
|
+
valid: false,
|
|
244
|
+
diagnostics: error.diagnostics
|
|
245
|
+
}, null, 2)}\n`);
|
|
246
|
+
else process.stdout.write(`${error.message}\n`);
|
|
247
|
+
process.exitCode = 1;
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
configCommand.command("validate").description(localize("Validate owned config fields without running commands", "只读校验 repoctl 自有配置字段")).option("--json", localize("Output JSON for scripts", "输出 JSON,方便脚本消费")).action(async (opts) => {
|
|
251
|
+
const report = await validateConfigFile(cwd);
|
|
252
|
+
if (opts.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
253
|
+
else process.stdout.write(`${report.valid ? "Configuration is valid." : new ConfigValidationError(report.diagnostics).message}\n`);
|
|
254
|
+
if (!report.valid) process.exitCode = 1;
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
//#endregion
|
|
258
|
+
//#region src/cli/commands/deps/admission.ts
|
|
259
|
+
function registerDependencyAdmission(deps, cwd) {
|
|
260
|
+
deps.command("policy").description(localize("Check direct third-party dependency admission", "检查第三方直接依赖准入规则")).option("--json", localize("Output stable JSON", "输出稳定 JSON")).option("--baseline <file>", localize("Compare a reviewed report; missing or incompatible baselines fail", "对比已审核报告;缺失或不兼容基线将失败")).option("--full", localize("Explicitly check all violations, ignoring a baseline", "显式检查全部违规,不使用基线")).option("--strict", localize("Also fail on warnings", "警告也返回失败")).action(async (options) => {
|
|
261
|
+
let baseline;
|
|
262
|
+
if (options.baseline && !options.full) try {
|
|
263
|
+
baseline = JSON.parse(await readFile(options.baseline, "utf8"));
|
|
264
|
+
} catch {
|
|
265
|
+
throw new Error("Cannot read the dependency policy baseline. Supply a valid report or explicitly use --full.");
|
|
266
|
+
}
|
|
267
|
+
const report = await checkDependencyAdmission(cwd, {
|
|
268
|
+
...options.baseline && !options.full ? { baseline } : {},
|
|
269
|
+
...options.full ? { full: true } : {}
|
|
270
|
+
});
|
|
271
|
+
if (options.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
272
|
+
else {
|
|
273
|
+
for (const finding of report.findings) {
|
|
274
|
+
const item = finding.declaration;
|
|
275
|
+
process.stdout.write(`[${finding.baseline}/${finding.status}] ${finding.rule || finding.id}${item ? ` ${item.path} ${item.section}.${item.name} -> ${item.target ?? "?"}` : ""}\n ${finding.detail}${finding.reason ? ` ${finding.reason}` : ""}${finding.alternative ? ` Alternative: ${finding.alternative}` : ""}\n`);
|
|
276
|
+
}
|
|
277
|
+
for (const exception of report.exceptions) process.stdout.write(`[waived] ${exception.rule}: ${exception.workspace} ${exception.section}.${exception.dependency}: ${exception.reason}\n`);
|
|
278
|
+
process.stdout.write(`${report.mode}: ${report.summary.fail} fail, ${report.summary.warn} warn, ${report.summary.existing} existing, ${report.summary.waived} waived\n`);
|
|
279
|
+
}
|
|
280
|
+
if (report.summary.fail || options.strict && report.summary.warn) process.exitCode = 1;
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
//#endregion
|
|
284
|
+
//#region src/cli/commands/deps/catalog.ts
|
|
285
|
+
const output$2 = (value) => process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
286
|
+
function registerCatalogCommands(deps, cwd) {
|
|
287
|
+
const catalog = deps.command("catalog").description(localize("Inspect pnpm catalogs and review coordinated migrations", "巡检 pnpm catalog 并审阅联动迁移"));
|
|
288
|
+
catalog.command("check").description(localize("Inspect references, usage and direct-version bypasses without writing", "只读巡检引用、使用情况和直接版本绕过")).option("--catalog <name>", localize("Catalog policy for direct declarations and migration candidates", "直接声明与迁移候选所采用的 catalog 策略"), "default").option("--json", localize("Output a versioned catalog report", "输出有版本结构的 catalog 报告")).action(async (options) => {
|
|
289
|
+
const { checkCatalogs } = await import("./catalog-D0Sk385O.mjs").then((n) => n.t);
|
|
290
|
+
const report = await checkCatalogs(cwd, options);
|
|
291
|
+
if (options.json) output$2(report);
|
|
292
|
+
else {
|
|
293
|
+
for (const item of report.findings) process.stdout.write(`[${item.code}] ${item.catalog}/${item.dependency}: ${item.path}${item.section ? ` / ${item.section}` : ""}\n`);
|
|
294
|
+
for (const candidate of report.candidates) process.stdout.write(`[${candidate.status}:${candidate.reason}] ${candidate.dependency} / ${candidate.section} / ${candidate.group} -> ${candidate.catalog}\n`);
|
|
295
|
+
}
|
|
296
|
+
if (report.summary.missing || report.summary.direct) process.exitCode = 1;
|
|
297
|
+
});
|
|
298
|
+
catalog.command("plan").description(localize("Preview catalog YAML and consumer manifest changes without writing", "只读预览 catalog YAML 与消费者清单的联动变更")).argument("<dependency>", localize("Dependency to migrate", "待迁移依赖")).requiredOption("--section <section>", localize("Dependency section; peer ranges remain unchanged", "依赖分区;peer 范围保留原样")).option("--catalog <name>", localize("Default or named catalog", "默认或命名 catalog"), "default").option("--group <name>", localize("Configured dependency version group", "已配置的依赖版本组"), "default").option("--to <specifier>", localize("Explicit common subrange for non-equivalent declarations", "不等价声明的明确共同子范围")).option("--dry-run", localize("Preview only (the default)", "仅预览(默认行为)")).option("--json", localize("Output a reviewed plan for catalog apply", "输出可审阅并交给 catalog apply 的计划")).action(async (dependency, options) => {
|
|
299
|
+
const { planCatalogMigration } = await import("./catalog-D0Sk385O.mjs").then((n) => n.t);
|
|
300
|
+
const plan = await planCatalogMigration(cwd, {
|
|
301
|
+
dependency,
|
|
302
|
+
...options
|
|
303
|
+
});
|
|
304
|
+
if (options.json) output$2(plan);
|
|
305
|
+
else {
|
|
306
|
+
for (const file of plan.files) process.stdout.write(`${file.path}\n--- before\n${file.before}\n+++ after\n${file.after}\n`);
|
|
307
|
+
process.stdout.write(localize("Preview only. Review --json output, then run deps catalog apply <plan.json>.\n", "仅预览。审阅 --json 输出后执行 deps catalog apply <plan.json>。\n"));
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
catalog.command("apply").description(localize("Apply a reviewed catalog migration with conflict checks and rollback", "应用已审阅的 catalog 迁移,检查冲突并支持失败恢复")).argument("<plan>", localize("Reviewed JSON plan", "已审阅的 JSON 计划")).option("--json", localize("Output the apply result as JSON", "以 JSON 输出应用结果")).action(async (file, options) => {
|
|
311
|
+
const { applyCatalogMigrationPlan } = await import("./catalog-D0Sk385O.mjs").then((n) => n.t);
|
|
312
|
+
const result = await applyCatalogMigrationPlan(cwd, JSON.parse(await readFile(file, "utf8")));
|
|
313
|
+
if (options.json) output$2(result);
|
|
314
|
+
else process.stdout.write(`${result.status}: ${result.changed.join(", ")}\n${result.nextSteps.join("\n")}\n`);
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/cli/commands/deps/peers.ts
|
|
319
|
+
function registerPeerChecks(deps, cwd) {
|
|
320
|
+
deps.command("peers").description(localize("Check peer promises against development/test versions", "检查 peer 支持范围与开发测试版本是否兼容")).option("--json", localize("Output a versioned JSON report", "输出带版本的 JSON 报告")).option("--strict", localize("Also fail on unknown compatibility", "无法确定兼容性时也失败")).action(async (options) => {
|
|
321
|
+
const report = await checkPeerDependencies(cwd);
|
|
322
|
+
if (options.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
323
|
+
else for (const check of report.checks) process.stdout.write(`[${check.status}] ${check.packageName ?? check.path} / ${check.peer}: ${check.code}\n peer=${check.peerSpecifier}, dev=${check.testSpecifier ?? "(missing)"}, evidence=${check.evidence}${check.testVersion ? `:${check.testVersion}` : ""}\n ${check.detail}\n`);
|
|
324
|
+
if (report.summary.fail || options.strict && report.summary.unknown) process.exitCode = 1;
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
//#endregion
|
|
328
|
+
//#region src/cli/commands/deps.ts
|
|
329
|
+
function output$1(value) {
|
|
330
|
+
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
331
|
+
}
|
|
332
|
+
function registerDepsCommands(program, cwd) {
|
|
333
|
+
const deps = program.command("deps").description(localize("Inspect dependency declarations and review explicit fixes", "检查依赖声明并审阅显式修复"));
|
|
334
|
+
registerPeerChecks(deps, cwd);
|
|
335
|
+
registerDependencyAdmission(deps, cwd);
|
|
336
|
+
registerCatalogCommands(deps, cwd);
|
|
337
|
+
deps.command("check").description(localize("Check dependency consistency without writing or accessing registries", "只读检查依赖版本一致性,不访问 registry")).option("--json", localize("Output the dependency report as JSON", "以 JSON 输出依赖报告")).action(async (options) => {
|
|
338
|
+
const { checkDependencies } = await import("./deps-BbykICqB.mjs").then((n) => n.n);
|
|
339
|
+
const report = await checkDependencies(cwd);
|
|
340
|
+
if (options.json) output$1(report);
|
|
341
|
+
else for (const group of report.groups) {
|
|
342
|
+
process.stdout.write(`[${group.status}] ${group.dependency} / ${group.section} / ${group.group}\n ${group.detail}${group.reason ? ` (${group.reason})` : ""}\n`);
|
|
343
|
+
for (const item of group.occurrences) process.stdout.write(` ${item.path}: ${item.specifier} [${item.protocol}]${item.range ? ` -> ${item.source}@${item.range}` : ""}\n`);
|
|
344
|
+
}
|
|
345
|
+
if (report.summary.equivalent + report.summary.compatible + report.summary.conflict > 0) process.exitCode = 1;
|
|
346
|
+
});
|
|
347
|
+
deps.command("plan").alias("fix").description(localize("Preview an explicit dependency fix; always read-only", "预览显式依赖修复;始终只读")).argument("<dependency>", localize("Dependency name", "依赖名称")).requiredOption("--section <section>", localize("dependencies, devDependencies, peerDependencies or optionalDependencies", "依赖分区:dependencies、devDependencies、peerDependencies 或 optionalDependencies")).requiredOption("--to <specifier>", localize("Explicit target semver range or same-source npm alias", "明确的目标 semver 范围或同源 npm alias")).option("--group <name>", localize("Configured version group", "配置中的版本分组"), "default").option("--dry-run", localize("Preview only (already the default)", "仅预览(默认行为)")).option("--json", localize("Output a serializable plan for deps apply", "输出可交给 deps apply 的 JSON 计划")).action(async (dependency, options) => {
|
|
348
|
+
const { planDependencyFix } = await import("./deps-BbykICqB.mjs").then((n) => n.n);
|
|
349
|
+
const plan = await planDependencyFix(cwd, {
|
|
350
|
+
dependency,
|
|
351
|
+
section: options.section,
|
|
352
|
+
to: options.to,
|
|
353
|
+
group: options.group
|
|
354
|
+
});
|
|
355
|
+
if (options.json) {
|
|
356
|
+
output$1(plan);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
for (const file of plan.files) process.stdout.write(`${file.path} / ${file.section}.${file.dependency}: ${file.before} -> ${file.after}\n`);
|
|
360
|
+
process.stdout.write(localize("Preview only. Save --json output, review it, then run deps apply <plan.json>.\n", "仅预览。保存并审阅 --json 输出,然后执行 deps apply <plan.json>。\n"));
|
|
361
|
+
});
|
|
362
|
+
deps.command("apply").description(localize("Apply a reviewed dependency plan with conflict checks and rollback", "应用已审阅的依赖计划,检查冲突并支持失败回滚")).argument("<plan>", localize("JSON plan file", "JSON 计划文件")).option("--json", localize("Output the result as JSON", "以 JSON 输出结果")).action(async (file, options) => {
|
|
363
|
+
const { applyDependencyFixPlan } = await import("./deps-BbykICqB.mjs").then((n) => n.n);
|
|
364
|
+
const result = await applyDependencyFixPlan(cwd, JSON.parse(await readFile(file, "utf8")));
|
|
365
|
+
if (options.json) output$1(result);
|
|
366
|
+
else {
|
|
367
|
+
process.stdout.write(`${result.status}: ${result.changed.join(", ")}\n`);
|
|
368
|
+
process.stdout.write(localize(`Next, explicitly run:\n${result.nextSteps.join("\n")}\n`, `下一步请手动执行:\n${result.nextSteps.join("\n")}\n`));
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
//#endregion
|
|
373
|
+
//#region src/cli/commands/env/check.ts
|
|
374
|
+
function registerEnvironmentCheck(command, cwd) {
|
|
375
|
+
command.command("check [tasks...]").description(localize("Check static environment references against Turbo cache declarations", "检查静态环境变量引用与 Turbo 缓存声明")).option("--json", localize("Output structured findings", "输出结构化诊断")).option("--markdown", localize("Output Markdown to stdout", "向标准输出写入 Markdown")).option("--strict", localize("Fail on warnings as well as errors", "警告也返回失败码")).option("--no-framework-inference", localize("Disable framework prefix assumptions", "不采用框架变量前缀推断")).option("--dry-run", localize("Read-only check (always enabled)", "只读检查(始终启用)")).action(async (tasks, options, action) => {
|
|
376
|
+
if (options.json && options.markdown) throw new Error("--json and --markdown cannot be combined");
|
|
377
|
+
const { checkEnvironmentCache } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.F);
|
|
378
|
+
const { formatEnvironmentCache } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.N);
|
|
379
|
+
const report = await checkEnvironmentCache(cwd, {
|
|
380
|
+
...tasks.length ? { tasks } : {},
|
|
381
|
+
...action.getOptionValueSource("frameworkInference") === "cli" ? { frameworkInference: options.frameworkInference } : {}
|
|
382
|
+
});
|
|
383
|
+
process.stdout.write(`${options.json ? JSON.stringify(report, null, 2) : formatEnvironmentCache(report, options.markdown)}\n`);
|
|
384
|
+
if (report.status === "fail" || options.strict && report.status === "warn") process.exitCode = 1;
|
|
130
385
|
});
|
|
131
386
|
}
|
|
132
387
|
//#endregion
|
|
@@ -409,7 +664,7 @@ async function emitEnvInfo(info, opts, cwd) {
|
|
|
409
664
|
return;
|
|
410
665
|
}
|
|
411
666
|
const outFile = path.resolve(cwd, opts.out);
|
|
412
|
-
await fs.outputFile(outFile, `${content}\n`, "utf8");
|
|
667
|
+
await fs$1.outputFile(outFile, `${content}\n`, "utf8");
|
|
413
668
|
logger.success(localize(`Wrote ${path.relative(cwd, outFile)}`, `已写入 ${path.relative(cwd, outFile)}`));
|
|
414
669
|
}
|
|
415
670
|
async function emitEnvPaths(paths, opts, cwd) {
|
|
@@ -419,7 +674,7 @@ async function emitEnvPaths(paths, opts, cwd) {
|
|
|
419
674
|
return;
|
|
420
675
|
}
|
|
421
676
|
const outFile = path.resolve(cwd, opts.out);
|
|
422
|
-
await fs.outputFile(outFile, `${content}\n`, "utf8");
|
|
677
|
+
await fs$1.outputFile(outFile, `${content}\n`, "utf8");
|
|
423
678
|
logger.success(localize(`Wrote ${path.relative(cwd, outFile)}`, `已写入 ${path.relative(cwd, outFile)}`));
|
|
424
679
|
}
|
|
425
680
|
async function emitEnvSnapshot(snapshot, opts, cwd) {
|
|
@@ -427,7 +682,7 @@ async function emitEnvSnapshot(snapshot, opts, cwd) {
|
|
|
427
682
|
if (!opts.out) logger.log(content);
|
|
428
683
|
else {
|
|
429
684
|
const outFile = path.resolve(cwd, opts.out);
|
|
430
|
-
await fs.outputFile(outFile, `${content}\n`, "utf8");
|
|
685
|
+
await fs$1.outputFile(outFile, `${content}\n`, "utf8");
|
|
431
686
|
logger.success(localize(`Wrote ${path.relative(cwd, outFile)}`, `已写入 ${path.relative(cwd, outFile)}`));
|
|
432
687
|
}
|
|
433
688
|
if (opts.strict && hasStrictEnvSnapshotIssues(snapshot)) process.exitCode = 1;
|
|
@@ -437,41 +692,148 @@ async function emitEnvSupportBundle(bundle, opts, cwd) {
|
|
|
437
692
|
if (!opts.out) logger.log(content);
|
|
438
693
|
else {
|
|
439
694
|
const outFile = path.resolve(cwd, opts.out);
|
|
440
|
-
await fs.outputFile(outFile, `${content}\n`, "utf8");
|
|
695
|
+
await fs$1.outputFile(outFile, `${content}\n`, "utf8");
|
|
441
696
|
logger.success(localize(`Wrote ${path.relative(cwd, outFile)}`, `已写入 ${path.relative(cwd, outFile)}`));
|
|
442
697
|
}
|
|
443
698
|
if (opts.strict && hasStrictSupportBundleIssues(bundle)) process.exitCode = 1;
|
|
444
699
|
}
|
|
445
700
|
function registerEnvCommands(program, cwd) {
|
|
446
701
|
const envCommand = program.command("env").alias("e").description(localize("Environment and support commands", "环境命令"));
|
|
702
|
+
registerEnvironmentCheck(envCommand, cwd);
|
|
447
703
|
envCommand.command("info").description(localize("Show environment information for the current repository", "输出当前仓库环境信息")).alias("i").option("--json", localize("Output JSON for scripts", "输出 JSON,方便脚本消费")).option("--markdown", localize("Output Markdown", "输出 Markdown,方便粘贴到 issue 或 PR")).option("--out <file>", localize("Write output to a file", "把当前输出写入文件")).option("--redact", localize("Redact workspace, cwd, and home paths", "脱敏 workspace/cwd/home 绝对路径后再输出")).action(async (opts) => {
|
|
448
|
-
const { collectEnvInfo } = await import("./commands-
|
|
704
|
+
const { collectEnvInfo } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
449
705
|
await emitEnvInfo(await collectEnvInfo(cwd), opts, cwd);
|
|
450
706
|
});
|
|
451
707
|
envCommand.command("snapshot").description(localize("Create a support snapshot with environment, doctor, and check data", "输出排障快照,包含环境、doctor 和 check 计划")).alias("s").option("--json", localize("Output JSON for scripts", "输出 JSON,方便脚本消费")).option("--markdown", localize("Output Markdown", "输出 Markdown,方便粘贴到 issue 或 PR")).option("--out <file>", localize("Write output to a file", "把当前输出写入文件")).option("--redact", localize("Redact workspace, cwd, and home paths", "脱敏 workspace/cwd/home 绝对路径后再输出")).option("--strict", localize("Fail when doctor reports a failure or warning", "输出快照后,如果 doctor 有 fail 或 warn 则返回失败码")).action(async (opts) => {
|
|
452
|
-
const { collectEnvSnapshot } = await import("./commands-
|
|
708
|
+
const { collectEnvSnapshot } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
453
709
|
await emitEnvSnapshot(await collectEnvSnapshot(cwd), opts, cwd);
|
|
454
710
|
});
|
|
455
711
|
envCommand.command("paths").description(localize("Show important repository and report paths", "输出当前仓库关键路径和报告建议位置")).alias("p").option("--json", localize("Output JSON for scripts", "输出 JSON,方便脚本消费")).option("--markdown", localize("Output Markdown", "输出 Markdown,方便粘贴到 issue 或 PR")).option("--out <file>", localize("Write output to a file", "把当前输出写入文件")).option("--redact", localize("Redact workspace, cwd, and home paths", "脱敏 workspace/cwd/home 绝对路径后再输出")).action(async (opts) => {
|
|
456
|
-
const { collectEnvPaths } = await import("./commands-
|
|
712
|
+
const { collectEnvPaths } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
457
713
|
await emitEnvPaths(await collectEnvPaths(cwd), opts, cwd);
|
|
458
714
|
});
|
|
459
715
|
envCommand.command("support").description(localize("Create a complete support bundle", "输出完整排障包,包含环境、路径、配置、doctor 和 check 计划")).alias("b").option("--json", localize("Output JSON for scripts", "输出 JSON,方便脚本消费")).option("--markdown", localize("Output Markdown", "输出 Markdown,方便粘贴到 issue 或 PR")).option("--out <file>", localize("Write output to a file", "把当前输出写入文件")).option("--redact", localize("Redact workspace, cwd, and home paths", "脱敏 workspace/cwd/home 绝对路径后再输出")).option("--strict", localize("Fail when doctor reports a failure or warning", "输出排障包后,如果 doctor 有 fail 或 warn 则返回失败码")).action(async (opts) => {
|
|
460
|
-
const { collectEnvSupportBundle } = await import("./commands-
|
|
716
|
+
const { collectEnvSupportBundle } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
461
717
|
await emitEnvSupportBundle(await collectEnvSupportBundle(cwd), opts, cwd);
|
|
462
718
|
});
|
|
463
719
|
envCommand.command("mirror").description(localize("Configure the VS Code binary mirror", "设置 VS Code binary mirror")).alias("m").action(async () => {
|
|
464
|
-
const { setVscodeBinaryMirror } = await import("./commands-
|
|
720
|
+
const { setVscodeBinaryMirror } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
465
721
|
await setVscodeBinaryMirror(cwd);
|
|
466
722
|
logger.success(localize("Environment mirror finished.", "环境镜像完成。"));
|
|
467
723
|
});
|
|
468
724
|
}
|
|
469
725
|
//#endregion
|
|
726
|
+
//#region src/cli/commands/generate.ts
|
|
727
|
+
function registerGenerateCommand(program, cwd) {
|
|
728
|
+
program.command("generate").alias("g").description(localize("Generate a component or route inside an existing package", "在已有包内生成组件或路由")).argument("<generator>", "vue-component, react-component, hono-route").argument("<name>", localize("Kebab-case component or route name", "kebab-case 组件或路由名称")).requiredOption("--package <name-or-path>", localize("Exact workspace package name or relative directory", "精确 workspace 包名或相对目录")).option("--directory <path>", localize("Package-relative source directory", "包内源文件相对目录")).option("--barrel <path>", localize("TypeScript export barrel, used with --export", "配合 --export 使用的 TypeScript 导出文件")).option("--export", localize("Add a named export to src/index.ts or --barrel", "向 src/index.ts 或 --barrel 添加具名导出")).option("--params <json>", localize("Additional typed generator parameters as JSON", "JSON 格式的类型化生成参数")).option("--dry-run", localize("Preview all generated changes without writing", "预览全部生成变更,不写入文件")).option("--json", localize("Print a JSON preview without writing", "以 JSON 输出预览,不写入文件")).action(async (generator, name, options) => {
|
|
729
|
+
try {
|
|
730
|
+
const { applyGeneratePlan, planGenerate } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.v);
|
|
731
|
+
const extra = options.params ? JSON.parse(options.params) : {};
|
|
732
|
+
if (!extra || typeof extra !== "object" || Array.isArray(extra)) throw new Error("--params must contain a JSON object.");
|
|
733
|
+
if (Object.hasOwn(extra, "name") || options.export !== void 0 && Object.hasOwn(extra, "export")) throw new Error("Do not supply the same generator parameter through multiple inputs.");
|
|
734
|
+
const plan = await planGenerate({
|
|
735
|
+
cwd,
|
|
736
|
+
package: options.package,
|
|
737
|
+
generator,
|
|
738
|
+
parameters: {
|
|
739
|
+
...extra,
|
|
740
|
+
name,
|
|
741
|
+
...options.export === void 0 ? {} : { export: options.export }
|
|
742
|
+
},
|
|
743
|
+
...options.directory === void 0 ? {} : { directory: options.directory },
|
|
744
|
+
...options.barrel === void 0 ? {} : { barrel: options.barrel }
|
|
745
|
+
});
|
|
746
|
+
if (options.json || options.dryRun) {
|
|
747
|
+
process.stdout.write(`${options.json ? JSON.stringify(plan, null, 2) : plan.files.map((file) => `${file.action}: ${file.path}`).concat(plan.nextSteps).join("\n")}\n`);
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
const result = await applyGeneratePlan(plan);
|
|
751
|
+
process.stdout.write(`${result.changed.map((file) => `generated: ${file}`).concat(result.nextSteps).join("\n")}\n`);
|
|
752
|
+
if (result.recoveryFiles.length) {
|
|
753
|
+
process.stderr.write(`Recovery files retained: ${result.recoveryFiles.join(", ")}\n`);
|
|
754
|
+
process.exitCode = 1;
|
|
755
|
+
}
|
|
756
|
+
} catch (error) {
|
|
757
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
758
|
+
process.stderr.write(`${options.json ? JSON.stringify({ error: message }) : message}\n`);
|
|
759
|
+
process.exitCode = 1;
|
|
760
|
+
}
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
//#endregion
|
|
764
|
+
//#region src/cli/commands/maintenance.ts
|
|
765
|
+
function registerMaintenanceCommands(program, cwd) {
|
|
766
|
+
const maintenance = program.command("maintenance").description(localize("Prepare reviewed managed asset upgrades", "准备可审核的受管资产升级"));
|
|
767
|
+
maintenance.command("upgrade").description(localize("Generate a validated patch in a disposable clean checkout", "在一次性干净 checkout 中生成经过校验的补丁")).requiredOption("--base <sha>", localize("Full trusted source commit before the dependency update", "依赖升级前的完整可信提交 SHA")).option("--head <sha>", localize("Exact current source commit (default: HEAD)", "当前精确源码提交(默认 HEAD)")).requiredOption("--out <directory>", localize("Empty artifact directory outside the repository", "仓库外的空产物目录")).action(async (options) => {
|
|
768
|
+
const report = await prepareMaintenanceUpgrade({
|
|
769
|
+
cwd,
|
|
770
|
+
base: options.base,
|
|
771
|
+
...options.head ? { head: options.head } : {},
|
|
772
|
+
outputDirectory: path$1.resolve(cwd, options.out)
|
|
773
|
+
});
|
|
774
|
+
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
775
|
+
if (report.status === "blocked") process.exitCode = 1;
|
|
776
|
+
});
|
|
777
|
+
maintenance.command("workflow").description(localize("Export the opt-in two-job GitHub Actions recipe", "导出按需启用的双 job GitHub Actions 工作流")).requiredOption("--out <file>", localize("New workflow filename; existing files are protected", "新工作流路径;保护已有文件")).action(async (options) => {
|
|
778
|
+
const filename = path$1.resolve(cwd, options.out);
|
|
779
|
+
await mkdir(path$1.dirname(filename), { recursive: true });
|
|
780
|
+
await writeFile(filename, await getMaintenanceWorkflow(cwd), { flag: "wx" });
|
|
781
|
+
process.stdout.write(`${filename}\n`);
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
//#endregion
|
|
785
|
+
//#region src/cli/commands/package/api-report.ts
|
|
786
|
+
function registerPublicApiCommands(command, cwd) {
|
|
787
|
+
const api = command.command("api").description(localize("Review built public API signatures", "审核构建后的公共 API 签名"));
|
|
788
|
+
api.command("check").description(localize("Read-only comparison with declared API baselines", "只读比较显式声明的 API 基线")).option("--package <selector...>", localize("Exact workspace names or ./paths", "精确工作区名称或 ./路径")).option("--json", localize("Output a stable JSON report", "输出稳定 JSON 报告")).action(async (opts) => {
|
|
789
|
+
const report = await checkPublicApi(cwd, opts.package ? { packages: opts.package } : {});
|
|
790
|
+
process.stdout.write(`${opts.json ? JSON.stringify(report, null, 2) : formatPublicApiReport(report)}\n`);
|
|
791
|
+
if (["changes", "failed"].includes(report.status)) process.exitCode = 1;
|
|
792
|
+
});
|
|
793
|
+
api.command("update").description(localize("Preview baseline updates or apply a reviewed JSON plan", "预览基线更新,或应用审核后的 JSON 计划")).option("--package <selector...>", localize("Exact workspace names or ./paths", "精确工作区名称或 ./路径")).option("--json", localize("Output the reviewed plan as JSON", "以 JSON 输出待审核计划")).option("--apply <plan>", localize("Apply an explicitly reviewed JSON plan file", "应用显式审核过的 JSON 计划文件")).action(async (opts) => {
|
|
794
|
+
if (opts.apply) {
|
|
795
|
+
if (opts.package) throw new Error("--apply uses the package selection in the reviewed plan.");
|
|
796
|
+
const result = await applyPublicApiUpdate(cwd, JSON.parse(await readFile(opts.apply, "utf8")));
|
|
797
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
const plan = await planPublicApiUpdate(cwd, opts.package ? { packages: opts.package } : {});
|
|
801
|
+
process.stdout.write(`${opts.json ? JSON.stringify(plan, null, 2) : formatPublicApiReport(plan.report)}\n`);
|
|
802
|
+
if (plan.report.status === "failed") process.exitCode = 1;
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
//#endregion
|
|
806
|
+
//#region src/cli/commands/package/check.ts
|
|
807
|
+
function registerPackageCheckCommand(command, cwd) {
|
|
808
|
+
command.command("check").description(localize("Build, pack, and test packages as consumers receive them", "构建并校验消费者实际收到的发布 tarball")).option("--filter <selector>", localize("Select packages using pnpm filters (repeatable)", "用 pnpm filter 选择包,可重复传入"), (value, values = []) => [...values, value]).option("--include-private", localize("Also check private packages", "同时校验 private 包")).option("--build-script <script>", localize("Workspace build script (default: build)", "workspace 构建脚本,默认为 build")).option("--strict", localize("Treat warnings as failures", "将 warning 视为失败")).option("--keep-temp", localize("Preserve tarballs and consumers for reproduction", "保留 tarball 和临时消费者,便于复现")).option("--json", localize("Output the complete machine-readable report", "输出完整 JSON 报告")).action(async (options) => {
|
|
809
|
+
const report = await checkPackages({
|
|
810
|
+
cwd,
|
|
811
|
+
...options.filter ? { filters: options.filter } : {},
|
|
812
|
+
...options
|
|
813
|
+
});
|
|
814
|
+
if (options.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
815
|
+
else {
|
|
816
|
+
for (const pkg of report.packages) {
|
|
817
|
+
process.stdout.write(`${pkg.status} ${pkg.name}${pkg.reason ? ` (${pkg.reason})` : ""}\n`);
|
|
818
|
+
for (const diagnostic of pkg.diagnostics.filter((item) => item.severity !== "info")) process.stdout.write(` ${diagnostic.source}:${diagnostic.code} ${diagnostic.file ?? diagnostic.entry ?? ""} ${diagnostic.message}\n`);
|
|
819
|
+
}
|
|
820
|
+
if (report.retained) process.stdout.write(`${report.temporaryDirectory}\n`);
|
|
821
|
+
}
|
|
822
|
+
if (report.status === "failed") process.exitCode = 1;
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
//#endregion
|
|
470
826
|
//#region src/cli/commands/package.ts
|
|
471
827
|
function registerPackageCommands(program, cwd) {
|
|
472
|
-
program.command("package").alias("pkg").description(localize("Package commands", "子包命令"))
|
|
473
|
-
|
|
828
|
+
const packageCommand = program.command("package").alias("pkg").description(localize("Package commands", "子包命令"));
|
|
829
|
+
registerPackageCheckCommand(packageCommand, cwd);
|
|
830
|
+
registerPublicApiCommands(packageCommand, cwd);
|
|
831
|
+
packageCommand.command("create").description(localize("Create a new workspace package", "创建一个新的子包")).alias("new").argument("[name]").option("--offline", localize("Use only verified cached remote assets", "只使用通过校验的远程资产缓存")).option("--data <file>", localize("Read typed template parameters from a JSON file", "从 JSON 文件读取类型化模板参数")).option("--cache-dir <directory>", localize("Template asset cache directory", "模板资产缓存目录")).option("-t, --template <template>", localize("Use a template key without prompting", "直接使用指定模板,跳过模板选择")).option("--dry-run", localize("Preview without writing files", "预览将要创建的目录与 package 信息,不写入文件")).option("--json", localize("Output JSON; implies --dry-run", "以 JSON 输出创建预览,隐含 --dry-run")).option("--out <file>", localize("Write the preview to a file; implies --dry-run", "把创建预览写入文件,隐含 --dry-run")).action(async (inputName, opts) => {
|
|
832
|
+
const { runCreateFlow } = await import("./create-flow-BWFWDWR4.mjs");
|
|
474
833
|
const result = await runCreateFlow(cwd, inputName, {
|
|
834
|
+
...opts.offline !== void 0 ? { offline: opts.offline } : {},
|
|
835
|
+
...opts.cacheDir ? { cacheDir: opts.cacheDir } : {},
|
|
836
|
+
...opts.data ? { data: opts.data } : {},
|
|
475
837
|
...opts.template !== void 0 ? { template: opts.template } : {},
|
|
476
838
|
...opts.dryRun || opts.json || opts.out ? { dryRun: true } : {},
|
|
477
839
|
...opts.json ? { json: true } : {},
|
|
@@ -482,6 +844,122 @@ function registerPackageCommands(program, cwd) {
|
|
|
482
844
|
});
|
|
483
845
|
}
|
|
484
846
|
//#endregion
|
|
847
|
+
//#region src/cli/commands/presets.ts
|
|
848
|
+
function registerPresetCommands(program, cwd) {
|
|
849
|
+
const presets = program.command("presets").description(localize("Inspect installed organization presets and review engineering asset updates", "检查已安装的组织预设并审阅工程文件更新"));
|
|
850
|
+
presets.command("inspect").description(localize("Show installed package identities and recommendations without running package code", "只读查看预设包身份及推荐能力,不运行包代码")).option("--json", localize("Output JSON", "输出 JSON")).action(async (options) => {
|
|
851
|
+
const loaded = await loadMonorepoConfigDetails(await findWorkspaceDir(cwd) ?? cwd, { refresh: true });
|
|
852
|
+
const report = {
|
|
853
|
+
schemaVersion: 1,
|
|
854
|
+
workspaceDir: loaded.presets.workspaceDir,
|
|
855
|
+
diagnostics: loaded.presets.diagnostics,
|
|
856
|
+
presets: loaded.presets.layers.map((layer) => ({
|
|
857
|
+
...layer.source,
|
|
858
|
+
requires: layer.manifest.requires,
|
|
859
|
+
templates: Object.keys(layer.manifest.templates ?? {}),
|
|
860
|
+
capabilities: layer.manifest.capabilities ?? [],
|
|
861
|
+
assets: layer.manifest.assets ?? []
|
|
862
|
+
}))
|
|
863
|
+
};
|
|
864
|
+
process.stdout.write(`${options.json ? JSON.stringify(report, null, 2) : report.presets.map((item) => `${item.id}: ${item.templates.length} templates, ${item.assets.length} assets; recommendations: ${item.capabilities.map((capability) => capability.id).join(", ") || "-"}`).join("\n") || "No organization presets configured."}\n`);
|
|
865
|
+
});
|
|
866
|
+
presets.command("plan").description(localize("Plan managed engineering assets without writing project files", "只读规划预设工程文件")).option("--json", localize("Output the complete JSON plan", "输出完整 JSON 计划")).option("--out <file>", localize("Save the JSON plan to a new file", "将 JSON 计划保存到新文件")).action(async (options) => {
|
|
867
|
+
const plan = await planOrganizationPresetAssets(cwd);
|
|
868
|
+
if (options.out) await writeFile(path.resolve(cwd, options.out), `${JSON.stringify(plan, null, 2)}\n`, { flag: "wx" });
|
|
869
|
+
process.stdout.write(`${options.json ? JSON.stringify(plan, null, 2) : [
|
|
870
|
+
plan.status,
|
|
871
|
+
...plan.files.map((file) => `${file.status}: ${file.path} (${file.source.packageName}@${file.source.version})`),
|
|
872
|
+
...plan.conflicts.map((item) => `${item.path}: ${item.reason}`)
|
|
873
|
+
].join("\n")}\n`);
|
|
874
|
+
if (plan.status === "blocked") process.exitCode = 1;
|
|
875
|
+
});
|
|
876
|
+
presets.command("apply <file>").description(localize("Apply an unchanged reviewed JSON asset plan", "应用经审阅且输入未变化的 JSON 工程文件计划")).option("--json", localize("Output JSON", "输出 JSON")).action(async (file, options) => {
|
|
877
|
+
const plan = JSON.parse(await readFile(path.resolve(cwd, file), "utf8"));
|
|
878
|
+
if (plan.rootDir !== await canonicalDirectory(await findWorkspaceDir(cwd) ?? cwd)) throw new Error("Preset plan must belong to the current workspace");
|
|
879
|
+
const result = await applyOrganizationPresetAssets(plan);
|
|
880
|
+
process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : `${result.status}: ${result.changed.length} files`}\n`);
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
//#endregion
|
|
884
|
+
//#region src/cli/commands/release/plan.ts
|
|
885
|
+
function formatReleasePlan(plan) {
|
|
886
|
+
const cell = (value) => String(value).replaceAll("|", "\\|").replaceAll("\n", "<br>");
|
|
887
|
+
return [
|
|
888
|
+
"# Release plan",
|
|
889
|
+
"",
|
|
890
|
+
`Status: ${plan.status}; pnpm: ${plan.pnpmVersion ?? "unknown"}`,
|
|
891
|
+
...plan.branchRule ? [`Branch: ${cell(plan.branchRule.branch)}; kind: ${plan.branchRule.kind}; lane: ${cell(plan.branchRule.lane)}; range: ${cell(plan.branchRule.range)}; tag: ${cell(plan.branchRule.distTag)}`, ...plan.branchRule.excludedRanges.length ? [`Excluded maintenance ranges: ${plan.branchRule.excludedRanges.map(cell).join(", ")}`] : []] : [],
|
|
892
|
+
"",
|
|
893
|
+
"| Package | Current | Planned | Lane | Publish | Reasons |",
|
|
894
|
+
"| --- | --- | --- | --- | --- | --- |",
|
|
895
|
+
...plan.packages.map((pkg) => `| ${[
|
|
896
|
+
pkg.name,
|
|
897
|
+
pkg.currentVersion,
|
|
898
|
+
pkg.newVersion,
|
|
899
|
+
pkg.lane,
|
|
900
|
+
pkg.publishCandidate,
|
|
901
|
+
pkg.reasons.join(", ")
|
|
902
|
+
].map(cell).join(" | ")} |`),
|
|
903
|
+
...plan.blockers.flatMap((blocker) => ["", `- ${blocker.id}: ${blocker.detail}`]),
|
|
904
|
+
"",
|
|
905
|
+
renderReleasePullRequest(plan.notes, { locale: repoctlLocale })
|
|
906
|
+
].join("\n");
|
|
907
|
+
}
|
|
908
|
+
function registerReleasePlan(release, cwd) {
|
|
909
|
+
release.command("plan").description(localize("Preview native pnpm versioning without consuming intents or running release hooks", "只读预览 pnpm 版本计划,不消费 intents 或执行发布 hooks")).option("--json", localize("Output a versioned JSON plan", "输出有版本结构的 JSON 计划")).option("--markdown", localize("Output Markdown with release-note previews", "输出包含发布说明预览的 Markdown")).option("--branch <branch>", localize("Select the release line; defaults to the primary stable line", "选择发布线,默认正式主线")).action(async (options) => {
|
|
910
|
+
const plan = await createReleasePlan({
|
|
911
|
+
cwd,
|
|
912
|
+
...options.branch ? { branch: options.branch } : {}
|
|
913
|
+
});
|
|
914
|
+
process.stdout.write(`${options.json ? JSON.stringify(plan, null, 2) : formatReleasePlan(plan)}\n`);
|
|
915
|
+
if (plan.status === "blocked") process.exitCode = 1;
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
//#endregion
|
|
919
|
+
//#region src/cli/commands/release/snapshot.ts
|
|
920
|
+
function formatSnapshotReport(report) {
|
|
921
|
+
return [
|
|
922
|
+
`Snapshot: ${report.status}`,
|
|
923
|
+
`Source: ${report.identity.commit}; build: ${report.identity.buildId}`,
|
|
924
|
+
`Tag: ${report.tag}; registry: ${report.registry}`,
|
|
925
|
+
...report.packages.map((pkg) => `- ${pkg.name}@${pkg.version} (${pkg.reasons.join(", ")})`),
|
|
926
|
+
"",
|
|
927
|
+
report.installCommand,
|
|
928
|
+
...report.outputDirectory ? [`Artifacts: ${report.outputDirectory}`] : [],
|
|
929
|
+
...report.error ? [`Error: ${report.error}`] : []
|
|
930
|
+
].join("\n");
|
|
931
|
+
}
|
|
932
|
+
function registerSnapshot(release, cwd) {
|
|
933
|
+
release.command("snapshot").description(localize("Prepare isolated PR/nightly packages, optionally publish from authorized CI", "隔离准备 PR/nightly 临时包,可在授权 CI 中发布")).requiredOption("--kind <kind>", "pr / nightly").option("--pr <number>", localize("Pull request number for pr snapshots", "PR 快照的 pull request 编号")).requiredOption("--commit <sha>", localize("Full commit matching HEAD", "与 HEAD 一致的完整提交 SHA")).requiredOption("--build-id <identity>", localize("Unique CI build identity; repeat it only to recover the same build", "唯一 CI 构建身份;仅在恢复同一构建时复用")).option("--output <directory>", localize("Artifact parent outside the source repository", "源码仓库以外的产物父目录")).option("--registry <url>", localize("Publication registry, defaults to public npm", "发布 registry,默认公共 npm")).option("--publish", localize("Publish after build and package validation in trusted CI", "在可信 CI 中通过构建与包校验后发布")).option("--dry-run", localize("Only preview identity, candidates, versions and tag", "只预览身份、候选、版本和 tag")).option("--json", localize("Output a versioned JSON report", "输出有版本结构的 JSON 报告")).action(async (options) => {
|
|
934
|
+
try {
|
|
935
|
+
if (!["pr", "nightly"].includes(options.kind) || options.kind === "nightly" && options.pr !== void 0) throw new Error("Use --kind pr --pr <number> or --kind nightly.");
|
|
936
|
+
const identity = options.kind === "pr" ? {
|
|
937
|
+
kind: "pr",
|
|
938
|
+
pullRequest: Number(options.pr),
|
|
939
|
+
commit: options.commit,
|
|
940
|
+
buildId: options.buildId
|
|
941
|
+
} : {
|
|
942
|
+
kind: "nightly",
|
|
943
|
+
commit: options.commit,
|
|
944
|
+
buildId: options.buildId
|
|
945
|
+
};
|
|
946
|
+
const report = await releaseSnapshot({
|
|
947
|
+
cwd,
|
|
948
|
+
identity,
|
|
949
|
+
...options.output ? { outputDirectory: options.output } : {},
|
|
950
|
+
...options.registry ? { registry: options.registry } : {},
|
|
951
|
+
...options.publish ? { publish: true } : {},
|
|
952
|
+
...options.dryRun ? { dryRun: true } : {}
|
|
953
|
+
});
|
|
954
|
+
process.stdout.write(`${options.json ? JSON.stringify(report, null, 2) : formatSnapshotReport(report)}\n`);
|
|
955
|
+
if (report.status === "failed") process.exitCode = 1;
|
|
956
|
+
} catch (error) {
|
|
957
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
958
|
+
process.exitCode = 1;
|
|
959
|
+
}
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
//#endregion
|
|
485
963
|
//#region src/cli/commands/release.ts
|
|
486
964
|
async function runReleaseAction(action) {
|
|
487
965
|
try {
|
|
@@ -492,7 +970,7 @@ async function runReleaseAction(action) {
|
|
|
492
970
|
}
|
|
493
971
|
}
|
|
494
972
|
async function resolveReleaseOptions(cwd) {
|
|
495
|
-
const config = await resolveCommandConfig("release", cwd);
|
|
973
|
+
const config = resolveCommandValues("release", await resolveCommandConfig("release", cwd)).values;
|
|
496
974
|
return {
|
|
497
975
|
cwd,
|
|
498
976
|
...config ? { config } : {}
|
|
@@ -500,9 +978,11 @@ async function resolveReleaseOptions(cwd) {
|
|
|
500
978
|
}
|
|
501
979
|
function registerReleaseCommands(program, cwd) {
|
|
502
980
|
const releaseCommand = program.command("release").description(localize("Release and pnpm versioning commands", "发布与 pnpm versioning 工具集"));
|
|
503
|
-
releaseCommand
|
|
981
|
+
registerReleasePlan(releaseCommand, cwd);
|
|
982
|
+
registerSnapshot(releaseCommand, cwd);
|
|
983
|
+
releaseCommand.command("ci").description(localize("Prepare, publish, or recover versions in CI", "在 CI 中自动准备、发布和恢复版本")).option("--mode <mode>", localize("auto / prepare / publish / publish-unpublished / reconcile", "auto / prepare / publish / publish-unpublished / reconcile"), "auto").option("--package <name>", localize("Package used by publish-unpublished mode", "publish-unpublished 使用的 package")).option("--version <version>", localize("Version used by publish-unpublished mode", "publish-unpublished 使用的版本")).option("--source-sha <sha>", localize("Recover a prepared release from the selected line history", "从所选发布线的历史提交恢复整批发布")).option("--dry-run", localize("Preview reconcile changes without updating GitHub", "只预览 reconcile 变更,不更新 GitHub")).action(async (opts) => {
|
|
504
984
|
await runReleaseAction(async () => {
|
|
505
|
-
const { releaseCi } = await import("./commands-
|
|
985
|
+
const { releaseCi } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
506
986
|
await releaseCi({
|
|
507
987
|
...await resolveReleaseOptions(cwd),
|
|
508
988
|
...opts.mode ? { mode: opts.mode } : {},
|
|
@@ -516,7 +996,7 @@ function registerReleaseCommands(program, cwd) {
|
|
|
516
996
|
});
|
|
517
997
|
releaseCommand.command("notes").description(localize("Manage GitHub Release notes", "维护 GitHub Release 正文")).command("repair").description(localize("Rebuild GitHub Release notes from the changelog for each release tag", "按每个发布 tag 对应的 changelog 重建 GitHub Release 正文")).option("--all", localize("Repair every recognized GitHub Release", "修复所有可识别的 GitHub Release")).option("--tag <package@version>", localize("Repair only the specified package@version", "只修复指定 package@version")).option("--dry-run", localize("Generate and summarize without updating GitHub Releases", "只生成并统计,不更新 GitHub Release")).option("--create-missing", localize("Create a missing GitHub Release after validating the published package and tag", "核验已发布 package 和 tag 后补建缺失的 GitHub Release")).action(async (opts) => {
|
|
518
998
|
await runReleaseAction(async () => {
|
|
519
|
-
const { repairReleaseNotes } = await import("./commands-
|
|
999
|
+
const { repairReleaseNotes } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
520
1000
|
const result = await repairReleaseNotes({
|
|
521
1001
|
cwd,
|
|
522
1002
|
...opts.all ? { all: true } : {},
|
|
@@ -527,9 +1007,9 @@ function registerReleaseCommands(program, cwd) {
|
|
|
527
1007
|
logger.success(localize(`Release notes repaired: ${result.repaired.length}; skipped: ${result.skipped.length}`, `Release 正文已修复:${result.repaired.length};已跳过:${result.skipped.length}`));
|
|
528
1008
|
});
|
|
529
1009
|
});
|
|
530
|
-
const stableCommand = releaseCommand.command("stable").description(localize("Run a stable release from
|
|
1010
|
+
const stableCommand = releaseCommand.command("stable").description(localize("Run a stable release from the configured release line", "在配置的正式发布线执行发布")).action(async () => {
|
|
531
1011
|
await runReleaseAction(async () => {
|
|
532
|
-
const { releaseCi } = await import("./commands-
|
|
1012
|
+
const { releaseCi } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
533
1013
|
await releaseCi({
|
|
534
1014
|
...await resolveReleaseOptions(cwd),
|
|
535
1015
|
mode: "publish"
|
|
@@ -539,7 +1019,7 @@ function registerReleaseCommands(program, cwd) {
|
|
|
539
1019
|
});
|
|
540
1020
|
stableCommand.command("prepare").description(localize("Consume pnpm change intents and prepare a Release PR", "消费 pnpm change intents 并准备 Release PR")).action(async () => {
|
|
541
1021
|
await runReleaseAction(async () => {
|
|
542
|
-
const { releaseCi } = await import("./commands-
|
|
1022
|
+
const { releaseCi } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
543
1023
|
await releaseCi({
|
|
544
1024
|
...await resolveReleaseOptions(cwd),
|
|
545
1025
|
mode: "prepare"
|
|
@@ -547,9 +1027,9 @@ function registerReleaseCommands(program, cwd) {
|
|
|
547
1027
|
logger.success(localize("Stable release preparation finished.", "稳定版发布准备完成。"));
|
|
548
1028
|
});
|
|
549
1029
|
});
|
|
550
|
-
stableCommand.command("publish").description(localize("Publish versions
|
|
1030
|
+
stableCommand.command("publish").description(localize("Publish prepared versions from the configured release line", "发布所选发布线已经准备的包版本")).action(async () => {
|
|
551
1031
|
await runReleaseAction(async () => {
|
|
552
|
-
const { releaseCi } = await import("./commands-
|
|
1032
|
+
const { releaseCi } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
553
1033
|
await releaseCi({
|
|
554
1034
|
...await resolveReleaseOptions(cwd),
|
|
555
1035
|
mode: "publish"
|
|
@@ -558,25 +1038,25 @@ function registerReleaseCommands(program, cwd) {
|
|
|
558
1038
|
});
|
|
559
1039
|
});
|
|
560
1040
|
const preCommand = releaseCommand.command("pre").description(localize("Run or manage prereleases", "执行或管理 prerelease 发布"));
|
|
561
|
-
preCommand.command("publish").alias("run").description(localize("Publish
|
|
1041
|
+
preCommand.command("publish").alias("run").description(localize("Publish from a configured prerelease branch", "在已配置的预发布分支发布 prerelease")).action(async () => {
|
|
562
1042
|
await runReleaseAction(async () => {
|
|
563
|
-
const { releaseCi } = await import("./commands-
|
|
1043
|
+
const { releaseCi } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
564
1044
|
await releaseCi(await resolveReleaseOptions(cwd));
|
|
565
1045
|
logger.success(localize("Prerelease finished.", "预发布完成。"));
|
|
566
1046
|
});
|
|
567
1047
|
});
|
|
568
|
-
preCommand.command("enter").description(localize("Enter a pnpm prerelease lane", "进入 pnpm prerelease lane")).argument("<tag>", localize("
|
|
1048
|
+
preCommand.command("enter").description(localize("Enter a pnpm prerelease lane", "进入 pnpm prerelease lane")).argument("<tag>", localize("Configured pnpm prerelease lane", "已配置的 pnpm 预发布 lane")).action(async (tag) => {
|
|
569
1049
|
await runReleaseAction(async () => {
|
|
570
|
-
const { enterPrerelease } = await import("./commands-
|
|
1050
|
+
const { enterPrerelease } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
571
1051
|
await enterPrerelease(tag, { cwd });
|
|
572
1052
|
logger.success(localize(`Entered ${tag} prerelease mode.`, `已进入 ${tag} 预发布模式。`));
|
|
573
1053
|
});
|
|
574
1054
|
});
|
|
575
1055
|
preCommand.command("exit").description(localize("Exit the pnpm prerelease lane", "退出 pnpm prerelease lane")).action(async () => {
|
|
576
1056
|
await runReleaseAction(async () => {
|
|
577
|
-
const { exitPrerelease } = await import("./commands-
|
|
578
|
-
await exitPrerelease({ cwd });
|
|
579
|
-
logger.success(localize(
|
|
1057
|
+
const { exitPrerelease } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1058
|
+
const target = await exitPrerelease({ cwd });
|
|
1059
|
+
logger.success(localize(`Exited prerelease mode. Stable target: ${target.branch}.`, `已退出预发布模式,正式目标分支:${target.branch}。`));
|
|
580
1060
|
});
|
|
581
1061
|
});
|
|
582
1062
|
}
|
|
@@ -591,7 +1071,7 @@ const skillTargets = [
|
|
|
591
1071
|
];
|
|
592
1072
|
function registerSkillsCommands(program, cwd) {
|
|
593
1073
|
program.command("skills").alias("sk").description(localize("AI skill commands", "技能工具集")).command("sync").description(localize("Synchronize the repoctl skill to global agent directories", "同步 resources/skills/repoctl 到全局目录")).alias("s").option("--codex", localize("Synchronize to ~/.codex/skills", "同步到 ~/.codex/skills")).option("--claude", localize("Synchronize to ~/.claude/skills", "同步到 ~/.claude/skills")).option("--cursor", localize("Synchronize to ~/.cursor/skills", "同步到 ~/.cursor/skills")).option("--agents", localize("Synchronize to ~/.agents/skills", "同步到 ~/.agents/skills")).option("--grok", localize("Synchronize to ~/.grok/skills", "同步到 ~/.grok/skills")).option("--all", localize("Synchronize every target", "同步全部目标")).action(async (opts) => {
|
|
594
|
-
const { syncSkills } = await import("./commands-
|
|
1074
|
+
const { syncSkills } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
595
1075
|
const selected = /* @__PURE__ */ new Set();
|
|
596
1076
|
if (opts.all) for (const target of skillTargets) selected.add(target);
|
|
597
1077
|
else {
|
|
@@ -614,37 +1094,179 @@ function registerSkillsCommands(program, cwd) {
|
|
|
614
1094
|
});
|
|
615
1095
|
}
|
|
616
1096
|
//#endregion
|
|
617
|
-
//#region src/cli/commands/
|
|
1097
|
+
//#region src/cli/commands/template-instances/output.ts
|
|
1098
|
+
async function templateWorkspaceRoot() {
|
|
1099
|
+
return await findWorkspaceDir(process.cwd()) ?? process.cwd();
|
|
1100
|
+
}
|
|
1101
|
+
async function emitTemplateReport(value, options) {
|
|
1102
|
+
const content = JSON.stringify(value, null, 2);
|
|
1103
|
+
if (options.out) await fs$1.outputFile(path.resolve(options.out), `${content}\n`);
|
|
1104
|
+
else process.stdout.write(`${content}\n`);
|
|
1105
|
+
}
|
|
1106
|
+
//#endregion
|
|
1107
|
+
//#region src/cli/commands/template-instances/drift.ts
|
|
1108
|
+
function registerTemplateDriftCommand(templates) {
|
|
1109
|
+
templates.command("drift").description(localize("Inspect template versions and managed file drift without changing assets", "只读诊断模板版本、基线和受管文件漂移")).option("--source-dir <directory>", localize("Compare with metadata from an extracted template package", "与已解压模板包的真实版本元数据比较")).option("--remote", localize("Explicitly query the public npm latest dist-tag", "显式查询公共 npm 仓库的 latest 版本")).option("--strict", localize("Fail on active warnings, including unavailable evidence", "存在有效告警或证据不可用时失败")).option("--json", localize("Output structured JSON", "输出结构化 JSON")).option("--markdown", localize("Output a Markdown report (default)", "输出 Markdown 报告(默认)")).option("--out <file>", localize("Write only the report to this file", "仅将诊断报告写入指定文件")).action(async (options, command) => {
|
|
1110
|
+
const { checkTemplateDrift, formatTemplateDriftReport, hasTemplateDriftIssues } = await import("./template-drift-D0hKxixr.mjs").then((n) => n.n);
|
|
1111
|
+
const merged = {
|
|
1112
|
+
...command.optsWithGlobals(),
|
|
1113
|
+
...options
|
|
1114
|
+
};
|
|
1115
|
+
const report = await checkTemplateDrift(await templateWorkspaceRoot(), {
|
|
1116
|
+
...merged.sourceDir ? { sourceDir: merged.sourceDir } : {},
|
|
1117
|
+
...merged.remote !== void 0 ? { remote: merged.remote } : {}
|
|
1118
|
+
});
|
|
1119
|
+
const content = merged.json ? JSON.stringify(report, null, 2) : formatTemplateDriftReport(report);
|
|
1120
|
+
if (merged.out) await fs$1.outputFile(path.resolve(merged.out), `${content}\n`);
|
|
1121
|
+
else process.stdout.write(`${content}\n`);
|
|
1122
|
+
if (hasTemplateDriftIssues(report, merged.strict)) process.exitCode = 1;
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
//#endregion
|
|
1126
|
+
//#region src/cli/commands/template-instances/upgrade.ts
|
|
1127
|
+
function registerTemplateUpgradeCommands(templates) {
|
|
1128
|
+
templates.command("upgrade").description(localize("Preview a selected template instance upgrade, preserving business changes", "预览所选模板实例的增量升级,保留业务修改")).argument("<instance>", localize("Registered instance ID or target path", "已登记实例 ID 或目标路径")).requiredOption("--source-version <version>", localize("Exact target template package version", "目标模板包的精确版本")).option("--source-dir <directory>", localize("Read an extracted target template package", "只读使用已解压的目标模板包")).option("--exclude <paths...>", localize("Keep these relative files or directories unmanaged in future upgrades", "将这些相对文件或目录持久标记为不受管")).option("--apply", localize("Apply a conflict-free instance upgrade", "应用无冲突的实例升级")).option("--json", localize("Output structured JSON", "输出结构化 JSON")).option("--out <file>", localize("Write the report to a file", "将报告写入文件")).action(async (instance, options, command) => {
|
|
1129
|
+
const { planTemplateUpgrade, applyTemplateUpgradePlan } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.d);
|
|
1130
|
+
const plan = await planTemplateUpgrade({
|
|
1131
|
+
cwd: await templateWorkspaceRoot(),
|
|
1132
|
+
instance,
|
|
1133
|
+
version: options.sourceVersion,
|
|
1134
|
+
...options.sourceDir ? { sourceDir: options.sourceDir } : {},
|
|
1135
|
+
...options.exclude ? { exclude: options.exclude } : {}
|
|
1136
|
+
});
|
|
1137
|
+
await emitTemplateReport(options.apply ? await applyTemplateUpgradePlan(plan) : plan, {
|
|
1138
|
+
...command.optsWithGlobals(),
|
|
1139
|
+
...options
|
|
1140
|
+
});
|
|
1141
|
+
});
|
|
1142
|
+
templates.command("recover-upgrade").description(localize("Inspect or restore an interrupted instance upgrade", "检查或恢复中断的实例升级")).argument("<instance>", localize("Registered instance ID or target path", "已登记实例 ID 或目标路径")).option("--apply", localize("Restore the recorded instance and changed files", "恢复记录中的实例信息及受影响文件")).option("--json", localize("Output structured JSON", "输出结构化 JSON")).option("--out <file>", localize("Write the report to a file", "将报告写入文件")).action(async (instance, options, command) => {
|
|
1143
|
+
const { recoverTemplateUpgrade } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.d);
|
|
1144
|
+
await emitTemplateReport(await recoverTemplateUpgrade(await templateWorkspaceRoot(), instance, options.apply), {
|
|
1145
|
+
...command.optsWithGlobals(),
|
|
1146
|
+
...options
|
|
1147
|
+
});
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
//#endregion
|
|
1151
|
+
//#region src/cli/commands/template-instances/index.ts
|
|
1152
|
+
function registerTemplateInstanceCommands(templates) {
|
|
1153
|
+
registerTemplateDriftCommand(templates);
|
|
1154
|
+
registerTemplateUpgradeCommands(templates);
|
|
1155
|
+
templates.command("instances").description(localize("Inspect registered template instances without changing files", "只读查询已登记模板实例")).argument("[target]", localize("Instance ID or workspace-relative target", "实例 ID 或相对工作区路径")).option("--json", localize("Output structured JSON", "输出结构化 JSON")).option("--out <file>", localize("Write the report to a file", "将报告写入文件")).action(async (target, options, command) => {
|
|
1156
|
+
const { listTemplateInstances } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.d);
|
|
1157
|
+
const instances = await listTemplateInstances(await templateWorkspaceRoot());
|
|
1158
|
+
const selected = target ? instances.filter((item) => item.instance.id === target || item.instance.target === target) : instances;
|
|
1159
|
+
if (target && !selected.length) throw new Error(`Unknown template instance: ${target}`);
|
|
1160
|
+
await emitTemplateReport({
|
|
1161
|
+
schemaVersion: 1,
|
|
1162
|
+
instances: selected
|
|
1163
|
+
}, {
|
|
1164
|
+
...command.optsWithGlobals(),
|
|
1165
|
+
...options
|
|
1166
|
+
});
|
|
1167
|
+
});
|
|
1168
|
+
templates.command("link").description(localize("Preview an explicit historical template association; --apply writes metadata only", "预览历史模板关联;--apply 仅写登记信息")).argument("<target>", localize("Existing workspace-relative project path", "存量项目相对工作区路径")).requiredOption("--template <key>", localize("Stable template key", "稳定模板标识")).requiredOption("--source-version <version>", localize("Exact historical template package version", "模板包的精确历史版本")).option("--source-dir <directory>", localize("Read an extracted historical template package without executing it", "只读使用已解压的历史模板包,不执行其脚本")).option("--profile <profile>", localize("workspace-copy-v1 or repo-new-v1", "workspace-copy-v1 或 repo-new-v1"), "repo-new-v1").option("--package-name <name>", localize("Historical generated package name", "历史生成包名")).option("--rename-json", localize("Historical output used package.mock.json", "历史生成时使用了 package.mock.json")).option("--unverified", localize("Explicitly allow metadata-only association when the source is unavailable", "来源不可用时显式允许未验证关联")).option("--apply", localize("Apply the reviewed association without changing project files", "应用关联,不改写项目文件")).option("--json", localize("Output the plan as JSON", "以 JSON 输出计划")).option("--out <file>", localize("Write the plan or result to a file", "将计划或结果写入文件")).action(async (target, options, command) => {
|
|
1169
|
+
const { applyTemplateLinkPlan, planTemplateLink } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.d);
|
|
1170
|
+
const plan = await planTemplateLink({
|
|
1171
|
+
cwd: await templateWorkspaceRoot(),
|
|
1172
|
+
target,
|
|
1173
|
+
template: options.template,
|
|
1174
|
+
version: options.sourceVersion,
|
|
1175
|
+
profile: options.profile ?? "repo-new-v1",
|
|
1176
|
+
parameters: {
|
|
1177
|
+
...options.packageName ? { packageName: options.packageName } : {},
|
|
1178
|
+
...options.renameJson !== void 0 ? { renameJson: options.renameJson } : {}
|
|
1179
|
+
},
|
|
1180
|
+
allowUnverified: options.unverified === true,
|
|
1181
|
+
...options.sourceDir ? { sourceDir: options.sourceDir } : {}
|
|
1182
|
+
});
|
|
1183
|
+
await emitTemplateReport(options.apply ? await applyTemplateLinkPlan(plan) : plan, {
|
|
1184
|
+
...command.optsWithGlobals(),
|
|
1185
|
+
...options
|
|
1186
|
+
});
|
|
1187
|
+
});
|
|
1188
|
+
templates.command("relocate").description(localize("Associate a missing instance with an identical destination, without moving files", "显式关联已移动且可验证的实例,不移动业务文件")).argument("<instance>", localize("Registered instance ID or old path", "已登记实例 ID 或旧路径")).argument("<target>", localize("New workspace-relative path", "新相对工作区路径")).option("--apply", localize("Update the registered path", "更新登记路径")).option("--json", localize("Output JSON", "输出 JSON")).option("--out <file>", localize("Write the report to a file", "将报告写入文件")).action(async (instance, target, options, command) => {
|
|
1189
|
+
const { relocateTemplateInstance } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.d);
|
|
1190
|
+
await emitTemplateReport(await relocateTemplateInstance(await templateWorkspaceRoot(), instance, target, options.apply), {
|
|
1191
|
+
...command.optsWithGlobals(),
|
|
1192
|
+
...options
|
|
1193
|
+
});
|
|
1194
|
+
});
|
|
1195
|
+
templates.command("rebuild-baseline").description(localize("Reconstruct a retained baseline into a new isolated directory", "在新的隔离目录中重建留存基线")).argument("<instance>", localize("Instance ID or target", "实例 ID 或目标路径")).requiredOption("--destination <directory>", localize("A directory that does not exist", "尚不存在的目录")).option("--original", localize("Reconstruct the original template before repoctl transformations", "重建 repoctl 处理前的原始模板")).action(async (instance, options) => {
|
|
1196
|
+
const { rebuildTemplateInstanceBaseline } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.d);
|
|
1197
|
+
await emitTemplateReport({
|
|
1198
|
+
instance: (await rebuildTemplateInstanceBaseline(await templateWorkspaceRoot(), instance, path.resolve(options.destination), options.original ? "original" : "rendered")).id,
|
|
1199
|
+
destination: path.resolve(options.destination)
|
|
1200
|
+
}, {});
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
1203
|
+
//#endregion
|
|
1204
|
+
//#region src/cli/commands/template-catalog/fetch.ts
|
|
1205
|
+
function registerTemplateFetch(templates) {
|
|
1206
|
+
templates.command("fetch").description(localize("Fetch and verify fixed remote template assets", "获取并验证固定的远程模板资产")).argument("<key>").option("--offline", localize("Read only an exact verified cache entry", "只读取精确匹配且通过校验的缓存")).option("--cache-dir <directory>", localize("Template asset cache directory", "模板资产缓存目录")).option("--json", localize("Print resolved source identity as JSON", "以 JSON 输出固定来源身份")).action(async (key, _local, command) => {
|
|
1207
|
+
const options = command.optsWithGlobals();
|
|
1208
|
+
try {
|
|
1209
|
+
const cwd = process.cwd();
|
|
1210
|
+
const context = await loadTemplateCatalogContext({ cwd });
|
|
1211
|
+
const catalog = createTemplateCatalog(context);
|
|
1212
|
+
const invalid = catalog.diagnostics.find((item) => item.status === "fail" && (!item.template || item.template === key));
|
|
1213
|
+
const entry = catalog.entries.find((item) => item.key === key);
|
|
1214
|
+
if (invalid || !entry?.remote) throw new Error(invalid?.detail ?? `Template ${key} does not declare an npm or Git remote source.`);
|
|
1215
|
+
const cacheDir = options.cacheDir ?? context.createConfig.cacheDir;
|
|
1216
|
+
const result = await resolveRemoteTemplateSource(entry.remote, entry.source, {
|
|
1217
|
+
cwd,
|
|
1218
|
+
offline: options.offline ?? context.createConfig.offline ?? false,
|
|
1219
|
+
...cacheDir ? { cacheDir } : {}
|
|
1220
|
+
});
|
|
1221
|
+
process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : `${key}: ${result.cache}\n${JSON.stringify(result.resolved)}\n${result.sourceDir}`}\n`);
|
|
1222
|
+
} catch (error) {
|
|
1223
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1224
|
+
process.stdout.write(`${options.json ? JSON.stringify({ error: message }, null, 2) : message}\n`);
|
|
1225
|
+
process.exitCode = 1;
|
|
1226
|
+
}
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
//#endregion
|
|
1230
|
+
//#region src/cli/commands/template-catalog/format.ts
|
|
618
1231
|
function formatTemplateTable(choices) {
|
|
619
1232
|
const rows = choices.map((choice) => ({
|
|
620
1233
|
key: choice.key,
|
|
1234
|
+
origin: choice.origin,
|
|
621
1235
|
category: choice.category ?? "-",
|
|
1236
|
+
source: choice.sourceDir,
|
|
622
1237
|
target: choice.target,
|
|
623
1238
|
description: choice.description ?? ""
|
|
624
1239
|
}));
|
|
625
1240
|
const headers = {
|
|
626
1241
|
key: "key",
|
|
1242
|
+
origin: localize("origin", "来源"),
|
|
627
1243
|
category: localize("category", "分类"),
|
|
1244
|
+
source: localize("source", "源目录"),
|
|
628
1245
|
target: localize("target", "目标"),
|
|
629
1246
|
description: localize("description", "说明")
|
|
630
1247
|
};
|
|
631
1248
|
const widths = {
|
|
632
1249
|
key: Math.max(headers.key.length, ...rows.map((row) => row.key.length)),
|
|
1250
|
+
origin: Math.max(headers.origin.length, ...rows.map((row) => row.origin.length)),
|
|
633
1251
|
category: Math.max(headers.category.length, ...rows.map((row) => row.category.length)),
|
|
1252
|
+
source: Math.max(headers.source.length, ...rows.map((row) => row.source.length)),
|
|
634
1253
|
target: Math.max(headers.target.length, ...rows.map((row) => row.target.length))
|
|
635
1254
|
};
|
|
636
1255
|
return [
|
|
637
|
-
`${headers.key.padEnd(widths.key)} ${headers.category.padEnd(widths.category)} ${headers.target.padEnd(widths.target)} ${headers.description}`,
|
|
638
|
-
`${"-".repeat(widths.key)} ${"-".repeat(widths.category)} ${"-".repeat(widths.target)} ${"-".repeat(headers.description.length)}`,
|
|
639
|
-
...rows.map((row) => `${row.key.padEnd(widths.key)} ${row.category.padEnd(widths.category)} ${row.target.padEnd(widths.target)} ${row.description}`)
|
|
1256
|
+
`${headers.key.padEnd(widths.key)} ${headers.origin.padEnd(widths.origin)} ${headers.category.padEnd(widths.category)} ${headers.source.padEnd(widths.source)} ${headers.target.padEnd(widths.target)} ${headers.description}`,
|
|
1257
|
+
`${"-".repeat(widths.key)} ${"-".repeat(widths.origin)} ${"-".repeat(widths.category)} ${"-".repeat(widths.source)} ${"-".repeat(widths.target)} ${"-".repeat(headers.description.length)}`,
|
|
1258
|
+
...rows.map((row) => `${row.key.padEnd(widths.key)} ${row.origin.padEnd(widths.origin)} ${row.category.padEnd(widths.category)} ${row.source.padEnd(widths.source)} ${row.target.padEnd(widths.target)} ${row.description}`)
|
|
640
1259
|
].join("\n");
|
|
641
1260
|
}
|
|
642
1261
|
function formatTemplateDetail(choice) {
|
|
643
1262
|
return [
|
|
644
1263
|
`key: ${choice.key}`,
|
|
1264
|
+
`origin: ${choice.origin}`,
|
|
1265
|
+
`overridesBuiltin: ${choice.overridesBuiltin}`,
|
|
1266
|
+
...choice.configFile ? [`config: ${choice.configFile}:${choice.configPath ?? "commands.create.choices"}`] : [],
|
|
645
1267
|
localize(`label: ${choice.label}`, `标签:${choice.label}`),
|
|
646
1268
|
localize(`category: ${choice.category ?? "-"}`, `分类:${choice.category ?? "-"}`),
|
|
647
|
-
localize(`source:
|
|
1269
|
+
localize(`source: ${choice.sourceDir}`, `源目录:${choice.sourceDir}`),
|
|
648
1270
|
localize(`default target: ${choice.target}`, `默认目标:${choice.target}`),
|
|
649
1271
|
localize(`description: ${choice.description ?? "-"}`, `说明:${choice.description ?? "-"}`)
|
|
650
1272
|
].join("\n");
|
|
@@ -654,12 +1276,13 @@ function escapeMarkdownTableCell(value) {
|
|
|
654
1276
|
}
|
|
655
1277
|
function formatTemplateMarkdownTable(choices) {
|
|
656
1278
|
return [
|
|
657
|
-
localize("| Key | Category | Source | Default target | Description |", "| Key | 分类 | 源目录 | 默认目标 | 说明 |"),
|
|
658
|
-
"| --- | --- | --- | --- | --- |",
|
|
1279
|
+
localize("| Key | Origin | Category | Source | Default target | Description |", "| Key | 来源 | 分类 | 源目录 | 默认目标 | 说明 |"),
|
|
1280
|
+
"| --- | --- | --- | --- | --- | --- |",
|
|
659
1281
|
...choices.map((choice) => [
|
|
660
1282
|
`\`${choice.key}\``,
|
|
1283
|
+
choice.origin,
|
|
661
1284
|
choice.category ?? "-",
|
|
662
|
-
|
|
1285
|
+
`\`${choice.sourceDir}\``,
|
|
663
1286
|
`\`${choice.target}\``,
|
|
664
1287
|
choice.description ?? ""
|
|
665
1288
|
].map((value) => escapeMarkdownTableCell(value)).join(" | ")).map((row) => `| ${row} |`)
|
|
@@ -673,9 +1296,12 @@ function formatTemplateMarkdownDetail(choice) {
|
|
|
673
1296
|
"",
|
|
674
1297
|
localize("| Field | Value |", "| 字段 | 值 |"),
|
|
675
1298
|
"| --- | --- |",
|
|
1299
|
+
`| Origin | ${choice.origin} |`,
|
|
1300
|
+
`| Overrides built-in | ${choice.overridesBuiltin} |`,
|
|
1301
|
+
...choice.configFile ? [`| Config | ${escapeMarkdownTableCell(choice.configFile)}:${escapeMarkdownTableCell(choice.configPath ?? "commands.create.choices")} |`] : [],
|
|
676
1302
|
localize(`| Label | ${escapeMarkdownTableCell(choice.label)} |`, `| 标签 | ${escapeMarkdownTableCell(choice.label)} |`),
|
|
677
1303
|
localize(`| Category | ${escapeMarkdownTableCell(choice.category ?? "-")} |`, `| 分类 | ${escapeMarkdownTableCell(choice.category ?? "-")} |`),
|
|
678
|
-
localize(`| Source |
|
|
1304
|
+
localize(`| Source | \`${escapeMarkdownTableCell(choice.sourceDir)}\` |`, `| 源目录 | \`${escapeMarkdownTableCell(choice.sourceDir)}\` |`),
|
|
679
1305
|
localize(`| Default target | \`${escapeMarkdownTableCell(choice.target)}\` |`, `| 默认目标 | \`${escapeMarkdownTableCell(choice.target)}\` |`)
|
|
680
1306
|
].join("\n");
|
|
681
1307
|
}
|
|
@@ -701,31 +1327,92 @@ function formatTemplateHealthReport(report, color = false) {
|
|
|
701
1327
|
lines.push(color ? localize(`summary: ${pc.green(String(report.summary.pass))} pass, ${pc.yellow(String(report.summary.warn))} warn, ${pc.red(String(report.summary.fail))} fail`, `摘要:${pc.green(String(report.summary.pass))} 通过,${pc.yellow(String(report.summary.warn))} 警告,${pc.red(String(report.summary.fail))} 失败`) : localize(`summary: ${report.summary.pass} pass, ${report.summary.warn} warn, ${report.summary.fail} fail`, `摘要:${report.summary.pass} 通过,${report.summary.warn} 警告,${report.summary.fail} 失败`));
|
|
702
1328
|
return lines.join("\n");
|
|
703
1329
|
}
|
|
1330
|
+
//#endregion
|
|
1331
|
+
//#region src/cli/commands/template-catalog/validate.ts
|
|
1332
|
+
async function readParameterMatrix(filename) {
|
|
1333
|
+
const content = await readFile(path$1.resolve(filename));
|
|
1334
|
+
if (content.length > 1048576) throw new Error("Template parameter matrix exceeds 1 MiB.");
|
|
1335
|
+
let value;
|
|
1336
|
+
try {
|
|
1337
|
+
value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(content));
|
|
1338
|
+
} catch {
|
|
1339
|
+
throw new Error("Template parameter matrix must contain valid UTF-8 JSON.");
|
|
1340
|
+
}
|
|
1341
|
+
if (!Array.isArray(value)) throw new TypeError("Template parameter matrix must be an array of parameter objects.");
|
|
1342
|
+
return value;
|
|
1343
|
+
}
|
|
1344
|
+
function registerTemplateValidation(templates) {
|
|
1345
|
+
templates.command("validate").description(localize("Generate, install and validate an isolated template sample", "生成、安装并验证隔离的模板样本")).argument("<key>").option("--offline", localize("Use only verified cached remote assets", "只使用通过校验的远程资产缓存")).option("--cache-dir <directory>", localize("Template asset cache directory", "模板资产缓存目录")).option("--name <name>", localize("Sample name; repeat for a matrix", "样本名称,可重复用于组合验证"), (name, previous = []) => [...previous, name]).option("--parameter-matrix <file>", localize("JSON array of typed parameter objects, crossed with names", "类型化参数对象的 JSON 数组文件,与样本名称交叉验证")).option("--fixture <directory>", localize("Author workspace fixture to copy", "需要复制的作者工作区样本")).option("--timeout <ms>", localize("Timeout per child command", "每个子命令超时毫秒数")).option("--keep-failed", localize("Keep failing samples and diagnostics", "保留失败样本和诊断")).option("--keep-temp", localize("Keep every generated sample", "保留全部生成样本")).option("--dry-run", localize("Inspect the plan without generation or commands", "只检查计划,不生成或执行命令")).option("--json", localize("Print machine-readable JSON", "输出 JSON")).option("--out <file>", localize("Write the report to a file", "报告写入文件")).action(async (key, _localOptions, command) => {
|
|
1346
|
+
const opts = command.optsWithGlobals();
|
|
1347
|
+
const controller = new AbortController();
|
|
1348
|
+
const interrupt = () => controller.abort("SIGINT");
|
|
1349
|
+
const terminate = () => controller.abort("SIGTERM");
|
|
1350
|
+
process.on("SIGINT", interrupt);
|
|
1351
|
+
process.on("SIGTERM", terminate);
|
|
1352
|
+
try {
|
|
1353
|
+
const options = {
|
|
1354
|
+
template: key,
|
|
1355
|
+
cwd: process.cwd(),
|
|
1356
|
+
signal: controller.signal,
|
|
1357
|
+
...opts.offline !== void 0 ? { offline: opts.offline } : {},
|
|
1358
|
+
...opts.cacheDir ? { cacheDir: opts.cacheDir } : {},
|
|
1359
|
+
...opts.name ? { names: opts.name } : {},
|
|
1360
|
+
...opts.parameterMatrix ? { parameterSets: await readParameterMatrix(opts.parameterMatrix) } : {},
|
|
1361
|
+
...opts.fixture ? { fixtureDir: opts.fixture } : {},
|
|
1362
|
+
...opts.timeout ? { timeoutMs: Number(opts.timeout) } : {},
|
|
1363
|
+
keep: opts.keepTemp ? "always" : opts.keepFailed ? "failure" : "never"
|
|
1364
|
+
};
|
|
1365
|
+
const result = opts.dryRun ? await planTemplateValidation(options) : await validateTemplate(options);
|
|
1366
|
+
const json = JSON.stringify(result, null, 2);
|
|
1367
|
+
if (opts.out) await writeFile(path$1.resolve(opts.out), `${json}\n`);
|
|
1368
|
+
if (opts.json) process.stdout.write(`${json}\n`);
|
|
1369
|
+
else if ("status" in result) {
|
|
1370
|
+
process.stdout.write(`Template ${key}: ${result.status}\n`);
|
|
1371
|
+
for (const diagnostic of result.plan.diagnostics) process.stdout.write(`[${diagnostic.code}] ${diagnostic.message}\n`);
|
|
1372
|
+
for (const sample of result.samples) {
|
|
1373
|
+
process.stdout.write(`${sample.name} [parameters ${sample.parameterSet + 1}]: ${sample.status}${sample.failedStage ? ` (${sample.failedStage})` : ""}\n`);
|
|
1374
|
+
for (const step of sample.steps.filter((step) => step.status !== "passed")) process.stdout.write(`${step.command?.output ?? step.diagnostics.map((item) => `[${item.code}] ${item.message}`).join("\n")}\n`);
|
|
1375
|
+
}
|
|
1376
|
+
if (result.retained) process.stdout.write(`Retained: ${result.temporaryDirectory}\n`);
|
|
1377
|
+
} else process.stdout.write(`${json}\n`);
|
|
1378
|
+
process.exitCode = controller.signal.aborted ? controller.signal.reason === "SIGTERM" ? 143 : 130 : ("status" in result ? result.status !== "passed" : result.diagnostics.length > 0) ? 1 : 0;
|
|
1379
|
+
} finally {
|
|
1380
|
+
process.removeListener("SIGINT", interrupt);
|
|
1381
|
+
process.removeListener("SIGTERM", terminate);
|
|
1382
|
+
}
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
//#endregion
|
|
1386
|
+
//#region src/cli/commands/template-catalog/index.ts
|
|
704
1387
|
async function emitTemplateOutput(content, options) {
|
|
705
1388
|
if (!options.out) {
|
|
706
|
-
|
|
1389
|
+
if (options.json) process.stdout.write(`${content}\n`);
|
|
1390
|
+
else logger.log(content);
|
|
707
1391
|
return;
|
|
708
1392
|
}
|
|
709
1393
|
const outFile = path.resolve(process.cwd(), options.out);
|
|
710
|
-
await fs.outputFile(outFile, `${content}\n`, "utf8");
|
|
1394
|
+
await fs$1.outputFile(outFile, `${content}\n`, "utf8");
|
|
711
1395
|
logger.success(localize(`Wrote ${path.relative(process.cwd(), outFile)}`, `已写入 ${path.relative(process.cwd(), outFile)}`));
|
|
712
1396
|
}
|
|
713
1397
|
function registerTemplatesCommands(program) {
|
|
714
|
-
program.command("templates").alias("tpl").description(localize("List
|
|
715
|
-
const {
|
|
1398
|
+
const templates = program.command("templates").alias("tpl").description(localize("List built-in and configured templates", "列出内置与自定义模板")).argument("[key]", localize("Show details for a template key", "查看指定模板详情")).option("-c, --category <category>", localize("Filter by library, app, service, docs, or tool", "按模板分类过滤:library / app / service / docs / tool")).option("--check", localize("Check template configuration, metadata and directories", "检查模板配置、元数据、目录和临时文件")).option("--json", localize("Output JSON for scripts", "输出 JSON,方便脚本消费")).option("--markdown", localize("Output Markdown for documentation", "输出 Markdown,方便同步文档")).option("--out <file>", localize("Write output to a file", "把当前输出写入文件")).action(async (key, opts) => {
|
|
1399
|
+
const { isTemplateCategory, suggestTemplateKey, templateCategories } = await import("@icebreakers/monorepo-templates");
|
|
716
1400
|
if (opts.check) {
|
|
717
|
-
const { checkTemplates } = await import("./commands-
|
|
1401
|
+
const { checkTemplates } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
718
1402
|
const report = await checkTemplates();
|
|
719
1403
|
if (opts.json) await emitTemplateOutput(JSON.stringify(report, null, 2), opts);
|
|
720
1404
|
else await emitTemplateOutput(formatTemplateHealthReport(report, !opts.out), opts);
|
|
721
1405
|
if (report.summary.fail > 0) process.exitCode = 1;
|
|
722
1406
|
return;
|
|
723
1407
|
}
|
|
1408
|
+
const catalog = await resolveTemplateCatalog();
|
|
1409
|
+
for (const diagnostic of catalog.diagnostics) process.stderr.write(`[${diagnostic.status.toUpperCase()}] ${diagnostic.configFile ?? "repoctl.config"}:${diagnostic.configPath}: ${diagnostic.detail}\n`);
|
|
1410
|
+
if (catalog.diagnostics.some((diagnostic) => diagnostic.status === "fail")) process.exitCode = 1;
|
|
724
1411
|
if (key) {
|
|
725
|
-
const choice =
|
|
1412
|
+
const choice = catalog.entries.find((entry) => entry.key === key);
|
|
726
1413
|
if (!choice) {
|
|
727
1414
|
logger.error(localize(`Unknown template: ${key}`, `未知模板:${key}`));
|
|
728
|
-
const suggestion = suggestTemplateKey(key);
|
|
1415
|
+
const suggestion = suggestTemplateKey(key, { keys: catalog.entries.map((entry) => entry.key) });
|
|
729
1416
|
if (suggestion) logger.info(localize(`Did you mean \`${suggestion}\`?`, `你是否想使用 \`${suggestion}\`?`));
|
|
730
1417
|
logger.info(localize("Run `repo templates` to list available templates.", "运行 `repo templates` 查看可用模板。"));
|
|
731
1418
|
process.exitCode = 1;
|
|
@@ -753,7 +1440,7 @@ function registerTemplatesCommands(program) {
|
|
|
753
1440
|
}
|
|
754
1441
|
category = opts.category;
|
|
755
1442
|
}
|
|
756
|
-
const choices =
|
|
1443
|
+
const choices = category ? catalog.entries.filter((entry) => entry.category === category) : catalog.entries;
|
|
757
1444
|
if (opts.json) {
|
|
758
1445
|
await emitTemplateOutput(JSON.stringify(choices, null, 2), opts);
|
|
759
1446
|
return;
|
|
@@ -765,18 +1452,15 @@ function registerTemplatesCommands(program) {
|
|
|
765
1452
|
await emitTemplateOutput(localize(`Available templates:\n${formatTemplateTable(choices)}`, `可用模板:\n${formatTemplateTable(choices)}`), opts);
|
|
766
1453
|
if (!opts.out) logger.info(localize("Next: run `repo new <name> --template <key>`.", "下一步:运行 `repo new <name> --template <key>`。"));
|
|
767
1454
|
});
|
|
1455
|
+
registerTemplateInstanceCommands(templates);
|
|
1456
|
+
registerTemplateValidation(templates);
|
|
1457
|
+
registerTemplateFetch(templates);
|
|
768
1458
|
}
|
|
769
1459
|
//#endregion
|
|
770
1460
|
//#region src/cli/utils.ts
|
|
771
|
-
function normalizeCliOpts(cwd, opts) {
|
|
772
|
-
return {
|
|
773
|
-
...opts,
|
|
774
|
-
core: opts.core ?? false,
|
|
775
|
-
cwd
|
|
776
|
-
};
|
|
777
|
-
}
|
|
778
1461
|
function normalizeCleanOptions(opts) {
|
|
779
1462
|
const overrides = {};
|
|
1463
|
+
if (opts.dryRun) overrides.dryRun = true;
|
|
780
1464
|
if (opts.yes) overrides.autoConfirm = true;
|
|
781
1465
|
if (opts.includePrivate) overrides.includePrivate = true;
|
|
782
1466
|
if (opts.pinnedVersion) overrides.pinnedVersion = opts.pinnedVersion;
|
|
@@ -789,11 +1473,108 @@ function normalizeToolingTargets(tooling) {
|
|
|
789
1473
|
return tooling;
|
|
790
1474
|
}
|
|
791
1475
|
//#endregion
|
|
1476
|
+
//#region src/cli/commands/tooling/capabilities.ts
|
|
1477
|
+
function registerCapabilityCommands(toolingCommand, cwd) {
|
|
1478
|
+
const capabilities = toolingCommand.command("capability").description(localize("Add an incremental tooling capability", "增量接入工程化能力包"));
|
|
1479
|
+
capabilities.command("list").option("--json").action((options) => {
|
|
1480
|
+
const result = listToolingCapabilities();
|
|
1481
|
+
if (options.json) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1482
|
+
else result.forEach((item) => logger.info(`${item.id}@${item.version}: ${item.description}`));
|
|
1483
|
+
});
|
|
1484
|
+
capabilities.command("plan <capability>").requiredOption("--target <workspace>").option("--route <path>").option("--expect-text <text>").option("--test-id <id>").option("--role <role>").option("--name <name>").option("--directory <path>").option("--port <port>").option("--ci-port <port>").option("--reuse-existing-server").option("--framework <framework>").option("--component <export>").option("--example <json-file>").option("--json").action(async (capability, options) => {
|
|
1485
|
+
if (!["playwright", "storybook"].includes(capability)) throw new Error(`Unknown tooling capability: ${capability}`);
|
|
1486
|
+
const click = options.testId ? { testId: options.testId } : {
|
|
1487
|
+
role: options.role ?? "button",
|
|
1488
|
+
name: options.name
|
|
1489
|
+
};
|
|
1490
|
+
const input = capability === "playwright" ? {
|
|
1491
|
+
capability,
|
|
1492
|
+
target: options.target,
|
|
1493
|
+
interaction: {
|
|
1494
|
+
route: options.route,
|
|
1495
|
+
click,
|
|
1496
|
+
expectText: options.expectText
|
|
1497
|
+
},
|
|
1498
|
+
...options.directory ? { directory: options.directory } : {},
|
|
1499
|
+
...options.port ? { port: Number(options.port) } : {},
|
|
1500
|
+
...options.ciPort ? { ciPort: Number(options.ciPort) } : {},
|
|
1501
|
+
...options.reuseExistingServer ? { reuseExistingServer: true } : {}
|
|
1502
|
+
} : {
|
|
1503
|
+
capability,
|
|
1504
|
+
target: options.target,
|
|
1505
|
+
...options.directory ? { directory: options.directory } : {},
|
|
1506
|
+
framework: options.framework,
|
|
1507
|
+
component: options.component,
|
|
1508
|
+
example: options.example ? JSON.parse(await readFile(options.example, "utf8")) : void 0
|
|
1509
|
+
};
|
|
1510
|
+
const result = await planToolingCapability(cwd, input);
|
|
1511
|
+
if (options.json) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1512
|
+
else logger.info(`${result.status}: ${result.files.length} files, ${result.conflicts.length} conflicts`);
|
|
1513
|
+
});
|
|
1514
|
+
capabilities.command("apply <plan>").option("--json").action(async (file, options) => {
|
|
1515
|
+
const result = await applyToolingCapability(JSON.parse(await readFile(file, "utf8")));
|
|
1516
|
+
if (options.json) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1517
|
+
else logger.success(localize("Tooling capability applied.", "工程化能力包已应用。"));
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
//#endregion
|
|
1521
|
+
//#region src/cli/commands/tooling/devcontainer.ts
|
|
1522
|
+
function registerDevContainerCommand(command, cwd) {
|
|
1523
|
+
command.command("devcontainer").description(localize("Preview a pnpm Dev Container preset, or apply a reviewed plan", "预览 pnpm Dev Container 预设,或应用已审查的计划")).option("--node-version <version>", localize("Choose an exact Node version allowed by engines.node", "选择 engines.node 允许的精确 Node 版本")).option("--apply <plan>", localize("Apply a saved JSON plan without starting containers", "应用已保存的 JSON 计划,不启动容器")).option("--dry-run", localize("Preview only (the default)", "只读预览(默认行为)")).option("--json", localize("Output JSON with generated files and diffs", "输出包含生成文件与差异的 JSON")).option("--out <file>", localize("Save the JSON preview to a new file", "将 JSON 预览保存到一个新文件")).action(async (_options, current) => {
|
|
1524
|
+
const options = current.optsWithGlobals();
|
|
1525
|
+
const { applyDevContainerPlan, planDevContainer } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1526
|
+
if (options.apply) {
|
|
1527
|
+
if (options.nodeVersion || options.dryRun || options.out) throw new Error("--apply cannot be combined with preview or selection options.");
|
|
1528
|
+
const filename = path.resolve(cwd, options.apply);
|
|
1529
|
+
if ((await stat(filename)).size > 1048576) throw new Error("Dev Container plan exceeds 1 MiB.");
|
|
1530
|
+
const result = await applyDevContainerPlan(cwd, JSON.parse(await readFile(filename, "utf8")));
|
|
1531
|
+
process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : `${result.status}: ${result.files.join(", ") || result.workspaceDir}`}\n`);
|
|
1532
|
+
return;
|
|
1533
|
+
}
|
|
1534
|
+
const plan = await planDevContainer(cwd, options.nodeVersion ? { nodeVersion: options.nodeVersion } : {});
|
|
1535
|
+
const json = `${JSON.stringify(plan, null, 2)}\n`;
|
|
1536
|
+
if (options.out) {
|
|
1537
|
+
const filename = path.resolve(cwd, options.out);
|
|
1538
|
+
const relative = path.relative(plan.workspaceDir, filename);
|
|
1539
|
+
if (relative === ".devcontainer.json" || relative === ".devcontainer" || relative.startsWith(".devcontainer/")) throw new Error("Save the reviewed plan outside the Dev Container target paths.");
|
|
1540
|
+
await writeFile(filename, json, { flag: "wx" });
|
|
1541
|
+
}
|
|
1542
|
+
process.stdout.write(`${options.json ? json.trimEnd() : [
|
|
1543
|
+
`${plan.status}: ${plan.image} / ${plan.packageManager}`,
|
|
1544
|
+
...plan.files.map((file) => `${file.action}: ${file.path}`),
|
|
1545
|
+
...plan.blockers,
|
|
1546
|
+
...plan.files.filter((file) => file.action === "preserve" && file.diff).map((file) => file.diff),
|
|
1547
|
+
localize("Review the JSON plan, then use --apply <plan>. Start the container explicitly in your editor or Dev Containers CLI.", "审查 JSON 计划后使用 --apply <plan>;通过编辑器或 Dev Containers CLI 主动启动容器。")
|
|
1548
|
+
].join("\n")}\n`);
|
|
1549
|
+
if (plan.status === "blocked") process.exitCode = 1;
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
//#endregion
|
|
1553
|
+
//#region src/cli/commands/tooling/references.ts
|
|
1554
|
+
function output(value) {
|
|
1555
|
+
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
1556
|
+
}
|
|
1557
|
+
function registerProjectReferencesCommands(tooling, cwd) {
|
|
1558
|
+
const command = tooling.command("references").description(localize("Inspect and synchronize TypeScript project references", "检查和同步 TypeScript project references"));
|
|
1559
|
+
command.command("check").option("--json", localize("Output stable JSON (default)", "输出稳定 JSON(默认)")).description(localize("Check existing or explicitly managed references without writing", "只读检查已有或显式受管的引用")).action(async () => {
|
|
1560
|
+
const result = await checkProjectReferences(cwd);
|
|
1561
|
+
output(result);
|
|
1562
|
+
if (!result.ok) process.exitCode = 1;
|
|
1563
|
+
});
|
|
1564
|
+
command.command("plan").option("--json", localize("Output stable JSON (default)", "输出稳定 JSON(默认)")).description(localize("Preview a serializable references plan", "预览可保存的引用计划")).action(async () => output(await planProjectReferences(cwd)));
|
|
1565
|
+
command.command("sync").option("--dry-run", localize("Preview without writing", "预览但不写入")).description(localize("Synchronize explicitly enabled references", "同步显式启用的引用")).action(async (options) => output(options.dryRun ? await planProjectReferences(cwd) : await syncProjectReferences(cwd)));
|
|
1566
|
+
command.command("apply <plan>").description(localize("Apply a reviewed JSON plan", "应用已审阅的 JSON 计划")).action(async (file) => output(await applyProjectReferencesPlan(JSON.parse(await readFile(file, "utf8")))));
|
|
1567
|
+
}
|
|
1568
|
+
//#endregion
|
|
792
1569
|
//#region src/cli/commands/tooling.ts
|
|
793
1570
|
function registerToolingCommands(program, cwd) {
|
|
794
|
-
program.command("tooling").alias("tg").description(localize("Tooling configuration commands", "工程化配置命令"))
|
|
1571
|
+
const toolingCommand = program.command("tooling").alias("tg").description(localize("Tooling configuration commands", "工程化配置命令"));
|
|
1572
|
+
registerProjectReferencesCommands(toolingCommand, cwd);
|
|
1573
|
+
registerCapabilityCommands(toolingCommand, cwd);
|
|
1574
|
+
registerDevContainerCommand(toolingCommand, cwd);
|
|
1575
|
+
toolingCommand.command("init").description(localize(`Generate tooling configuration (${initToolingTargets.join(", ")})`, `生成 tooling 配置(可选值:${initToolingTargets.join(", ")})`)).alias("i").argument("[tooling...]").option("-a, --all", localize("Generate every tooling configuration", "生成全部 tooling 配置")).option("-f, --force", localize("Overwrite existing tooling configuration files", "覆盖已存在的 tooling 配置文件")).action(async (tooling = [], opts) => {
|
|
795
1576
|
const normalizedTooling = normalizeToolingTargets(tooling);
|
|
796
|
-
const { initTooling } = await import("./commands-
|
|
1577
|
+
const { initTooling } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
797
1578
|
await initTooling(cwd, {
|
|
798
1579
|
...normalizedTooling ? { targets: normalizedTooling } : {},
|
|
799
1580
|
...opts.all !== void 0 ? { all: opts.all } : {},
|
|
@@ -803,6 +1584,114 @@ function registerToolingCommands(program, cwd) {
|
|
|
803
1584
|
});
|
|
804
1585
|
}
|
|
805
1586
|
//#endregion
|
|
1587
|
+
//#region src/cli/commands/check/cache.ts
|
|
1588
|
+
function registerCacheAnalysis(check, cwd) {
|
|
1589
|
+
check.command("cache <current> [previous]").description(localize("Analyze existing Turbo run summaries without running tasks", "只读分析已有 Turbo run summaries")).option("--json", localize("Output structured analysis", "输出结构化分析")).option("--markdown", localize("Output a Markdown report to stdout", "向标准输出写入 Markdown 报告")).option("--slowest <count>", localize("Number of slow tasks (1–100)", "最慢任务数量(1–100)")).option("--dry-run", localize("Read-only analysis (always enabled)", "只读分析(始终启用)")).action(async (current, previous, options, command) => {
|
|
1590
|
+
const parent = check.opts();
|
|
1591
|
+
const incompatible = Object.keys(parent).filter((key) => ![
|
|
1592
|
+
"json",
|
|
1593
|
+
"markdown",
|
|
1594
|
+
"dryRun"
|
|
1595
|
+
].includes(key) && parent[key] !== void 0);
|
|
1596
|
+
if (incompatible.length) throw new Error(`check cache does not accept parent execution/plan options: ${incompatible.join(", ")}`);
|
|
1597
|
+
const json = options.json || parent["json"] === true;
|
|
1598
|
+
const markdown = options.markdown || parent["markdown"] === true;
|
|
1599
|
+
if (json && markdown) throw new Error("--json and --markdown cannot be combined");
|
|
1600
|
+
const own = command.opts();
|
|
1601
|
+
const { analyzeTurboRuns } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.G);
|
|
1602
|
+
const { formatTurboAnalysis } = await import("./format-Dbs0fupU.mjs");
|
|
1603
|
+
const result = await analyzeTurboRuns(path.resolve(cwd, current), {
|
|
1604
|
+
...previous !== void 0 ? { previous: path.resolve(cwd, previous) } : {},
|
|
1605
|
+
...own.slowest !== void 0 ? { slowest: Number(own.slowest) } : {}
|
|
1606
|
+
});
|
|
1607
|
+
process.stdout.write(`${json ? JSON.stringify(result, null, 2) : formatTurboAnalysis(result, markdown)}\n`);
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
//#endregion
|
|
1611
|
+
//#region src/cli/commands/check/knip.ts
|
|
1612
|
+
function formatReport(report) {
|
|
1613
|
+
return [
|
|
1614
|
+
`Knip ${report.plan.tool.version ?? "(not installed)"}: ${report.status}; ${report.summary.errors} errors, ${report.summary.warnings} warnings`,
|
|
1615
|
+
...report.findings.map((item) => `[${item.severity}] ${item.type} / ${item.workspace}: ${item.file}${item.line !== void 0 ? `:${item.line}:${item.column ?? 0}` : ""} ${item.symbol}`),
|
|
1616
|
+
...report.baseline.status !== "none" ? [`baseline: ${report.baseline.status}; existing=${report.baseline.existing.length}, added=${report.baseline.added.length}, fixed=${report.baseline.fixed.length}`] : [],
|
|
1617
|
+
...report.diagnostics.map((item) => `${item.code}: ${item.message}`)
|
|
1618
|
+
].join("\n");
|
|
1619
|
+
}
|
|
1620
|
+
function registerKnipCheck(check, cwd) {
|
|
1621
|
+
check.command("knip").description(localize("Explicitly check unused files, exports and dependency declarations with local Knip", "显式使用本地 Knip 检查闲置文件、导出和依赖声明")).option("--config <file>", localize("Use an existing native Knip configuration", "使用现有原生 Knip 配置")).option("--baseline <file>", localize("Compare with a saved baseline relative to the workspace root", "与工作区根目录相对路径下的基线比较")).option("--new-only", localize("Fail only for new error findings; requires --baseline", "仅新增 error 阻断;必须指定 --baseline")).option("--production", localize("Use native Knip production scope", "使用 Knip 原生 production 范围")).option("--strict", localize("Use native per-workspace dependency strictness; also enables production scope", "使用 Knip 原生工作区直接依赖检查;同时启用 production 范围")).option("--save-baseline <file>", localize("Explicitly save current findings; does not suppress their exit status", "显式保存当前问题;不隐藏本次问题的退出码")).option("--recommend-config", localize("Print native configuration suggestions without writing", "只读输出原生配置合并建议")).option("--dry-run", localize("Preview the local tool command without running Knip", "预览本地工具命令,不运行 Knip")).option("--timeout <ms>", localize("Tool timeout in milliseconds (default 120000)", "工具超时毫秒数(默认 120000)")).option("--json", localize("Output the actual report as JSON (use --dry-run for a plan)", "以 JSON 输出实际报告(计划请另加 --dry-run)")).action(async (localOptions) => {
|
|
1622
|
+
const inherited = check.opts();
|
|
1623
|
+
if (Object.entries(inherited).some(([key, value]) => !["json", "dryRun"].includes(key) && value !== void 0 && value !== false)) throw new Error("Do not combine check knip with parent check modes or execution options.");
|
|
1624
|
+
const opts = {
|
|
1625
|
+
...inherited,
|
|
1626
|
+
...localOptions
|
|
1627
|
+
};
|
|
1628
|
+
if (opts.saveBaseline && (opts.baseline || opts.newOnly || opts.dryRun || opts.recommendConfig)) throw new Error("--save-baseline cannot be combined with --baseline, --new-only, --dry-run or --recommend-config.");
|
|
1629
|
+
if (opts.recommendConfig && (opts.config || opts.baseline || opts.newOnly || opts.timeout || opts.production || opts.strict)) throw new Error("--recommend-config only provides native configuration suggestions; it cannot run or compare an analysis.");
|
|
1630
|
+
const { getKnipConfigurationSuggestions, planKnipCheck, runKnipCheck, saveKnipBaseline } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.L);
|
|
1631
|
+
if (opts.recommendConfig) {
|
|
1632
|
+
process.stdout.write(`${JSON.stringify(await getKnipConfigurationSuggestions(cwd), null, 2)}\n`);
|
|
1633
|
+
return;
|
|
1634
|
+
}
|
|
1635
|
+
const options = {
|
|
1636
|
+
...opts.config ? { config: opts.config } : {},
|
|
1637
|
+
...opts.baseline ? { baseline: opts.baseline } : {},
|
|
1638
|
+
...opts.newOnly !== void 0 ? { newOnly: opts.newOnly } : {},
|
|
1639
|
+
...opts.production !== void 0 ? { production: opts.production } : {},
|
|
1640
|
+
...opts.strict !== void 0 ? { strict: opts.strict } : {},
|
|
1641
|
+
...opts.timeout ? { timeoutMs: Number(opts.timeout) } : {}
|
|
1642
|
+
};
|
|
1643
|
+
if (opts.dryRun) {
|
|
1644
|
+
const plan = await planKnipCheck(cwd, options);
|
|
1645
|
+
process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`);
|
|
1646
|
+
if (plan.status !== "ready") process.exitCode = 2;
|
|
1647
|
+
return;
|
|
1648
|
+
}
|
|
1649
|
+
const controller = new AbortController();
|
|
1650
|
+
const interrupt = () => controller.abort("SIGINT");
|
|
1651
|
+
const terminate = () => controller.abort("SIGTERM");
|
|
1652
|
+
process.on("SIGINT", interrupt);
|
|
1653
|
+
process.on("SIGTERM", terminate);
|
|
1654
|
+
try {
|
|
1655
|
+
const report = await runKnipCheck(cwd, {
|
|
1656
|
+
...options,
|
|
1657
|
+
signal: controller.signal
|
|
1658
|
+
});
|
|
1659
|
+
const baselineSaved = opts.saveBaseline && report.status === "completed" ? await saveKnipBaseline(cwd, report, opts.saveBaseline) : void 0;
|
|
1660
|
+
const savedText = baselineSaved ? `\nbaseline ${baselineSaved.status}: ${baselineSaved.path}${baselineSaved.cleanupPending.length ? `\nInspect retained temporary files: ${baselineSaved.cleanupPending.join(", ")}` : ""}` : "";
|
|
1661
|
+
process.stdout.write(`${opts.json ? JSON.stringify({
|
|
1662
|
+
...report,
|
|
1663
|
+
...baselineSaved ? { baselineSaved } : {}
|
|
1664
|
+
}, null, 2) : `${formatReport(report)}${savedText}`}\n`);
|
|
1665
|
+
process.exitCode = report.exitCode;
|
|
1666
|
+
} finally {
|
|
1667
|
+
process.removeListener("SIGINT", interrupt);
|
|
1668
|
+
process.removeListener("SIGTERM", terminate);
|
|
1669
|
+
}
|
|
1670
|
+
});
|
|
1671
|
+
}
|
|
1672
|
+
//#endregion
|
|
1673
|
+
//#region src/cli/commands/check/affected.ts
|
|
1674
|
+
function formatAffectedCheckPlan(plan, markdown = false) {
|
|
1675
|
+
return [
|
|
1676
|
+
...markdown ? [localize("# Affected check plan", "# Affected 校验计划"), ""] : [],
|
|
1677
|
+
`cwd: ${plan.cwd}`,
|
|
1678
|
+
`mode: affected (${plan.strategy})`,
|
|
1679
|
+
`range: ${plan.git.base}...${plan.git.head}${plan.git.includesWorkingTree ? " + working tree" : ""}`,
|
|
1680
|
+
...plan.fallback.map((reason) => `! ${localize("Full fallback", "全量回退")}: ${reason.code}${reason.files ? ` (${reason.files.join(", ")})` : ""}${reason.diagnostics ? ` [${reason.diagnostics.map((item) => item.code).join(", ")}]` : ""}`),
|
|
1681
|
+
"",
|
|
1682
|
+
localize("Packages:", "包选择:"),
|
|
1683
|
+
...plan.packages.map((pkg) => `- ${pkg.id}: ${pkg.selected ? "selected" : pkg.skippedReason}; ${pkg.reasons.map((reason) => `${reason.code}${reason.path ? ` (${reason.path.join(" -> ")})` : ""}${reason.files ? ` (${reason.files.join(", ")})` : ""}`).join("; ")}`),
|
|
1684
|
+
...plan.files.filter((file) => file.reason === "documentation").map((file) => `- ${file.path}: documentation`),
|
|
1685
|
+
"",
|
|
1686
|
+
localize("Commands (build first):", "命令(先构建):"),
|
|
1687
|
+
...plan.commands.flatMap((command) => [
|
|
1688
|
+
`- ${command.name}: ${command.skipReason ? `skipped (${command.skipReason})` : command.command}`,
|
|
1689
|
+
...command.missingTargets.length ? [` missing_script: ${command.missingTargets.join(", ")}`] : [],
|
|
1690
|
+
...command.prerequisiteTargets.length ? [` build_prerequisites: ${command.prerequisiteTargets.join(", ")}`] : []
|
|
1691
|
+
])
|
|
1692
|
+
].join("\n");
|
|
1693
|
+
}
|
|
1694
|
+
//#endregion
|
|
806
1695
|
//#region src/cli/commands/check/output.ts
|
|
807
1696
|
function formatCheckPlan(plan) {
|
|
808
1697
|
const lines = [
|
|
@@ -848,16 +1737,96 @@ function redactCheckPlanValue(value, replacements) {
|
|
|
848
1737
|
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactCheckPlanValue(item, replacements)]));
|
|
849
1738
|
return value;
|
|
850
1739
|
}
|
|
851
|
-
function
|
|
852
|
-
return redactCheckPlanValue(
|
|
1740
|
+
function redactCheckOutput(value, cwd) {
|
|
1741
|
+
return redactCheckPlanValue(value, [[cwd, "<cwd>"], [os.homedir(), "<home>"]].filter(([search], index, entries) => search.length > 0 && entries.findIndex(([value]) => value === search) === index).sort(([left], [right]) => right.length - left.length));
|
|
853
1742
|
}
|
|
854
1743
|
function createCheckPlanOutput(plan, opts) {
|
|
855
|
-
const outputPlan = opts.redact ?
|
|
1744
|
+
const outputPlan = opts.redact ? redactCheckOutput(plan, plan.cwd) : plan;
|
|
856
1745
|
if (opts.json) return JSON.stringify(outputPlan, null, 2);
|
|
1746
|
+
if (outputPlan.mode === "affected") return formatAffectedCheckPlan(outputPlan, opts.markdown);
|
|
857
1747
|
if (opts.markdown) return formatCheckPlanMarkdown(outputPlan);
|
|
858
1748
|
return formatCheckPlan(outputPlan);
|
|
859
1749
|
}
|
|
860
1750
|
//#endregion
|
|
1751
|
+
//#region src/cli/commands/check/index.ts
|
|
1752
|
+
const collect$1 = (value, previous = []) => [...previous, value];
|
|
1753
|
+
async function emitCheckOutput(content, opts, cwd, stdout) {
|
|
1754
|
+
if (!opts.out) {
|
|
1755
|
+
if (stdout) process.stdout.write(`${content}\n`);
|
|
1756
|
+
else logger.log(content);
|
|
1757
|
+
return;
|
|
1758
|
+
}
|
|
1759
|
+
const outFile = path.resolve(cwd, opts.out);
|
|
1760
|
+
await fs$1.outputFile(outFile, `${content}\n`, "utf8");
|
|
1761
|
+
logger.success(localize(`Wrote ${path.relative(cwd, outFile)}`, `已写入 ${path.relative(cwd, outFile)}`));
|
|
1762
|
+
}
|
|
1763
|
+
async function emitCheckPlan(plan, opts, cwd) {
|
|
1764
|
+
await emitCheckOutput(createCheckPlanOutput(plan, opts), opts, cwd, plan.mode === "affected");
|
|
1765
|
+
}
|
|
1766
|
+
function registerCheckCommand(program, cwd) {
|
|
1767
|
+
const check = program.command("check").description(localize("Run the recommended local verification", "执行推荐的本地校验")).option("--full", localize("Run full verification", "执行完整校验")).option("--staged", localize("Run staged-file verification", "仅执行 staged 相关校验")).option("--affected", localize("Check changed packages and their consumers", "校验变更包及其消费者")).option("--base <ref>", localize("Affected comparison base (default: origin/main)", "affected 比较基线(默认 origin/main)")).option("--head <ref>", localize("Affected comparison head (default: HEAD)", "affected 比较终点(默认 HEAD)")).option("--filter <package>", localize("Intersect affected packages with exact names or directories; repeatable", "按精确包名或目录与 affected 集合取交集,可重复"), collect$1).option("--global-input <glob>", localize("Add a global input glob; repeatable", "追加全局输入 glob,可重复"), collect$1).option("--matrix", localize("Preview a GitHub Actions matrix as JSON; requires --affected", "以 JSON 预览 GitHub Actions matrix,需配合 --affected")).option("--shards <count>", localize("Group matrix packages into at most 1–256 jobs", "把 matrix 工作区分为最多 1–256 个 job")).option("--edit-file <file>", localize("Validate a commit message file", "执行 commit message 校验")).option("--dry-run", localize("Preview checks without running them", "预览将要执行的校验,不实际运行")).option("--json", localize("Output the check plan as JSON; implies --dry-run", "以 JSON 输出校验计划,隐含 --dry-run")).option("--markdown", localize("Output the check plan as Markdown; implies --dry-run", "以 Markdown 输出校验计划,隐含 --dry-run")).option("--out <file>", localize("Write the check plan to a file; implies --dry-run", "把校验计划写入文件,隐含 --dry-run")).option("--redact", localize("Redact cwd and home paths", "脱敏 cwd/home 绝对路径后再输出")).option("--report <file>", localize("Run checks and write an execution report to a separate file", "执行检查并把实际结果写入独立报告文件")).option("--report-format <format>", localize("Execution report format: json or markdown", "执行报告格式:json / markdown")).action(async (opts) => {
|
|
1768
|
+
if (opts.affected && (opts.full || opts.staged || opts.editFile)) throw new Error("--affected cannot be combined with --full, --staged or --edit-file");
|
|
1769
|
+
if (!opts.affected && (opts.base || opts.head || opts.filter || opts.globalInput)) throw new Error("--base, --head, --filter and --global-input require --affected");
|
|
1770
|
+
if (opts.matrix && !opts.affected) throw new Error("--matrix requires --affected");
|
|
1771
|
+
if (opts.shards !== void 0 && !opts.matrix) throw new Error("--shards requires --matrix");
|
|
1772
|
+
if (opts.matrix && (opts.markdown || opts.report || opts.reportFormat)) throw new Error("--matrix cannot be combined with --markdown, --report or --report-format");
|
|
1773
|
+
const options = {
|
|
1774
|
+
cwd,
|
|
1775
|
+
...opts.full !== void 0 ? { full: opts.full } : {},
|
|
1776
|
+
...opts.staged !== void 0 ? { staged: opts.staged } : {},
|
|
1777
|
+
...opts.editFile !== void 0 ? { editFile: opts.editFile } : {},
|
|
1778
|
+
...opts.affected ? { affected: true } : {},
|
|
1779
|
+
...opts.base !== void 0 ? { base: opts.base } : {},
|
|
1780
|
+
...opts.head !== void 0 ? { head: opts.head } : {},
|
|
1781
|
+
...opts.filter ? { filters: opts.filter } : {},
|
|
1782
|
+
...opts.globalInput ? { globalInputs: opts.globalInput } : {}
|
|
1783
|
+
};
|
|
1784
|
+
if (opts.matrix) {
|
|
1785
|
+
const { resolveAffectedCheckMatrix } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1786
|
+
const matrix = await resolveAffectedCheckMatrix({
|
|
1787
|
+
...options,
|
|
1788
|
+
...opts.shards !== void 0 ? { shards: Number(opts.shards) } : {}
|
|
1789
|
+
});
|
|
1790
|
+
const output = opts.redact ? redactCheckOutput(matrix, matrix.affectedPlan.cwd) : matrix;
|
|
1791
|
+
await emitCheckOutput(JSON.stringify(output, null, 2), opts, cwd, true);
|
|
1792
|
+
return;
|
|
1793
|
+
}
|
|
1794
|
+
if (opts.reportFormat && !opts.report) throw new Error("--report-format requires --report <file>");
|
|
1795
|
+
if (opts.report) {
|
|
1796
|
+
if (opts.dryRun || opts.json || opts.markdown || opts.out) throw new Error("--report cannot be combined with preview options: --dry-run, --json, --markdown, --out");
|
|
1797
|
+
const format = opts.reportFormat ?? "json";
|
|
1798
|
+
if (format !== "json" && format !== "markdown") throw new Error("--report-format must be json or markdown");
|
|
1799
|
+
const { runCheckExecution } = await import("./execute-D2GlX018.mjs");
|
|
1800
|
+
await runCheckExecution(options, opts.report, format, opts.redact);
|
|
1801
|
+
return;
|
|
1802
|
+
}
|
|
1803
|
+
const { resolveRecommendedCheckPlan, runRecommendedCheck } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1804
|
+
if (opts.dryRun || opts.json || opts.markdown || opts.out) {
|
|
1805
|
+
if (opts.affected) {
|
|
1806
|
+
const { resolveAffectedCheckPlan } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1807
|
+
await emitCheckPlan(await resolveAffectedCheckPlan(options), opts, cwd);
|
|
1808
|
+
return;
|
|
1809
|
+
}
|
|
1810
|
+
if (opts.full) {
|
|
1811
|
+
const { resolveFullWorkspaceCheckPlan } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1812
|
+
await emitCheckPlan(await resolveFullWorkspaceCheckPlan(cwd), opts, cwd);
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1815
|
+
await emitCheckPlan(resolveRecommendedCheckPlan(options), opts, cwd);
|
|
1816
|
+
return;
|
|
1817
|
+
}
|
|
1818
|
+
if (opts.affected) {
|
|
1819
|
+
const { runCheckExecution } = await import("./execute-D2GlX018.mjs");
|
|
1820
|
+
await runCheckExecution(options);
|
|
1821
|
+
return;
|
|
1822
|
+
}
|
|
1823
|
+
await runRecommendedCheck(options);
|
|
1824
|
+
logger.success(localize("Checks finished.", "检查完成。"));
|
|
1825
|
+
});
|
|
1826
|
+
registerCacheAnalysis(check, cwd);
|
|
1827
|
+
registerKnipCheck(check, cwd);
|
|
1828
|
+
}
|
|
1829
|
+
//#endregion
|
|
861
1830
|
//#region src/cli/commands/doctor/output.ts
|
|
862
1831
|
function formatDoctorStatus(status) {
|
|
863
1832
|
if (status === "pass") return pc.green("PASS");
|
|
@@ -874,8 +1843,10 @@ function formatDoctorReport(report, color = false) {
|
|
|
874
1843
|
for (const check of report.checks) {
|
|
875
1844
|
lines.push(`[${status(check.status)}] ${check.title}`);
|
|
876
1845
|
lines.push(` ${check.detail}`);
|
|
1846
|
+
if (check.suppression) lines.push(` suppression: ${check.suppression.state}; reason: ${check.suppression.reason}; expires: ${check.suppression.expires ?? "never"}`);
|
|
877
1847
|
if (check.fix) lines.push(localize(` fix: ${check.fix}`, ` 修复:${check.fix}`));
|
|
878
1848
|
}
|
|
1849
|
+
for (const item of report.suppressions ?? []) lines.push(`suppression ${item.id}: ${item.state}; matched: ${item.matched}; reason: ${item.reason}; expires: ${item.expires ?? "never"}`);
|
|
879
1850
|
lines.push("");
|
|
880
1851
|
lines.push(color ? localize(`summary: ${pc.green(String(report.summary.pass))} pass, ${pc.yellow(String(report.summary.warn))} warn, ${pc.red(String(report.summary.fail))} fail`, `摘要:${pc.green(String(report.summary.pass))} 通过,${pc.yellow(String(report.summary.warn))} 警告,${pc.red(String(report.summary.fail))} 失败`) : localize(`summary: ${report.summary.pass} pass, ${report.summary.warn} warn, ${report.summary.fail} fail`, `摘要:${report.summary.pass} 通过,${report.summary.warn} 警告,${report.summary.fail} 失败`));
|
|
881
1852
|
return lines.join("\n");
|
|
@@ -904,7 +1875,13 @@ function formatDoctorMarkdown(report) {
|
|
|
904
1875
|
...warningsAndFailures.length > 0 ? [
|
|
905
1876
|
localize("## Findings", "## 问题"),
|
|
906
1877
|
"",
|
|
907
|
-
...warningsAndFailures.map((check) => localize(`- ${check.status}: ${check.title}${check.fix ? ` (fix: ${check.fix})` : ""}`, `- ${check.status}: ${check.title}${check.fix ? `(修复:${check.fix})` : ""}`)),
|
|
1878
|
+
...warningsAndFailures.map((check) => localize(`- ${check.status}: ${check.title}${check.fix ? ` (fix: ${check.fix})` : ""} — ${check.detail}`, `- ${check.status}: ${check.title}${check.fix ? `(修复:${check.fix})` : ""} — ${check.detail}`)),
|
|
1879
|
+
""
|
|
1880
|
+
] : [],
|
|
1881
|
+
...report.suppressions?.length ? [
|
|
1882
|
+
localize("## Suppressions", "## 抑制记录"),
|
|
1883
|
+
"",
|
|
1884
|
+
...report.suppressions.map((item) => `- ${item.id}: ${item.state}; matched: ${item.matched}; reason: ${item.reason}; expires: ${item.expires ?? "never"}`),
|
|
908
1885
|
""
|
|
909
1886
|
] : [],
|
|
910
1887
|
localize("## Checks", "## 检查项"),
|
|
@@ -941,74 +1918,82 @@ function hasDoctorBlockingIssues(report, opts) {
|
|
|
941
1918
|
return report.summary.fail > 0 || opts.strict === true && report.summary.warn > 0;
|
|
942
1919
|
}
|
|
943
1920
|
//#endregion
|
|
944
|
-
//#region src/cli/commands/
|
|
945
|
-
async function
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
1921
|
+
//#region src/cli/commands/doctor/security.ts
|
|
1922
|
+
async function readJson(filename) {
|
|
1923
|
+
try {
|
|
1924
|
+
return JSON.parse(await readFile(filename, "utf8"));
|
|
1925
|
+
} catch {
|
|
1926
|
+
throw new Error("Cannot read the installation policy JSON input; raw parser content is omitted.");
|
|
950
1927
|
}
|
|
951
|
-
const outFile = path.resolve(cwd, opts.out);
|
|
952
|
-
await fs.outputFile(outFile, `${content}\n`, "utf8");
|
|
953
|
-
logger.success(localize(`Wrote ${path.relative(cwd, outFile)}`, `已写入 ${path.relative(cwd, outFile)}`));
|
|
954
1928
|
}
|
|
955
|
-
|
|
956
|
-
|
|
1929
|
+
function registerInstallSecurityCommand(doctor, cwd) {
|
|
1930
|
+
doctor.command("security").description(localize("Inspect effective pnpm installation security settings without running scripts", "只读检查 pnpm 安装安全设置,不执行依赖脚本")).option("--json", localize("Output stable JSON", "输出稳定 JSON")).option("--strict", localize("Fail on policy warnings", "策略警告也返回失败")).option("--pnpm-version <version>", localize("Audit an exact pnpm version without activating it", "按精确 pnpm 版本检查,不激活该版本")).option("--expectations <file>", localize("Read reviewed organization expectations from JSON", "读取已审核的组织期望 JSON")).option("--preset <name>", localize("Preview the optional balanced preset as JSON", "以 JSON 预览可选 balanced 预设")).option("--apply <file>", localize("Apply a reviewed preset plan", "应用已审核的预设计划")).action(async (localOptions, command) => {
|
|
1931
|
+
const parentOptions = doctor.opts();
|
|
1932
|
+
if ([
|
|
1933
|
+
"rules",
|
|
1934
|
+
"listRules",
|
|
1935
|
+
"fix"
|
|
1936
|
+
].some((key) => parentOptions[key] !== void 0)) throw new Error("doctor security cannot be combined with parent doctor rule selection or fix operations.");
|
|
1937
|
+
const inherited = command.optsWithGlobals();
|
|
1938
|
+
if (inherited["markdown"] || inherited["out"] || inherited["redact"]) throw new Error("doctor security supports --json and --strict; parent report output options cannot be combined with this command.");
|
|
1939
|
+
const options = {
|
|
1940
|
+
...localOptions,
|
|
1941
|
+
json: localOptions.json ?? inherited["json"],
|
|
1942
|
+
strict: localOptions.strict ?? inherited["strict"],
|
|
1943
|
+
apply: localOptions.apply ?? inherited["apply"]
|
|
1944
|
+
};
|
|
1945
|
+
if (options.apply) {
|
|
1946
|
+
if (options.preset || options.pnpmVersion || options.expectations) throw new Error("Use --apply alone with a reviewed preset plan.");
|
|
1947
|
+
const result = await applyInstallSecurityPreset(cwd, await readJson(options.apply));
|
|
1948
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1949
|
+
return;
|
|
1950
|
+
}
|
|
1951
|
+
const input = {
|
|
1952
|
+
...options.pnpmVersion ? { pnpmVersion: options.pnpmVersion } : {},
|
|
1953
|
+
...options.expectations ? { expectations: await readJson(options.expectations) } : {}
|
|
1954
|
+
};
|
|
1955
|
+
if (options.preset) {
|
|
1956
|
+
if (options.preset !== "balanced") throw new Error("Unknown installation security preset. Available preset: balanced.");
|
|
1957
|
+
process.stdout.write(`${JSON.stringify(await planInstallSecurityPreset(cwd, input), null, 2)}\n`);
|
|
1958
|
+
return;
|
|
1959
|
+
}
|
|
1960
|
+
const report = await inspectInstallSecurity(cwd, input);
|
|
1961
|
+
if (options.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
1962
|
+
else {
|
|
1963
|
+
for (const check of report.checks) process.stdout.write(`[${check.status}] ${check.id}: ${check.detail}\n`);
|
|
1964
|
+
for (const setting of report.settings.filter((item) => item.configured)) process.stdout.write(`${setting.key} (${setting.source}, ${setting.state}): ${JSON.stringify(setting.value)}\n`);
|
|
1965
|
+
for (const decision of report.builds.decisions) process.stdout.write(`[${decision.decision}] ${decision.package} (${decision.selector}; ${decision.source})\n`);
|
|
1966
|
+
}
|
|
1967
|
+
if (report.summary.fail || options.strict && report.summary.warn) process.exitCode = 1;
|
|
1968
|
+
});
|
|
1969
|
+
}
|
|
1970
|
+
//#endregion
|
|
1971
|
+
//#region src/cli/commands/doctor/index.ts
|
|
1972
|
+
async function emitDoctorReport(report, opts, cwd) {
|
|
1973
|
+
const content = opts.json || opts.markdown || opts.out ? createDoctorReportOutput(report, opts) : createInteractiveDoctorReportOutput(report, opts);
|
|
957
1974
|
if (!opts.out) {
|
|
958
|
-
|
|
1975
|
+
if (opts.json || opts.markdown) process.stdout.write(`${content}\n`);
|
|
1976
|
+
else logger.log(content);
|
|
959
1977
|
return;
|
|
960
1978
|
}
|
|
961
1979
|
const outFile = path.resolve(cwd, opts.out);
|
|
962
|
-
await fs.outputFile(outFile, `${content}\n`, "utf8");
|
|
1980
|
+
await fs$1.outputFile(outFile, `${content}\n`, "utf8");
|
|
963
1981
|
logger.success(localize(`Wrote ${path.relative(cwd, outFile)}`, `已写入 ${path.relative(cwd, outFile)}`));
|
|
964
1982
|
}
|
|
965
|
-
function
|
|
966
|
-
program.command("
|
|
967
|
-
const
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
});
|
|
977
|
-
program.command("new").description(localize("Create a new package or application", "创建新的 package / app")).argument("[name]").option("-t, --template <template>", localize("Use a template key without prompting", "直接使用指定模板,跳过模板选择")).option("--dry-run", localize("Preview directories and package metadata without writing", "预览将要创建的目录与 package 信息,不写入文件")).option("--json", localize("Output the creation preview as JSON; implies --dry-run", "以 JSON 输出创建预览,隐含 --dry-run")).option("--out <file>", localize("Write the creation preview to a file; implies --dry-run", "把创建预览写入文件,隐含 --dry-run")).action(async (inputName, opts) => {
|
|
978
|
-
const { runCreateFlow } = await import("./create-flow-CXRhfGbb.mjs");
|
|
979
|
-
const result = await runCreateFlow(cwd, inputName, {
|
|
980
|
-
...opts.template !== void 0 ? { template: opts.template } : {},
|
|
981
|
-
...opts.dryRun || opts.json || opts.out ? { dryRun: true } : {},
|
|
982
|
-
...opts.json ? { json: true } : {},
|
|
983
|
-
...opts.out !== void 0 ? { out: opts.out } : {}
|
|
984
|
-
});
|
|
985
|
-
if (result.dryRun || result.failed) return;
|
|
986
|
-
logger.success(localize("Package creation finished.", "包创建完成。"));
|
|
987
|
-
logger.info(localize("Next: run `pnpm install` and start the new workspace package.", "下一步:运行 `pnpm install`,然后启动新 workspace 包。"));
|
|
988
|
-
});
|
|
989
|
-
program.command("check").description(localize("Run the recommended local verification", "执行推荐的本地校验")).option("--full", localize("Run full verification", "执行完整校验")).option("--staged", localize("Run staged-file verification", "仅执行 staged 相关校验")).option("--edit-file <file>", localize("Validate a commit message file", "执行 commit message 校验")).option("--dry-run", localize("Preview checks without running them", "预览将要执行的校验,不实际运行")).option("--json", localize("Output the check plan as JSON; implies --dry-run", "以 JSON 输出校验计划,隐含 --dry-run")).option("--markdown", localize("Output the check plan as Markdown; implies --dry-run", "以 Markdown 输出校验计划,隐含 --dry-run")).option("--out <file>", localize("Write the check plan to a file; implies --dry-run", "把校验计划写入文件,隐含 --dry-run")).option("--redact", localize("Redact cwd and home paths", "脱敏 cwd/home 绝对路径后再输出")).action(async (opts) => {
|
|
990
|
-
const options = {
|
|
991
|
-
cwd,
|
|
992
|
-
...opts.full !== void 0 ? { full: opts.full } : {},
|
|
993
|
-
...opts.staged !== void 0 ? { staged: opts.staged } : {},
|
|
994
|
-
...opts.editFile !== void 0 ? { editFile: opts.editFile } : {}
|
|
995
|
-
};
|
|
996
|
-
const { resolveRecommendedCheckPlan, runRecommendedCheck } = await import("./commands-D4xZQ5t-.mjs").then((n) => n.t);
|
|
997
|
-
if (opts.dryRun || opts.json || opts.markdown || opts.out) {
|
|
998
|
-
if (opts.full) {
|
|
999
|
-
const { resolveFullWorkspaceCheckPlan } = await import("./commands-D4xZQ5t-.mjs").then((n) => n.t);
|
|
1000
|
-
await emitCheckPlan(await resolveFullWorkspaceCheckPlan(cwd), opts, cwd);
|
|
1001
|
-
return;
|
|
1002
|
-
}
|
|
1003
|
-
await emitCheckPlan(resolveRecommendedCheckPlan(options), opts, cwd);
|
|
1983
|
+
function registerDoctorCommand(program, cwd) {
|
|
1984
|
+
registerInstallSecurityCommand(program.command("doctor").description(localize("Diagnose whether the current repository is ready to use", "诊断当前仓库是否适合直接开始使用")).option("--json", localize("Output JSON for CI or scripts", "输出 JSON 报告,方便 CI 或脚本消费")).option("--markdown", localize("Output Markdown for an issue or pull request", "输出 Markdown 报告,方便粘贴到 issue 或 PR")).option("--out <file>", localize("Write the diagnostic report to a file", "把诊断报告写入文件")).option("--redact", localize("Redact workspace, cwd, and home paths", "脱敏 workspace/cwd/home 绝对路径后再输出")).option("--strict", localize("Treat warnings as failures", "把 warning 也视为失败,适合 CI 门禁")).option("--rules <ids>", localize("Select exact check IDs, separated by commas", "选择精确检查 ID,以逗号分隔")).option("--list-rules", localize("List all available check IDs", "列出全部可用检查 ID")).option("--fix", localize("Preview safe fixes without writing", "预览安全修复,不写入文件")).option("--apply <plan>", localize("Apply a reviewed doctor fix JSON plan", "应用已审核的 doctor 修复 JSON 计划")).action(async (opts) => {
|
|
1985
|
+
const commands = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1986
|
+
if (opts.fix && opts.apply || opts.apply && opts.rules !== void 0 || opts.listRules && (opts.fix || opts.apply || opts.rules !== void 0)) throw new Error("Use one of --list-rules, --fix, or --apply; --apply cannot change the reviewed rule selection.");
|
|
1987
|
+
if (opts.listRules || opts.fix || opts.apply) {
|
|
1988
|
+
if (opts.markdown || opts.redact) throw new Error("--markdown and --redact apply to diagnostic reports, not rule lists or executable plans.");
|
|
1989
|
+
const result = opts.listRules ? commands.getDoctorRuleIds() : opts.apply ? await commands.applyDoctorFixPlan(cwd, await fs$1.readJson(path.resolve(cwd, opts.apply))) : await commands.planDoctorFix(cwd, opts.rules === void 0 ? {} : { rules: opts.rules.split(",") });
|
|
1990
|
+
const content = `${JSON.stringify(result, null, 2)}\n`;
|
|
1991
|
+
if (opts.out) await fs$1.outputFile(path.resolve(cwd, opts.out), content, "utf8");
|
|
1992
|
+
else process.stdout.write(content);
|
|
1993
|
+
if ("verification" in result && hasDoctorBlockingIssues(result.verification, opts)) process.exitCode = 1;
|
|
1004
1994
|
return;
|
|
1005
1995
|
}
|
|
1006
|
-
await
|
|
1007
|
-
logger.success(localize("Checks finished.", "检查完成。"));
|
|
1008
|
-
});
|
|
1009
|
-
program.command("doctor").description(localize("Diagnose whether the current repository is ready to use", "诊断当前仓库是否适合直接开始使用")).option("--json", localize("Output JSON for CI or scripts", "输出 JSON 报告,方便 CI 或脚本消费")).option("--markdown", localize("Output Markdown for an issue or pull request", "输出 Markdown 报告,方便粘贴到 issue 或 PR")).option("--out <file>", localize("Write the diagnostic report to a file", "把诊断报告写入文件")).option("--redact", localize("Redact workspace, cwd, and home paths", "脱敏 workspace/cwd/home 绝对路径后再输出")).option("--strict", localize("Treat warnings as failures", "把 warning 也视为失败,适合 CI 门禁")).action(async (opts) => {
|
|
1010
|
-
const { runDoctor } = await import("./commands-D4xZQ5t-.mjs").then((n) => n.t);
|
|
1011
|
-
const report = await runDoctor(cwd);
|
|
1996
|
+
const report = opts.rules === void 0 ? await commands.runDoctor(cwd) : await commands.runDoctor(cwd, { rules: opts.rules.split(",") });
|
|
1012
1997
|
await emitDoctorReport(report, opts, cwd);
|
|
1013
1998
|
if (opts.out || opts.json || opts.markdown) {
|
|
1014
1999
|
if (hasDoctorBlockingIssues(report, opts)) process.exitCode = 1;
|
|
@@ -1028,38 +2013,377 @@ function registerTopLevelCommands(program, cwd) {
|
|
|
1028
2013
|
logger.warn(localize(`Doctor found ${report.summary.warn} suggestion(s).`, `Doctor 提供了 ${report.summary.warn} 条建议。`));
|
|
1029
2014
|
}
|
|
1030
2015
|
logger.success(localize("Doctor finished.", "Doctor 诊断完成。"));
|
|
2016
|
+
}), cwd);
|
|
2017
|
+
}
|
|
2018
|
+
//#endregion
|
|
2019
|
+
//#region src/cli/commands/upgrade.ts
|
|
2020
|
+
function registerUpgradeCommand(parent, cwd, alias) {
|
|
2021
|
+
const command = parent.command("upgrade").description(localize("Plan or apply standard repository asset upgrades", "预览或应用仓库标准资产升级")).option("-i,--interactive", localize("Select managed files interactively", "交互式选择受管文件")).option("-c,--core", localize("Synchronize core configuration without GitHub assets", "仅同步核心配置,跳过 GitHub 相关资产")).option("--outDir <dir>", localize("Output directory", "输出目录")).option("-s,--skip-overwrite", localize("Preserve existing files", "保留已存在文件")).option("-y, --yes", localize("Approve changed managed assets", "接受受管资产变更")).option("--overwrite", localize("Explicitly replace differing managed assets and adopt upstream baselines", "显式替换有差异的受管资产并登记上游基线")).option("--no-overwrite", localize("Preserve existing assets and legacy metadata", "保留既有资产和旧版迁移元数据")).option("--overwrite-release", localize("Replace a custom release workflow", "替换自定义 release workflow")).option("--dry-run", localize("Preview every change without writes or asset preparation", "预览全部变更,不写文件或准备资产")).option("--from-version <version>", localize("Attest an exact previous template version for migration selection", "提供明确的旧模板版本,用于选择版本迁移")).option("--json", localize("Output a read-only JSON plan", "输出只读 JSON 计划")).option("--markdown", localize("Output a read-only Markdown plan with diffs", "输出含 diff 的只读 Markdown 计划")).option("--apply <file>", localize("Apply all actionable entries from a reviewed JSON plan", "应用已审核 JSON 计划中的全部变更")).action(async (options) => {
|
|
2022
|
+
if (options.apply) {
|
|
2023
|
+
if (options.dryRun) throw new Error(localize("--apply and --dry-run cannot be combined.", "--apply 和 --dry-run 不能同时使用。"));
|
|
2024
|
+
const plan = JSON.parse(await readFile(options.apply, "utf8"));
|
|
2025
|
+
const result = await applyUpgradePlan(cwd, plan);
|
|
2026
|
+
process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : `${result.status}: ${result.changed.join(", ")}`}\n`);
|
|
2027
|
+
if (result.conflicts?.length) {
|
|
2028
|
+
if (!options.json) process.stdout.write(`conflicts: ${result.conflicts.join(", ")}\n`);
|
|
2029
|
+
process.exitCode = 1;
|
|
2030
|
+
}
|
|
2031
|
+
return;
|
|
2032
|
+
}
|
|
2033
|
+
const normalized = {
|
|
2034
|
+
...options,
|
|
2035
|
+
cwd,
|
|
2036
|
+
...options.overwrite === false ? { noOverwrite: true } : {}
|
|
2037
|
+
};
|
|
2038
|
+
if (options.dryRun || options.json || options.markdown) {
|
|
2039
|
+
const plan = await planUpgrade(normalized);
|
|
2040
|
+
process.stdout.write(`${options.json ? JSON.stringify(plan, null, 2) : formatUpgradePlan(plan, options.markdown ? "markdown" : "text")}\n`);
|
|
2041
|
+
if (plan.status === "blocked" || plan.files.some((file) => file.status === "conflict")) process.exitCode = 1;
|
|
2042
|
+
return;
|
|
2043
|
+
}
|
|
2044
|
+
await upgradeMonorepo(normalized);
|
|
2045
|
+
logger.success(alias ? localize("Workspace upgrade finished.", "Workspace 升级完成。") : localize("Upgrade finished.", "升级完成。"));
|
|
1031
2046
|
});
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
2047
|
+
if (alias) command.alias(alias);
|
|
2048
|
+
return command;
|
|
2049
|
+
}
|
|
2050
|
+
//#endregion
|
|
2051
|
+
//#region src/cli/commands/top-level.ts
|
|
2052
|
+
function registerTopLevelCommands(program, cwd) {
|
|
2053
|
+
program.command("init").description(localize("Initialize the current workspace with recommended configuration", "初始化当前 workspace,并生成推荐配置")).option("--preset <preset>", localize("Initialization preset: minimal or standard", "初始化预设:minimal / standard")).option("-f, --force", localize("Overwrite existing tooling configuration files", "覆盖已存在的 tooling 配置文件")).option("--overwrite", localize("Overwrite existing managed files", "覆盖受管的已存在文件")).option("-y, --yes", localize("Use defaults without prompting; suitable for CI", "使用默认值跳过所有交互,适合 CI")).action(async (opts) => {
|
|
2054
|
+
const { init } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
2055
|
+
const config = await loadMonorepoConfig(cwd);
|
|
2056
|
+
const { preset } = resolveCommandValues("init", config.commands?.init, { preset: opts.preset }, { entry: "cli" }).values;
|
|
2057
|
+
await init(cwd, {
|
|
2058
|
+
...preset !== void 0 ? { preset } : {},
|
|
2059
|
+
...opts.force !== void 0 ? { force: opts.force } : {},
|
|
2060
|
+
...opts.overwrite !== void 0 ? { overwrite: opts.overwrite } : {},
|
|
2061
|
+
...opts.yes !== void 0 ? { yes: opts.yes } : {}
|
|
2062
|
+
});
|
|
2063
|
+
logger.success(localize("Initialization finished.", "初始化完成。"));
|
|
2064
|
+
logger.info(localize("Next: run `pnpm install` and `pnpm build`.", "下一步:运行 `pnpm install` 和 `pnpm build`。"));
|
|
2065
|
+
});
|
|
2066
|
+
program.command("new").description(localize("Create a new package or application", "创建新的 package / app")).argument("[name]").option("--offline", localize("Use only verified cached remote assets", "只使用通过校验的远程资产缓存")).option("--data <file>", localize("Read typed template parameters from a JSON file", "从 JSON 文件读取类型化模板参数")).option("--cache-dir <directory>", localize("Template asset cache directory", "模板资产缓存目录")).option("-t, --template <template>", localize("Use a template key without prompting", "直接使用指定模板,跳过模板选择")).option("--dry-run", localize("Preview directories and package metadata without writing", "预览将要创建的目录与 package 信息,不写入文件")).option("--json", localize("Output the creation preview as JSON; implies --dry-run", "以 JSON 输出创建预览,隐含 --dry-run")).option("--out <file>", localize("Write the creation preview to a file; implies --dry-run", "把创建预览写入文件,隐含 --dry-run")).action(async (inputName, opts) => {
|
|
2067
|
+
const { runCreateFlow } = await import("./create-flow-BWFWDWR4.mjs");
|
|
2068
|
+
const result = await runCreateFlow(cwd, inputName, {
|
|
2069
|
+
...opts.offline !== void 0 ? { offline: opts.offline } : {},
|
|
2070
|
+
...opts.cacheDir ? { cacheDir: opts.cacheDir } : {},
|
|
2071
|
+
...opts.data ? { data: opts.data } : {},
|
|
2072
|
+
...opts.template !== void 0 ? { template: opts.template } : {},
|
|
2073
|
+
...opts.dryRun || opts.json || opts.out ? { dryRun: true } : {},
|
|
2074
|
+
...opts.json ? { json: true } : {},
|
|
2075
|
+
...opts.out !== void 0 ? { out: opts.out } : {}
|
|
2076
|
+
});
|
|
2077
|
+
if (result.dryRun || result.failed) return;
|
|
2078
|
+
logger.success(localize("Package creation finished.", "包创建完成。"));
|
|
2079
|
+
logger.info(localize("Next: run `pnpm install` and start the new workspace package.", "下一步:运行 `pnpm install`,然后启动新 workspace 包。"));
|
|
1036
2080
|
});
|
|
2081
|
+
registerCheckCommand(program, cwd);
|
|
2082
|
+
registerDoctorCommand(program, cwd);
|
|
2083
|
+
registerUpgradeCommand(program, cwd);
|
|
1037
2084
|
}
|
|
1038
2085
|
//#endregion
|
|
1039
2086
|
//#region src/cli/commands/verify.ts
|
|
1040
2087
|
function registerVerifyCommands(program, cwd) {
|
|
1041
2088
|
const verifyCommand = program.command("verify").alias("v").description(localize("Local verification commands", "本地校验工具集"));
|
|
1042
2089
|
verifyCommand.command("pre-push").description(localize("Run build, test, and tsd checks for pushed changes", "按推送变更范围执行 build/test/tsd 校验")).alias("push").action(async () => {
|
|
1043
|
-
const { verifyPrePush } = await import("./commands-
|
|
2090
|
+
const { verifyPrePush } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1044
2091
|
await verifyPrePush({ cwd });
|
|
1045
2092
|
});
|
|
1046
2093
|
verifyCommand.command("pre-commit").description(localize("Run lint-staged verification", "执行 lint-staged 校验")).alias("commit").action(async () => {
|
|
1047
|
-
const { verifyPreCommit } = await import("./commands-
|
|
2094
|
+
const { verifyPreCommit } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1048
2095
|
await verifyPreCommit({ cwd });
|
|
1049
2096
|
});
|
|
1050
2097
|
verifyCommand.command("commit-msg").description(localize("Run commitlint verification", "执行 commitlint 校验")).alias("msg").argument("<edit-file>").action(async (editFile) => {
|
|
1051
|
-
const { verifyCommitMsg } = await import("./commands-
|
|
2098
|
+
const { verifyCommitMsg } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1052
2099
|
await verifyCommitMsg({
|
|
1053
2100
|
cwd,
|
|
1054
2101
|
editFile
|
|
1055
2102
|
});
|
|
1056
2103
|
});
|
|
1057
2104
|
verifyCommand.command("staged-typecheck").description(localize("Run typecheck in workspaces containing staged files", "按暂存文件所在 workspace 执行 typecheck")).alias("tc").argument("[files...]").action(async (files = []) => {
|
|
1058
|
-
const { verifyStagedTypecheck } = await import("./commands-
|
|
2105
|
+
const { verifyStagedTypecheck } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1059
2106
|
verifyStagedTypecheck(files, { cwd });
|
|
1060
2107
|
});
|
|
1061
2108
|
}
|
|
1062
2109
|
//#endregion
|
|
2110
|
+
//#region src/cli/commands/workspace/boundaries.ts
|
|
2111
|
+
function registerWorkspaceBoundaries(workspaceCommand, cwd) {
|
|
2112
|
+
workspaceCommand.command("boundaries").description(localize("Check internal dependency cycles and architecture rules", "检查内部依赖循环与架构规则")).option("--json", localize("Output stable JSON", "输出稳定 JSON")).option("--strict", localize("Fail on warnings as well as errors", "警告和错误均返回失败")).action(async (options) => {
|
|
2113
|
+
const report = await checkWorkspaceBoundaries(cwd);
|
|
2114
|
+
const lines = report.findings.map((finding) => `[${finding.status}] ${finding.id}${finding.rule ? ` (${finding.rule})` : ""}: ${finding.detail}`);
|
|
2115
|
+
for (const exception of report.exceptions) lines.push(`[waived] ${exception.rule}: ${exception.source} -> ${exception.target} (${exception.type}): ${exception.reason}`);
|
|
2116
|
+
lines.push(`${report.summary.fail} fail, ${report.summary.warn} warn, ${report.summary.waived} waived`);
|
|
2117
|
+
process.stdout.write(`${options.json ? JSON.stringify(report, null, 2) : lines.join("\n")}\n`);
|
|
2118
|
+
if (report.summary.fail || options.strict && report.summary.warn) process.exitCode = 1;
|
|
2119
|
+
});
|
|
2120
|
+
}
|
|
2121
|
+
//#endregion
|
|
2122
|
+
//#region src/cli/commands/workspace/format.ts
|
|
2123
|
+
function redactWorkspaceGraph(graph) {
|
|
2124
|
+
let serialized = JSON.stringify(graph);
|
|
2125
|
+
const replacements = [
|
|
2126
|
+
[graph.workspaceDir, "<workspace>"],
|
|
2127
|
+
[graph.cwd, "<cwd>"],
|
|
2128
|
+
[os.homedir(), "<home>"]
|
|
2129
|
+
];
|
|
2130
|
+
for (const [value, replacement] of replacements.sort(([a], [b]) => b.length - a.length)) if (value) serialized = serialized.split(JSON.stringify(value).slice(1, -1)).join(replacement);
|
|
2131
|
+
return JSON.parse(serialized);
|
|
2132
|
+
}
|
|
2133
|
+
function formatGraphDiagnostics(diagnostics) {
|
|
2134
|
+
return diagnostics.map((item) => `! ${item.code}: ${item.source ?? "."} ${item.dependency}${item.specifier ? ` (${item.specifier})` : ""}${item.candidates.length ? ` -> ${item.candidates.join(", ")}` : ""}`);
|
|
2135
|
+
}
|
|
2136
|
+
function formatWorkspaceGraph(graph) {
|
|
2137
|
+
return [
|
|
2138
|
+
localize(`workspace: ${graph.workspaceDir}`, `工作区:${graph.workspaceDir}`),
|
|
2139
|
+
localize(`packages: ${graph.nodes.length}; dependencies: ${graph.edges.length}`, `包数量:${graph.nodes.length};依赖边:${graph.edges.length}`),
|
|
2140
|
+
...graph.nodes.map((node) => `- ${node.id} (${node.name ?? localize("unnamed", "未命名")})${node.private ? " [private]" : ""}`),
|
|
2141
|
+
...graph.edges.map((edge) => ` ${edge.source} -> ${edge.target} [${edge.type}] ${edge.dependency}: ${edge.specifier}`),
|
|
2142
|
+
...formatGraphDiagnostics(graph.diagnostics)
|
|
2143
|
+
].join("\n");
|
|
2144
|
+
}
|
|
2145
|
+
function mermaidLabel(value) {
|
|
2146
|
+
return value.replaceAll("&", "&").replaceAll("\"", "#quot;").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\n", "<br/>").replaceAll("\r", "");
|
|
2147
|
+
}
|
|
2148
|
+
function formatWorkspaceGraphMermaid(graph) {
|
|
2149
|
+
const ids = new Map(graph.nodes.map((node, index) => [node.id, `n${index}`]));
|
|
2150
|
+
return [
|
|
2151
|
+
"flowchart LR",
|
|
2152
|
+
...graph.nodes.map((node) => ` ${ids.get(node.id)}["${mermaidLabel(`${node.name ?? node.id} (${node.id})`)}"]`),
|
|
2153
|
+
...graph.edges.map((edge) => ` ${ids.get(edge.source)} -->|"${mermaidLabel(`${edge.type}: ${edge.dependency}`)}"| ${ids.get(edge.target)}`),
|
|
2154
|
+
...formatGraphDiagnostics(graph.diagnostics).map((line) => ` %% ${line.replaceAll("\n", " ").replaceAll("\r", " ")}`)
|
|
2155
|
+
].join("\n");
|
|
2156
|
+
}
|
|
2157
|
+
function formatWorkspaceWhy(result) {
|
|
2158
|
+
return [
|
|
2159
|
+
result.found ? localize(`Shortest dependency path: ${result.path.join(" -> ")}`, `最短依赖路径:${result.path.join(" -> ")}`) : localize(`No dependency path: ${result.from} -> ${result.to}`, `没有依赖路径:${result.from} -> ${result.to}`),
|
|
2160
|
+
...result.edges.map((edge) => ` ${edge.source} -> ${edge.target} [${edge.type}] ${edge.dependency}: ${edge.specifier}`),
|
|
2161
|
+
...formatGraphDiagnostics(result.diagnostics)
|
|
2162
|
+
].join("\n");
|
|
2163
|
+
}
|
|
2164
|
+
function formatWorkspaceImpact(result) {
|
|
2165
|
+
return [
|
|
2166
|
+
localize(`Consumers of ${result.target}: ${result.consumers.length}`, `${result.target} 的消费者:${result.consumers.length}`),
|
|
2167
|
+
...result.consumers.map((consumer) => `- ${consumer.id} [${consumer.direct ? "direct" : "transitive"}; ${consumer.distance}] ${consumer.path.join(" -> ")}`),
|
|
2168
|
+
...formatGraphDiagnostics(result.diagnostics)
|
|
2169
|
+
].join("\n");
|
|
2170
|
+
}
|
|
2171
|
+
//#endregion
|
|
2172
|
+
//#region src/cli/commands/workspace/graph.ts
|
|
2173
|
+
function collect(value, previous = []) {
|
|
2174
|
+
return [...previous, value];
|
|
2175
|
+
}
|
|
2176
|
+
function commonOptions(command) {
|
|
2177
|
+
return command.option("--json", localize("Output stable JSON", "输出稳定 JSON")).option("--include-root", localize("Include the workspace root package", "包含 workspace 根包")).option("--exclude-private", localize("Exclude private packages (included by default)", "排除 private 包(默认包含)")).option("--type <type>", localize("Dependency field; repeatable: dependencies, devDependencies, peerDependencies, optionalDependencies", "依赖字段,可重复:dependencies、devDependencies、peerDependencies、optionalDependencies"), collect);
|
|
2178
|
+
}
|
|
2179
|
+
async function loadGraph(cwd, options) {
|
|
2180
|
+
return getWorkspaceGraph(cwd, {
|
|
2181
|
+
ignoreRootPackage: !options.includeRoot,
|
|
2182
|
+
ignorePrivatePackage: options.excludePrivate ?? false,
|
|
2183
|
+
...options.type ? { dependencyTypes: options.type } : {},
|
|
2184
|
+
...options.package ? { packages: options.package } : {}
|
|
2185
|
+
});
|
|
2186
|
+
}
|
|
2187
|
+
function registerWorkspaceGraphCommands(workspaceCommand, cwd) {
|
|
2188
|
+
commonOptions(workspaceCommand.command("graph").description(localize("Inspect internal manifest dependencies", "检查清单中的内部依赖关系"))).option("--package <selector>", localize("Show a package and its direct relationships; repeatable", "显示指定包及其直接关系,可重复"), collect).option("--mermaid", localize("Output a Mermaid graph", "输出 Mermaid 依赖图")).option("--redact", localize("Redact absolute workspace paths", "脱敏 workspace 绝对路径")).action(async (options) => {
|
|
2189
|
+
if (options.json && options.mermaid) throw new Error("--json and --mermaid cannot be combined");
|
|
2190
|
+
const graph = await loadGraph(cwd, options);
|
|
2191
|
+
const output = options.redact ? redactWorkspaceGraph(graph) : graph;
|
|
2192
|
+
process.stdout.write(`${options.json ? JSON.stringify(output, null, 2) : options.mermaid ? formatWorkspaceGraphMermaid(output) : formatWorkspaceGraph(output)}\n`);
|
|
2193
|
+
});
|
|
2194
|
+
commonOptions(workspaceCommand.command("why <from> <to>").description(localize("Explain one shortest dependency path from a consumer to a package", "解释从消费者到目标包的一条最短依赖路径"))).action(async (from, to, options) => {
|
|
2195
|
+
const result = whyWorkspaceDependency(await loadGraph(cwd, options), from, to);
|
|
2196
|
+
process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : formatWorkspaceWhy(result)}\n`);
|
|
2197
|
+
});
|
|
2198
|
+
commonOptions(workspaceCommand.command("impact <package>").description(localize("List direct and transitive consumers of a package", "列出一个包的直接和传递消费者"))).option("--direct", localize("Only include direct consumers", "只包含直接消费者")).action(async (selector, options) => {
|
|
2199
|
+
const result = getWorkspaceImpact(await loadGraph(cwd, options), selector, { direct: options.direct ?? false });
|
|
2200
|
+
process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : formatWorkspaceImpact(result)}\n`);
|
|
2201
|
+
});
|
|
2202
|
+
}
|
|
2203
|
+
//#endregion
|
|
2204
|
+
//#region src/cli/commands/workspace/move.ts
|
|
2205
|
+
function formatPlan$1(plan) {
|
|
2206
|
+
return [
|
|
2207
|
+
localize(`Move preview: ${plan.target.id} → ${plan.destination.id}`, `移动预览:${plan.target.id} → ${plan.destination.id}`),
|
|
2208
|
+
`name: ${plan.target.name ?? "(unnamed)"} → ${plan.destination.name ?? "(unnamed)"}`,
|
|
2209
|
+
...plan.blockers.map((item) => `blocked: ${item.code}: ${item.paths.join(", ")}`),
|
|
2210
|
+
...plan.consumers.map((item) => `consumer: ${item.path.join(" → ")}`),
|
|
2211
|
+
...plan.files.flatMap((file) => file.fields.map((field) => `update: ${file.path}: ${field}`)),
|
|
2212
|
+
...plan.review.tasks.map((item) => `review: ${item.path}:${item.line}: ${item.reason}`),
|
|
2213
|
+
localize("Review covers Git-tracked text candidates only. Ignored/untracked, binary, large files and dynamic references are not analyzed.", "人工复核覆盖 Git 跟踪文本候选;不分析忽略/未跟踪文件、二进制、大文件或动态引用。"),
|
|
2214
|
+
localize("Save the JSON plan outside the selected package and apply it with workspace move --apply <plan.json>.", "将 JSON 计划保存到所选包之外,再运行 workspace move --apply <plan.json>。"),
|
|
2215
|
+
...plan.nextSteps
|
|
2216
|
+
].join("\n");
|
|
2217
|
+
}
|
|
2218
|
+
function registerWorkspaceMove(workspace, cwd) {
|
|
2219
|
+
workspace.command("move").alias("mv").description(localize("Preview a workspace directory move, package rename, or both", "预览工作区目录移动、包名修改或两者同时变更")).argument("[target]", localize("Exact package name or ./directory", "准确包名或 ./目录")).option("--to <directory>", localize("Workspace-relative destination directory", "相对工作区根的目标目录")).option("--name <package>", localize("New npm package name", "新 npm 包名")).option("--dry-run", localize("Preview only (the default)", "仅预览(默认)")).option("--apply <plan.json>", localize("Apply a reviewed saved plan", "应用已审查的计划")).option("--json", localize("Output JSON", "输出 JSON")).action(async (target, options, command) => {
|
|
2220
|
+
const inherited = command.optsWithGlobals();
|
|
2221
|
+
const json = options.json ?? inherited.json;
|
|
2222
|
+
if (options.apply && (target !== void 0 || options.to !== void 0 || options.name !== void 0 || options.dryRun || inherited.dryRun)) throw new Error("--apply cannot be combined with target, --to, --name or --dry-run.");
|
|
2223
|
+
if (options.apply) {
|
|
2224
|
+
const result = await applyWorkspaceMovePlan(cwd, JSON.parse(await readFile(path.resolve(cwd, options.apply), "utf8")));
|
|
2225
|
+
process.stdout.write(`${json ? JSON.stringify(result, null, 2) : [
|
|
2226
|
+
result.status,
|
|
2227
|
+
...result.changed,
|
|
2228
|
+
...result.cleanupPending.map((file) => `cleanup pending: ${file}`),
|
|
2229
|
+
...result.nextSteps
|
|
2230
|
+
].join("\n")}\n`);
|
|
2231
|
+
return;
|
|
2232
|
+
}
|
|
2233
|
+
if (!target) throw new Error("Select one workspace or provide --apply <plan.json>.");
|
|
2234
|
+
const plan = await planWorkspaceMove(cwd, {
|
|
2235
|
+
target,
|
|
2236
|
+
...options.to !== void 0 ? { to: options.to } : {},
|
|
2237
|
+
...options.name !== void 0 ? { name: options.name } : {}
|
|
2238
|
+
});
|
|
2239
|
+
process.stdout.write(`${json ? JSON.stringify(plan, null, 2) : formatPlan$1(plan)}\n`);
|
|
2240
|
+
if (!plan.canApply) process.exitCode = 1;
|
|
2241
|
+
});
|
|
2242
|
+
}
|
|
2243
|
+
//#endregion
|
|
2244
|
+
//#region src/cli/commands/workspace/owners.ts
|
|
2245
|
+
function registerWorkspaceOwnersCommand(command, cwd) {
|
|
2246
|
+
command.command("owners [workspace]").description(localize("Inspect workspace owners and preview CODEOWNERS changes", "查询包负责人并预览 CODEOWNERS 变更")).option("--file <file>", localize("Explicit CODEOWNERS path relative to the workspace root", "显式指定相对工作区根目录的 CODEOWNERS 路径")).option("--sync", localize("Apply the validated preview to the selected file", "把校验过的预览写入指定文件")).option("--dry-run", localize("Preview without writing, including with --sync", "只预览不写入,包括与 --sync 一起使用时")).option("--json", localize("Output JSON", "输出 JSON")).action(async (query, options) => {
|
|
2247
|
+
if (options.sync && !options.file) throw new Error("--sync requires an explicit --file.");
|
|
2248
|
+
if (query && options.file) throw new Error("CODEOWNERS synchronization covers all configured workspaces; omit the workspace query.");
|
|
2249
|
+
const plan = options.file ? await planCodeowners({
|
|
2250
|
+
cwd,
|
|
2251
|
+
file: options.file
|
|
2252
|
+
}) : void 0;
|
|
2253
|
+
const report = plan ?? await inspectWorkspaceOwners({
|
|
2254
|
+
cwd,
|
|
2255
|
+
...query ? { query } : {}
|
|
2256
|
+
});
|
|
2257
|
+
const result = options.sync && !options.dryRun && plan && !report.diagnostics.some((item) => item.severity === "error") ? await applyCodeownersPlan(plan) : void 0;
|
|
2258
|
+
if (options.json) process.stdout.write(`${JSON.stringify({
|
|
2259
|
+
...report,
|
|
2260
|
+
...result ? { result } : {}
|
|
2261
|
+
}, null, 2)}\n`);
|
|
2262
|
+
else {
|
|
2263
|
+
for (const pkg of report.packages) process.stdout.write(`${pkg.name ?? pkg.path} (${pkg.path}): ${pkg.owners.join(" ") || "(missing)"}\n ${pkg.sources.join(", ")}\n`);
|
|
2264
|
+
for (const diagnostic of report.diagnostics) process.stdout.write(`${diagnostic.severity} ${diagnostic.code} ${diagnostic.source}${diagnostic.line ? `:${diagnostic.line}` : ""}: ${diagnostic.message}\n`);
|
|
2265
|
+
if (plan?.diff) process.stdout.write(`${plan.diff}\n`);
|
|
2266
|
+
if (result) process.stdout.write(`${result.status} ${result.file}\n`);
|
|
2267
|
+
}
|
|
2268
|
+
if (report.diagnostics.some((item) => item.severity === "error") || query && !report.packages.length) process.exitCode = 1;
|
|
2269
|
+
});
|
|
2270
|
+
}
|
|
2271
|
+
//#endregion
|
|
2272
|
+
//#region src/cli/commands/workspace/prepare.ts
|
|
2273
|
+
function registerWorkspacePrepare(command, cwd) {
|
|
2274
|
+
command.command("prepare [target]").description(localize("Preview isolated Turbo prune or production pnpm deploy artifacts", "预览隔离的 Turbo prune 或生产 pnpm deploy 产物")).option("--mode <mode>", localize("prune for a build context; deploy for a production directory", "prune 生成构建上下文,deploy 生成生产目录")).option("--out <directory>", localize("Explicit empty output directory outside the workspace", "工作区外的显式空输出目录")).option("--entry <file>", localize("Built deploy entry relative to the package", "相对包目录的已构建部署入口")).option("--docker", localize("Split prune output into Docker layers", "将 prune 产物分成 Docker 缓存层")).option("--offline", localize("Deploy only from local package stores", "部署仅使用本地包存储")).option("--legacy", localize("Explicitly select native legacy deploy", "显式使用原生 legacy deploy")).option("--json", localize("Output the portable JSON plan", "输出可保存的 JSON 计划")).option("--dry-run", localize("Explicitly preview without creating artifacts (default)", "显式只读预览,不创建产物(默认)")).option("--apply <plan.json>", localize("Apply a reviewed saved plan", "应用已审查的保存计划")).action(async (target, options, current) => {
|
|
2275
|
+
const inherited = current.optsWithGlobals();
|
|
2276
|
+
if (options.apply) {
|
|
2277
|
+
if (target || options.mode || options.out || options.entry || options.docker || options.offline || options.legacy || inherited.dryRun) throw new Error("--apply cannot be combined with a target, preview selection or --dry-run.");
|
|
2278
|
+
const result = await applyWorkspaceArtifactPlan(cwd, JSON.parse(await readFile(path.resolve(cwd, options.apply), "utf8")));
|
|
2279
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
2280
|
+
return;
|
|
2281
|
+
}
|
|
2282
|
+
if (!target || !options.mode || !options.out) throw new Error("Preview requires one exact target, --mode prune|deploy and --out <directory>.");
|
|
2283
|
+
const plan = await planWorkspaceArtifact(cwd, {
|
|
2284
|
+
target,
|
|
2285
|
+
mode: options.mode,
|
|
2286
|
+
output: options.out,
|
|
2287
|
+
...options.entry ? { entry: options.entry } : {},
|
|
2288
|
+
...options.docker ? { docker: true } : {},
|
|
2289
|
+
...options.offline ? { offline: true } : {},
|
|
2290
|
+
...options.legacy ? { legacy: true } : {}
|
|
2291
|
+
});
|
|
2292
|
+
process.stdout.write(`${inherited.json ? JSON.stringify(plan, null, 2) : [
|
|
2293
|
+
`${plan.selection.mode}: ${plan.target.name}`,
|
|
2294
|
+
`output: ${plan.selection.output}`,
|
|
2295
|
+
`native: ${plan.tool.name}@${plan.tool.version}`,
|
|
2296
|
+
`command: ${[plan.command.executable, ...plan.command.args].map((value) => JSON.stringify(value)).join(" ")}`,
|
|
2297
|
+
`manifest candidates: ${plan.manifestCandidates.join(", ")}`,
|
|
2298
|
+
`excluded private inputs: ${plan.excluded.join(", ") || "none"}`,
|
|
2299
|
+
...plan.notes,
|
|
2300
|
+
"Preview only. Save --json outside the source workspace and review it before --apply."
|
|
2301
|
+
].join("\n")}\n`);
|
|
2302
|
+
});
|
|
2303
|
+
}
|
|
2304
|
+
//#endregion
|
|
2305
|
+
//#region src/cli/commands/workspace/remove.ts
|
|
2306
|
+
function formatPlan(plan) {
|
|
2307
|
+
return [
|
|
2308
|
+
localize(`Removal preview: ${plan.target.name ?? "(unnamed)"} (${plan.target.id})`, `移除预览:${plan.target.name ?? "(未命名)"}(${plan.target.id})`),
|
|
2309
|
+
localize(`Directory entries: ${plan.inventory.length}; manifest changes: ${plan.files.length}`, `目录条目:${plan.inventory.length};清单变更:${plan.files.length}`),
|
|
2310
|
+
...plan.blockers.map((item) => `blocked: ${item.code}: ${item.paths.join(", ")}`),
|
|
2311
|
+
...plan.consumers.map((item) => `consumer: ${item.path.join(" → ")}`),
|
|
2312
|
+
...plan.files.flatMap((file) => file.fields.map((field) => `remove: ${file.path}: ${field}`)),
|
|
2313
|
+
...plan.review.matches.map((item) => `review: ${item.path}: ${item.values.join(", ")}`),
|
|
2314
|
+
localize("Review scans only Git-tracked text using literal matches; ignored/untracked, binary, large files and dynamic references are not analyzed.", "人工复核仅扫描 Git 跟踪文本的字面量;不分析忽略/未跟踪文件、二进制、大文件或动态引用。"),
|
|
2315
|
+
localize("Save the JSON preview outside the selected package, review it, then use workspace remove --apply <plan.json>.", "将 JSON 预览保存到所选包之外,审查后运行 workspace remove --apply <plan.json>。"),
|
|
2316
|
+
...plan.nextSteps
|
|
2317
|
+
].join("\n");
|
|
2318
|
+
}
|
|
2319
|
+
function formatResult(result) {
|
|
2320
|
+
return [
|
|
2321
|
+
`${result.status}: ${result.removed.join(", ")}`,
|
|
2322
|
+
...result.changed.map((file) => `changed: ${file}`),
|
|
2323
|
+
...result.cleanupPending.map((file) => `cleanup pending: ${file}`),
|
|
2324
|
+
...result.nextSteps
|
|
2325
|
+
].join("\n");
|
|
2326
|
+
}
|
|
2327
|
+
function registerWorkspaceRemoval(workspace, cwd) {
|
|
2328
|
+
workspace.command("remove").description(localize("Preview safe removal of one workspace; apply a reviewed saved plan explicitly", "预览安全移除单个工作区;显式应用已审查的计划")).argument("[target]", localize("Exact package name or explicit ./directory", "准确包名或显式 ./目录")).option("--remove-references", localize("Plan removal of exact dependency fields in consumer manifests", "计划删除消费者清单中的准确依赖字段")).option("--dry-run", localize("Preview only (the default)", "仅预览(默认行为)")).option("--apply <plan.json>", localize("Apply a reviewed JSON plan", "应用已审查的 JSON 计划")).option("--json", localize("Output JSON", "输出 JSON")).action(async (target, options) => {
|
|
2329
|
+
if (options.apply && (target !== void 0 || options.removeReferences || options.dryRun)) throw new Error(localize("--apply cannot be combined with a target, --remove-references or --dry-run.", "--apply 不能与目标、--remove-references 或 --dry-run 同时使用。"));
|
|
2330
|
+
if (options.apply) {
|
|
2331
|
+
const plan = JSON.parse(await readFile(path.resolve(cwd, options.apply), "utf8"));
|
|
2332
|
+
const result = await applyWorkspaceRemovalPlan(cwd, plan);
|
|
2333
|
+
process.stdout.write(`${options.json ? JSON.stringify(result, null, 2) : formatResult(result)}\n`);
|
|
2334
|
+
return;
|
|
2335
|
+
}
|
|
2336
|
+
if (target === void 0) throw new Error(localize("Select one workspace package or provide --apply <plan.json>.", "请选择单个工作区包或传入 --apply <plan.json>。"));
|
|
2337
|
+
const plan = await planWorkspaceRemoval(cwd, {
|
|
2338
|
+
target,
|
|
2339
|
+
removeReferences: options.removeReferences === true
|
|
2340
|
+
});
|
|
2341
|
+
process.stdout.write(`${options.json ? JSON.stringify(plan, null, 2) : formatPlan(plan)}\n`);
|
|
2342
|
+
if (!plan.canApply) process.exitCode = 1;
|
|
2343
|
+
});
|
|
2344
|
+
}
|
|
2345
|
+
//#endregion
|
|
2346
|
+
//#region src/cli/commands/workspace/tasks.ts
|
|
2347
|
+
function formatCatalog(catalog) {
|
|
2348
|
+
return catalog.packages.flatMap((pkg) => [`${pkg.name ?? "(unnamed)"} (${pkg.id})${pkg.root ? " [root]" : ""}${pkg.private ? " [private]" : ""}`, ...pkg.tasks.length ? pkg.tasks.map((task) => ` ${task.name}: ${task.command}`) : [localize(" (no scripts)", " (无脚本)")]]).join("\n") || localize("No workspace matches the requested query/script.", "没有工作区符合指定查询或脚本。");
|
|
2349
|
+
}
|
|
2350
|
+
function registerWorkspaceTasks(workspace, cwd) {
|
|
2351
|
+
workspace.command("tasks").description(localize("Discover workspace scripts without running them", "发现工作区脚本,不执行任务")).argument("[query]", localize("Search name, path, description or task name", "搜索名称、路径、说明或任务名")).option("--script <name>", localize("Require an exact script name", "筛选实际包含指定脚本的工作区")).option("--no-private", localize("Exclude private workspaces", "排除私有工作区")).option("--no-root", localize("Exclude root scripts", "排除根级脚本")).option("--json", localize("Output a versioned JSON catalog", "输出有版本结构的 JSON 任务目录")).action(async (query, options) => {
|
|
2352
|
+
const catalog = await getWorkspaceTaskCatalog(cwd, {
|
|
2353
|
+
...query !== void 0 ? { query } : {},
|
|
2354
|
+
...options.script !== void 0 ? { script: options.script } : {},
|
|
2355
|
+
includePrivate: options.private,
|
|
2356
|
+
includeRoot: options.root
|
|
2357
|
+
});
|
|
2358
|
+
process.stdout.write(`${options.json ? JSON.stringify(catalog, null, 2) : formatCatalog(catalog)}\n`);
|
|
2359
|
+
if (!catalog.packages.length) process.exitCode = 1;
|
|
2360
|
+
});
|
|
2361
|
+
workspace.command("locate").description(localize("Print one workspace path; report ambiguous matches", "输出唯一工作区路径;明确报告模糊匹配歧义")).argument("<query>", localize("Workspace name, path or search text", "工作区名称、路径或搜索文本")).option("--json", localize("Output status and candidates as JSON", "以 JSON 输出状态及候选项")).option("-i, --interactive", localize("Choose an ambiguous result in an interactive terminal", "在交互终端选择存在歧义的结果")).action(async (query, options) => {
|
|
2362
|
+
const result = await locateWorkspace(cwd, query);
|
|
2363
|
+
const ci = ![
|
|
2364
|
+
void 0,
|
|
2365
|
+
"",
|
|
2366
|
+
"false",
|
|
2367
|
+
"0"
|
|
2368
|
+
].includes(process.env["CI"]?.trim().toLowerCase());
|
|
2369
|
+
if (result.status === "ambiguous" && options.interactive && !options.json && !ci && process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY) {
|
|
2370
|
+
const id = await select({
|
|
2371
|
+
message: localize("Select a workspace", "选择工作区"),
|
|
2372
|
+
choices: result.candidates.map((pkg) => ({
|
|
2373
|
+
name: `${pkg.name ?? "(unnamed)"} (${pkg.id})`,
|
|
2374
|
+
value: pkg.id
|
|
2375
|
+
}))
|
|
2376
|
+
}, { output: process.stderr });
|
|
2377
|
+
result.candidates = result.candidates.filter((pkg) => pkg.id === id);
|
|
2378
|
+
result.status = "found";
|
|
2379
|
+
}
|
|
2380
|
+
if (options.json) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
2381
|
+
else if (result.status === "found") process.stdout.write(`${result.candidates[0].directory}\n`);
|
|
2382
|
+
else process.stderr.write(`${result.status}: ${query}\n${result.candidates.map((pkg) => ` ${pkg.name ?? "(unnamed)"} (${pkg.id})`).join("\n")}\n`);
|
|
2383
|
+
if (result.status !== "found") process.exitCode = 1;
|
|
2384
|
+
});
|
|
2385
|
+
}
|
|
2386
|
+
//#endregion
|
|
1063
2387
|
//#region src/cli/commands/workspace.ts
|
|
1064
2388
|
function collectValues(value, previous = []) {
|
|
1065
2389
|
return [...previous, value];
|
|
@@ -1128,33 +2452,35 @@ async function emitWorkspaceList(result, opts) {
|
|
|
1128
2452
|
return;
|
|
1129
2453
|
}
|
|
1130
2454
|
const outFile = path.resolve(process.cwd(), opts.out);
|
|
1131
|
-
await fs.outputFile(outFile, `${content}\n`, "utf8");
|
|
2455
|
+
await fs$1.outputFile(outFile, `${content}\n`, "utf8");
|
|
1132
2456
|
logger.success(localize(`Wrote ${path.relative(process.cwd(), outFile)}`, `已写入 ${path.relative(process.cwd(), outFile)}`));
|
|
1133
2457
|
}
|
|
1134
2458
|
function registerWorkspaceCommands(program, cwd) {
|
|
1135
2459
|
const workspaceCommand = program.command("workspace").alias("ws").description(localize("Workspace commands", "工作区命令"));
|
|
1136
|
-
workspaceCommand
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
2460
|
+
registerWorkspaceGraphCommands(workspaceCommand, cwd);
|
|
2461
|
+
registerWorkspaceBoundaries(workspaceCommand, cwd);
|
|
2462
|
+
registerWorkspaceOwnersCommand(workspaceCommand, cwd);
|
|
2463
|
+
registerWorkspacePrepare(workspaceCommand, cwd);
|
|
2464
|
+
registerWorkspaceTasks(workspaceCommand, cwd);
|
|
2465
|
+
registerUpgradeCommand(workspaceCommand, cwd, "up");
|
|
2466
|
+
registerWorkspaceRemoval(workspaceCommand, cwd);
|
|
2467
|
+
registerWorkspaceMove(workspaceCommand, cwd);
|
|
1141
2468
|
workspaceCommand.command("init").description(localize("Initialize workspace metadata and repository files", "初始化工作区元信息(README、package.json、pnpm intent、issue template)")).alias("i").action(async () => {
|
|
1142
|
-
const { initMetadata } = await import("./commands-
|
|
2469
|
+
const { initMetadata } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1143
2470
|
await initMetadata(cwd);
|
|
1144
2471
|
logger.success(localize("Workspace initialization finished.", "Workspace 初始化完成。"));
|
|
1145
2472
|
});
|
|
1146
2473
|
workspaceCommand.command("list").description(localize("List workspace packages", "列出 workspace 包")).alias("ls").option("--json", localize("Output JSON", "输出 JSON")).option("--markdown", localize("Output Markdown", "输出 Markdown,方便粘贴到 issue 或 PR")).option("--redact", localize("Redact workspace, cwd, and home paths", "脱敏 workspace/cwd/home 绝对路径后再输出")).option("--include-private", localize("Include private packages", "包含 private 包")).option("--include-root", localize("Include the workspace root package", "包含 workspace 根包")).option("-p, --pattern <glob>", localize("Append a workspace glob; repeatable", "追加自定义 workspace glob,可重复"), collectValues).option("--out <file>", localize("Write the package list to a file", "把当前列表输出写入文件")).action(async (opts) => {
|
|
1147
|
-
const { getWorkspacePackageSummaries } = await import("./workspace-
|
|
2474
|
+
const { getWorkspacePackageSummaries } = await import("./workspace-tasks-C5W-QwWj.mjs").then((n) => n.Kt);
|
|
1148
2475
|
await emitWorkspaceList(await getWorkspacePackageSummaries(cwd, {
|
|
1149
2476
|
ignorePrivatePackage: !opts.includePrivate,
|
|
1150
2477
|
ignoreRootPackage: !opts.includeRoot,
|
|
1151
2478
|
...opts.pattern?.length ? { patterns: opts.pattern } : {}
|
|
1152
2479
|
}), opts);
|
|
1153
2480
|
});
|
|
1154
|
-
workspaceCommand.command("clean").description(localize("Remove selected workspace packages", "清除选中的包")).alias("rm").option("-y, --yes", localize("
|
|
1155
|
-
const { cleanProjects } = await import("./commands-
|
|
2481
|
+
workspaceCommand.command("clean").description(localize("Remove selected workspace packages", "清除选中的包")).alias("rm").option("-y, --yes", localize("Select all eligible workspace packages without prompting", "跳过交互并选择所有符合条件的工作区包")).option("--dry-run", localize("Preview directory deletions and metadata changes without writing", "预览目录删除和元数据变更,不写入文件")).option("--include-private", localize("Include private packages", "包含 private 包")).option("--pinned-version <version>", localize("Override the repoctl version written to the root package", "覆盖写入的 repoctl 版本")).action(async (opts) => {
|
|
2482
|
+
const { cleanProjects } = await import("./commands-Bj0sX3R9.mjs").then((n) => n.t);
|
|
1156
2483
|
await cleanProjects(cwd, normalizeCleanOptions(opts));
|
|
1157
|
-
logger.success(localize("Workspace cleanup finished.", "Workspace 清理完成。"));
|
|
1158
2484
|
});
|
|
1159
2485
|
}
|
|
1160
2486
|
//#endregion
|
|
@@ -1192,16 +2518,21 @@ registerWorkspaceCommands(program, cwd);
|
|
|
1192
2518
|
registerToolingCommands(program, cwd);
|
|
1193
2519
|
registerEnvCommands(program, cwd);
|
|
1194
2520
|
registerConfigCommands(program, cwd);
|
|
2521
|
+
registerPresetCommands(program, cwd);
|
|
2522
|
+
registerDepsCommands(program, cwd);
|
|
1195
2523
|
registerReleaseCommands(program, cwd);
|
|
1196
2524
|
registerSkillsCommands(program, cwd);
|
|
1197
2525
|
registerVerifyCommands(program, cwd);
|
|
1198
2526
|
registerAiCommands(program, cwd);
|
|
1199
2527
|
registerPackageCommands(program, cwd);
|
|
2528
|
+
registerGenerateCommand(program, cwd);
|
|
2529
|
+
registerMaintenanceCommands(program, cwd);
|
|
1200
2530
|
configureLocalizedHelp(program);
|
|
1201
2531
|
program.addHelpText("after", message("quickStart", { cliName: activeCliName }));
|
|
1202
2532
|
//#endregion
|
|
1203
2533
|
//#region src/cli.ts
|
|
2534
|
+
registerConfigPreflight(program, process.cwd());
|
|
1204
2535
|
if (process.argv.length <= 2) program.outputHelp();
|
|
1205
|
-
else program.
|
|
2536
|
+
else program.parseAsync().catch(reportCliFailure);
|
|
1206
2537
|
//#endregion
|
|
1207
|
-
export {};
|
|
2538
|
+
export { formatAffectedCheckPlan as t };
|