@infly/libs 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,527 +1,540 @@
1
- const fs = require("node:fs");
2
- const os = require("node:os");
3
- const path = require("node:path");
4
- const { execFileSync } = require("node:child_process");
5
- const { EXIT_SELECTION, inputText, selectOption, selectOptions } = require("../../cli/select-option");
6
- const { composeRelease } = require("./compose-release");
7
- const { formatCicdLink, healthCheckImage } = require("./docker-build-push");
8
- const { loadDockerConfig } = require("./config-loader");
9
- const { detectReleaseContext, detectReleaseMode } = require("./release-mode");
10
- const { prepareWorkspaceSnapshot, verifyWorkspaceRemote } = require("./source-snapshot");
11
- const { readRegistryDigest } = require("./release-identity");
12
- const { compareVersions, normalizePreBuildCommand, resolveSourceDirectories, validateComponent, validateReleaseProfile } = require("./release-validation");
13
- const { buildTargetImage, finishTargetImage } = require("./target-image");
14
-
15
- // Jenkins 构建页“镜像版本”与 Webhook 通知均按北京时间展示。
16
- function beijingDateTime(now = new Date()) {
17
- const parts = new Intl.DateTimeFormat("en-CA", {
18
- timeZone: "Asia/Shanghai", year: "numeric", month: "2-digit", day: "2-digit",
19
- hour: "2-digit", minute: "2-digit", hourCycle: "h23",
20
- }).formatToParts(now);
21
- const values = Object.fromEntries(parts.filter((part) => part.type !== "literal").map((part) => [part.type, part.value]));
22
- return `${values.year}-${values.month}-${values.day} ${values.hour}:${values.minute}`;
23
- }
24
-
25
- async function checkDocker(run, projectDir, buildx = true, dependencies = {}, autoStart = true) {
26
- const quiet = { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] };
27
- try {
28
- run("docker", ["info"], quiet);
29
- } catch (error) {
30
- const detail = String(error.stderr || error.message || "").trim();
31
- const env = dependencies.env || process.env;
32
- const platform = dependencies.platform || process.platform;
33
- if (autoStart && platform === "win32" && !env.CI && !env.JENKINS_URL && !env.DOCKER_HOST
34
- && /dockerDesktopLinuxEngine/i.test(detail)) {
35
- // 只针对明确的本机 Desktop 管道启动软件,不切换 context,也不处理远端服务。
36
- const log = dependencies.log || console.log;
37
- log("Docker Desktop Linux 引擎未就绪,正在启动本机 Docker Desktop…");
38
- run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",
39
- "Start-Process -FilePath 'C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe' -WindowStyle Hidden"], quiet);
40
- const sleep = dependencies.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
41
- for (let attempt = 0; attempt < 60; attempt++) {
42
- await sleep(2000);
43
- try { run("docker", ["info"], quiet); }
44
- catch {
45
- if (attempt % 10 === 9) log(`等待 Docker Linux 引擎就绪…${(attempt + 1) * 2}s`);
46
- continue;
47
- }
48
- log("Docker 引擎已就绪,继续构建。");
49
- return checkDocker(run, projectDir, buildx, dependencies, false);
50
- }
51
- throw new Error("Docker Desktop 启动后 120 秒内 Linux 引擎仍未就绪,请检查 Docker Desktop 的启动错误后重试。", { cause: error });
52
- }
53
- const hint = error.code === "ENOENT"
54
- ? "未找到 Docker CLI,请安装 Docker 并确认 docker 位于 PATH。"
55
- : /dockerDesktopLinuxEngine/i.test(detail)
56
- ? "无法连接 Docker Desktop Linux 引擎。请打开 Docker Desktop,等待 Linux 引擎启动,再运行 docker info 确认 Server 可访问。"
57
- : "无法连接 Docker 引擎。请检查 docker context show、DOCKER_HOST 和 Docker 服务状态,再运行 docker info。";
58
- throw new Error(`${hint}\n${detail}`, { cause: error });
59
- }
60
- if (buildx) {
61
- try { run("docker", ["buildx", "version"], quiet); }
62
- catch (error) { throw new Error("Docker 引擎已连接,但 Buildx 不可用。请检查 docker buildx version。", { cause: error }); }
63
- }
64
- }
65
-
66
- function parseReleaseArgs(argv) {
67
- const options = { push: false };
68
- const keys = { "--target": "target", "--platform": "target", "--components": "components",
69
- "--project-dir": "projectDir", "--backend-dir": "backendDir", "--config": "config", "--output": "output",
70
- "--cicd-url": "cicdUrl" };
71
- for (let i = 0; i < argv.length; i++) {
72
- const [flag, ...suffix] = argv[i].split("=");
73
- if (flag === "--") continue;
74
- if (["--push", "--no-push", "--dry-run"].includes(flag) && suffix.length === 0) {
75
- if (flag === "--dry-run") options.dryRun = true;
76
- else options.push = flag === "--push";
77
- continue;
78
- }
79
- if (!keys[flag]) throw new Error(`不支持的参数: ${argv[i]}`);
80
- const value = suffix.length ? suffix.join("=") : argv[++i];
81
- if (!value || value.startsWith("--")) throw new Error(`${flag} 缺少参数值`);
82
- options[keys[flag]] = flag === "--components" ? value.split(",") : value;
83
- }
84
- return options;
85
- }
86
-
87
- function trimPathInput(value) {
88
- const trimmed = String(value || "").trim();
89
- return trimmed.length >= 2 && ((trimmed.startsWith('"') && trimmed.endsWith('"'))
90
- || (trimmed.startsWith("'") && trimmed.endsWith("'")))
91
- ? trimmed.slice(1, -1).trim()
92
- : trimmed;
93
- }
94
-
95
- const UNSAFE_WINDOWS_SHELL_TOKEN = /[\r\n\0&|<>^%!"]/;
96
- const WINDOWS_PACKAGE_MANAGERS = new Set(["npm", "npx", "pnpm", "yarn"]);
97
-
98
- function windowsExecutable(command, platform = process.platform) {
99
- return platform === "win32" && WINDOWS_PACKAGE_MANAGERS.has(command)
100
- ? `${command}.cmd`
101
- : command;
102
- }
103
-
104
- function quoteWindowsShellToken(value) {
105
- const token = String(value);
106
- if (UNSAFE_WINDOWS_SHELL_TOKEN.test(token)) {
107
- throw new Error(`Windows 包管理器参数包含不安全字符: ${token}`);
108
- }
109
- return /[\s()]/.test(token) ? `"${token}"` : token;
110
- }
111
-
112
- function buildExecutableSpawn(command, args, {
113
- platform = process.platform,
114
- env = process.env,
115
- } = {}) {
116
- if (platform !== "win32" || !WINDOWS_PACKAGE_MANAGERS.has(command)) {
117
- return { command, args };
118
- }
119
- const shellCommand = [command, ...args].map(quoteWindowsShellToken).join(" ");
120
- return {
121
- command: env.ComSpec || "cmd.exe",
122
- args: ["/d", "/s", "/c", shellCommand],
123
- };
124
- }
125
-
126
- function runReleasePreparation(profile, {
127
- run,
128
- capture,
129
- projectDir,
130
- push,
131
- platform = process.platform,
132
- env = process.env,
133
- releaseMode = detectReleaseMode(projectDir),
134
- log = console.log,
135
- }) {
136
- validateReleaseProfile(profile, profile.label || "Docker target");
137
- const git = (...args) => capture("git", ["-C", projectDir, ...args]);
138
- if (git("status", "--porcelain", "--untracked-files=all")) {
139
- throw new Error("当前项目存在未提交改动,不能构建发布镜像");
140
- }
141
- if (push && profile.pushBranch) {
142
- const branch = git("branch", "--show-current");
143
- if (branch !== profile.pushBranch) {
144
- throw new Error(`镜像只允许从 ${profile.pushBranch} 推送;当前分支: ${branch || "detached HEAD"}`);
145
- }
146
- const slash = profile.pushRef.indexOf("/");
147
- const remote = profile.pushRef.slice(0, slash);
148
- const remoteBranch = profile.pushRef.slice(slash + 1);
149
- run("git", ["-C", projectDir, "fetch", remote, remoteBranch], { cwd: projectDir });
150
- const commit = git("rev-parse", "HEAD").toLowerCase();
151
- const remoteCommit = git("rev-parse", `${profile.pushRef}^{commit}`).toLowerCase();
152
- if (commit !== remoteCommit) {
153
- throw new Error(`${profile.pushBranch} 必须已推送并与 ${profile.pushRef} 同步`);
154
- }
155
- }
156
- for (const [tool, requirement] of Object.entries(profile.requirements || {})) {
157
- const invocation = buildExecutableSpawn(tool, ["--version"], { platform, env });
158
- const actual = capture(invocation.command, invocation.args);
159
- if (!compareVersions(actual, requirement)) {
160
- throw new Error(`${tool} 必须满足 ${requirement},当前版本: ${actual || "无法识别"}`);
161
- }
162
- }
163
- for (const rawCommand of profile.preBuild || []) {
164
- const { command: commandArgs, when } = normalizePreBuildCommand(
165
- rawCommand,
166
- profile.label || "Docker target",
167
- );
168
- const [command, ...args] = commandArgs;
169
- if (when !== "always" && when !== releaseMode) {
170
- log(`跳过发布准备(当前 ${releaseMode} 模式,仅 ${when} 执行): ${commandArgs.join(" ")}`);
171
- continue;
172
- }
173
- log(`执行发布准备: ${command} ${args.join(" ")}`);
174
- const invocation = buildExecutableSpawn(command, args, { platform, env });
175
- run(invocation.command, invocation.args, { cwd: projectDir });
176
- }
177
- }
178
-
179
- function execute(command, args, options = {}) {
180
- return execFileSync(command, args, { stdio: "inherit", ...options });
181
- }
182
-
183
- function freezeReleaseSources(plan, {
184
- profile, projectDir, releaseContext, push, dependencies,
185
- sources, workspaces, publicSnapshots, resources, verifyFrozen, io, run, capture,
186
- }) {
187
- let configuration;
188
- if (profile.recordConfigurationRevision || plan.some((item) => item.dockerfileFromConfig || item.contextFiles)) {
189
- const commit = capture("git", ["-C", projectDir, "rev-parse", "HEAD"]).toLowerCase();
190
- if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error("无法冻结部署配置版本");
191
- configuration = { sourceDir: projectDir, commit };
192
- verifyFrozen(configuration, "部署配置");
193
- workspaces.set(projectDir, configuration);
194
- }
195
- // 所有来源先冻结,再开始任何镜像构建。相同仓库和分支只 fetch 一次,
196
- // worktree 使用完整 SHA,后续远端分支前移不会把同一组镜像拆成不同版本。
197
- for (const item of plan) {
198
- const directory = item.source?.directory || projectDir;
199
- const sourceKey = JSON.stringify([directory, item.source?.branch || null]);
200
- let frozen = sources.get(sourceKey);
201
- if (!frozen) {
202
- let sourceDir = projectDir;
203
- let commit;
204
- if (item.source) {
205
- run("git", ["-C", directory, "fetch", "origin"], { cwd: projectDir });
206
- commit = capture("git", ["-C", directory, "rev-parse", `origin/${item.source.branch}^{commit}`]).toLowerCase();
207
- if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
208
- const tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
209
- sourceDir = path.join(tempRoot, "source");
210
- // add 失败时也保留清理记录;不能安全移除 worktree 时留下目录供人工恢复。
211
- resources.push({ tempRoot, worktree: sourceDir, repository: directory });
212
- run("git", ["-C", directory, "worktree", "add", "--detach", sourceDir, commit], { cwd: projectDir });
213
- } else {
214
- commit = capture("git", ["-C", sourceDir, "rev-parse", "HEAD"]).toLowerCase();
215
- }
216
- if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
217
- frozen = { sourceDir, commit };
218
- sources.set(sourceKey, frozen);
219
- }
220
- const git = (...args) => capture("git", ["-C", frozen.sourceDir, ...args]);
221
- if (git("status", "--porcelain", "--untracked-files=all")) throw new Error(`${item.name} 仓库存在未提交改动`);
222
- const expectedRef = item.source ? null : item.expectedRef;
223
- if (git("rev-parse", "HEAD").toLowerCase() !== frozen.commit || (expectedRef
224
- && frozen.commit !== git("rev-parse", `${expectedRef}^{commit}`).toLowerCase())) {
225
- throw new Error(`${item.name} HEAD 与 ${expectedRef || "冻结提交"} 不一致,请先核对并 fetch 对应仓库`);
226
- }
227
- item.frozen = frozen;
228
- item.releaseContext = item.source
229
- ? ((!item.source.standalone && (item.dockerfileFromConfig || item.contextFiles))
230
- ? (dependencies.detectReleaseContext || detectReleaseContext)({ projectDir: item.source.directory })
231
- : { mode: "standalone", contextRoot: frozen.sourceDir, projectRelativeDir: "." })
232
- : releaseContext;
233
- if (item.source && item.releaseContext.mode === "standalone") {
234
- item.releaseContext = { ...item.releaseContext, contextRoot: frozen.sourceDir, projectRelativeDir: "." };
235
- }
236
- if (item.buildStrategy === "source" && item.releaseContext.mode === "monorepo") {
237
- const contextRoot = item.releaseContext.contextRoot;
238
- let workspace = workspaces.get(contextRoot);
239
- if (!workspace) {
240
- const revision = capture("git", ["-C", contextRoot, "rev-parse", "HEAD"]).toLowerCase();
241
- if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error(`${item.name} 无法解析合法的 monorepo revision`);
242
- workspace = { sourceDir: contextRoot, commit: revision };
243
- verifyFrozen(workspace, `${item.name} 的 monorepo 构建上下文`);
244
- workspaces.set(contextRoot, workspace);
245
- }
246
- item.workspace = workspace;
247
- if (item.projectInstall) {
248
- const synchronized = dependencies.rootSynchronization;
249
- if (synchronized?.verified && synchronized.workspaceRoot === contextRoot && synchronized.revision === workspace.commit) {
250
- workspace.remote = { expectedRef: synchronized.expectedRef, revision: synchronized.revision, verified: true };
251
- }
252
- if (push && !workspace.remote) {
253
- if (!item.workspaceRef) throw new Error(`${item.name} 正式源码发布必须配置 workspaceRef`);
254
- workspace.remote = verifyWorkspaceRemote({ workspaceRoot: contextRoot, revision: workspace.commit,
255
- expectedRef: item.workspaceRef, capture });
256
- }
257
- if (workspace.remote && item.workspaceRef !== workspace.remote.expectedRef) throw new Error("同一主仓不能使用不同的 workspaceRef");
258
- if (!publicSnapshots.has(contextRoot)) {
259
- const snapshot = (dependencies.prepareWorkspaceSnapshot || prepareWorkspaceSnapshot)({
260
- workspaceRoot: contextRoot, revision: workspace.commit, run,
261
- });
262
- publicSnapshots.set(contextRoot, snapshot);
263
- resources.push({ tempRoot: snapshot.contextRoot });
264
- }
265
- }
266
- }
267
- }
268
- return configuration;
269
- }
270
-
271
- function pushReleaseImages(results, { projectDir, run, capture }) {
272
- // 整组构建及校验通过后才推送。Registry 的多次 push 不具备事务性,
273
- // 网络失败可能留下部分镜像;不打印成功汇总,部署端仍需校验整组镜像齐备。
274
- for (const result of results) {
275
- run("docker", ["push", result.image], { cwd: projectDir });
276
- if (result.releaseId) {
277
- result.digest = readRegistryDigest(capture, result.image);
278
- result.deployImage = `${result.image.slice(0, result.image.lastIndexOf(":"))}@${result.digest}`;
279
- run("docker", ["pull", "--platform", result.provenance.platform, result.deployImage], { cwd: projectDir });
280
- if (capture("docker", ["image", "inspect", "--format", "{{.Id}}", result.deployImage]) !== result.imageId) {
281
- throw new Error("Registry digest 对应的内容与本地已验证镜像不一致");
282
- }
283
- }
284
- if (result.latestImage) run("docker", ["push", result.latestImage], { cwd: projectDir });
285
- result.pushed = true;
286
- }
287
- // 全组精确镜像均验证成功后才更新环境入口;部署端立即解析为 digest,之后不再读取可变标签。
288
- for (const result of results.filter((entry) => entry.channelImage)) {
289
- run("docker", ["tag", result.imageId, result.channelImage], { cwd: projectDir });
290
- run("docker", ["push", result.channelImage], { cwd: projectDir });
291
- if (readRegistryDigest(capture, result.channelImage) !== result.digest) throw new Error("环境最新镜像入口与本次发布内容不一致");
292
- }
293
- }
294
-
295
- function logReleaseSummary(results, { target, profile, push, cicdUrl, cicdLink, log, now }) {
296
- // 构建结果汇总(排版与 build:docker 保持一致:✅ 完成 + 可用标签 + 可选发布系统链接)。
297
- // 构建时已逐组件打印 frontend_commit= 等机器行,供失败前人工留档;这里汇总为可直接复制到
298
- // 输出同时面向本地核对与 Jenkins 下拉部署,避免再手工复制提交参数。
299
- if (results.length) {
300
- const usesMutableTags = results.some((item) => item.latestImage);
301
- const pushNote = push
302
- ? profile.deployment?.ready === true
303
- ? usesMutableTags
304
- ? "已推送不可变提交标签和 latest 最新推送标签,可直接在 Jenkins 选择部署"
305
- : "已推送不可变提交标签,可直接在 Jenkins 选择部署"
306
- : usesMutableTags
307
- ? "已推送不可变提交标签和 latest 最新推送标签;该平台尚未开放 Jenkins 部署"
308
- : "已推送不可变提交标签;该平台尚未开放 Jenkins 部署"
309
- : "仅本地生成,未推送镜像";
310
- log("");
311
- log("\x1b[0;34m==========================================");
312
- log("✅ 完成");
313
- log("==========================================\x1b[0m");
314
- log(`可用标签(${pushNote}):`);
315
- for (const r of results) {
316
- log(` ${r.component}=${r.image} (${r.releaseId ? "唯一发布版本" : "不可变提交版本"})`);
317
- if (r.pushed && r.channelImage) log(` ${r.component}_channel=${r.channelImage} (默认部署入口,部署时固定 digest)`);
318
- if (r.latestImage) log(` ${r.component}_latest=${r.latestImage} (最新推送镜像,即所选平台 registry 的 latest)`);
319
- if (r.pushed && profile.deployment?.ready === true && profile.deployment.instructions?.length) {
320
- log("");
321
- for (const line of profile.deployment.instructions) {
322
- log(line.replace(/\{(releaseId|image)\}/g, (_, field) => r[field] || r.commit));
323
- }
324
- }
325
- }
326
- if (cicdLink && profile.deployment?.ready === true) {
327
- log("");
328
- // 单组件推送成功后把平台与完整提交预填进 Jenkins 参数,新平台首次部署无需从历史下拉选项挑选;
329
- // 多组件对应多个任务时保持原链接,非 /build 地址由 formatCicdLink 原样返回。
330
- const deployLink = push && profile.deployment?.ready === true
331
- && results.length === 1 && /^[a-z0-9]+$/.test(target)
332
- ? formatCicdLink(cicdUrl, { platform: target, platformLabel: profile.label,
333
- tag: results[0].commit, releaseVersion: results[0].releaseId,
334
- date: beijingDateTime(now ? now() : undefined) })
335
- : cicdLink;
336
- log(deployLink);
337
- }
338
- }
339
- }
340
-
341
- async function runTargetRelease(options = {}, dependencies = {}) {
342
- const projectDir = path.resolve(options.projectDir || process.cwd());
343
- const config = loadDockerConfig({ projectDir, configPath: options.config,
344
- configObject: options.configObject, configDir: options.configDir });
345
- const targets = config?.targets;
346
- if (!targets || !Object.keys(targets).length) throw new Error("请配置 infly.docker.targets");
347
- const releaseScripts = config?.releaseScripts || {};
348
- const releaseContext = detectReleaseContext({ projectDir });
349
- const log = dependencies.log || console.log;
350
- const target = options.target || await (dependencies.selectOption || selectOption)("请选择构建平台",
351
- Object.entries(targets).map(([value, item]) => ({ value, label: item.label || value })));
352
- if (target === EXIT_SELECTION) return { cancelled: true };
353
- const profile = targets[target];
354
- const cicdUrl = options.cicdUrl ?? profile?.cicdUrl ?? config.cicdUrl;
355
- const cicdLink = formatCicdLink(cicdUrl);
356
- if (profile && !profile.components && profile.file) {
357
- // 旧目标只有 Compose 文件,保留既有镜像/版本语义,不把前端目标静默升级为前后端生产发布。
358
- const components = options.components || await (dependencies.selectOptions || selectOptions)("请选择构建范围",
359
- [{ value: "frontend", label: "前端(Compose)" }]);
360
- if (components === EXIT_SELECTION) return { cancelled: true };
361
- if (!Array.isArray(components) || components.length !== 1 || components[0] !== "frontend") {
362
- throw new Error(`平台 ${target} 只配置了 Compose 前端构建,不支持后端`);
363
- }
364
- log(`平台 ${profile.label || target} 使用 Compose 配置中的镜像标签,不自动升级版本;不生成 qc 镜像。`);
365
- if (!options.dryRun) await checkDocker(dependencies.run || execute, projectDir, false, dependencies);
366
- const result = await (dependencies.composeRelease || composeRelease)({ projectDir, file: profile.file,
367
- bump: "none", push: Boolean(options.push), dryRun: Boolean(options.dryRun) });
368
- if (!options.dryRun && cicdLink && profile.deployment?.ready !== false) {
369
- log("");
370
- log(cicdLink);
371
- }
372
- return result;
373
- }
374
- if (!profile?.components) throw new Error(`平台 ${target} 未配置 components`);
375
- validateReleaseProfile(profile, target);
376
- const components = options.components || await (dependencies.selectOptions || selectOptions)("请选择构建范围",
377
- Object.entries(profile.components).map(([value, item]) => ({ value, label: item.label || value })));
378
- if (components === EXIT_SELECTION) return { cancelled: true };
379
- if (!Array.isArray(components) || !components.length || new Set(components).size !== components.length) {
380
- throw new Error("请至少选择一个构建范围,且不能重复");
381
- }
382
- const io = dependencies.fs || fs;
383
- const plan = components.map((name) => {
384
- if (!Object.hasOwn(profile.components, name)) throw new Error(`不支持的构建范围: ${name}`);
385
- const component = profile.components[name];
386
- validateComponent(component, name, Boolean(profile.pushRef));
387
- if (component.releaseChannel && !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/.test(`${component.tagPrefix || ""}${target}-latest`)) {
388
- throw new Error("环境最新镜像标签无效");
389
- }
390
- if (!component.source) return { name, ...component };
391
- const configuredDirectory = name === "backend" && options.backendDir ? options.backendDir : component.source.directory;
392
- const directoryCandidates = resolveSourceDirectories(projectDir, configuredDirectory, name);
393
- return { name, ...component, source: { ...component.source,
394
- directory: directoryCandidates[0], directoryCandidates } };
395
- });
396
- // dry-run 只解析配置,不联网、不调用 Git/Docker、不创建临时目录。
397
- if (options.dryRun) { log(JSON.stringify({ target, push: Boolean(options.push), plan }, null, 2)); return { target, plan }; }
398
- // 全部组件先预检,数组按顺序采用第一个 Git 仓;交互终端允许补录机器本地路径。
399
- const stdin = dependencies.stdin || process.stdin;
400
- const stdout = dependencies.stdout || process.stdout;
401
- const interactive = dependencies.interactive ?? Boolean(stdin.isTTY && stdout.isTTY);
402
- for (const item of plan.filter((candidate) => candidate.source)) {
403
- const matched = item.source.directoryCandidates.find((directory) => io.existsSync(path.join(directory, ".git")));
404
- if (matched) {
405
- item.source.directory = matched;
406
- continue;
407
- }
408
- if (!interactive) continue;
409
- log(`未在 ${item.name} 源码候选路径中找到 Git 仓库:`);
410
- item.source.directoryCandidates.forEach((directory, index) => log(` ${index + 1}. ${directory}`));
411
- const example = process.platform === "win32" ? "D:\\Repo\\equity_project" : "/opt/src/equity_project";
412
- log(`请输入源码仓路径,例如:${example}`);
413
- log(`也可以退出后使用 --backend-dir "${example}" 重新执行。`);
414
- while (true) {
415
- const entered = await (dependencies.inputText || inputText)(
416
- `请输入 ${item.name} 源码 Git 仓库路径(例如 ${example})`,
417
- { stdin, stdout },
418
- );
419
- if (entered === EXIT_SELECTION) return { cancelled: true };
420
- const normalized = trimPathInput(entered);
421
- const candidate = normalized ? path.resolve(projectDir, normalized) : "";
422
- if (candidate && io.existsSync(path.join(candidate, ".git"))) {
423
- item.source.directory = candidate;
424
- item.source.directoryCandidates.push(candidate);
425
- log(`已使用 ${item.name} 源码仓:${candidate}`);
426
- break;
427
- }
428
- log(`路径不是有效 Git 仓库(缺少 .git):${candidate || "<空>"}`);
429
- }
430
- }
431
- const missing = plan.filter((item) => item.source && !io.existsSync(path.join(item.source.directory, ".git")));
432
- if (missing.length) {
433
- for (const item of missing) {
434
- const source = item.source;
435
- const releaseScript = releaseScripts[item.name];
436
- if (releaseScript && !/^[a-z0-9][a-z0-9:._-]*$/i.test(releaseScript)) {
437
- throw new Error(`${item.name} releaseScripts 配置无效`);
438
- }
439
- log(`未找到 ${item.name} 源码仓: ${source.directory}`);
440
- log("未执行任何构建或推送。请手动完成以下步骤:");
441
- if (source.url) log(`1. git clone "${source.url}" "${source.directory}"`);
442
- log(`${source.url ? "2" : "1"}. git -C "${source.directory}" fetch origin "${source.branch}"`);
443
- const overrides = `${options.backendDir ? ` --backend-dir "${options.backendDir}"` : ""}${options.config ? ` --config "${options.config}"` : ""}`;
444
- const rerun = releaseScript
445
- ? `pnpm run ${releaseScript} -- --platform ${target}${overrides}`
446
- : `pnpm exec infly-libs release:docker --project-dir "${projectDir}" --target ${target} --components ${components.join(",")}${overrides} ${options.push ? "--push" : "--no-push"}`;
447
- log(`${source.url ? "3" : "2"}. ${rerun}`);
448
- }
449
- return { target, missingSources: missing.map((item) => item.name) };
450
- }
451
- const run = dependencies.run || execute;
452
- const capture = (command, args) => String(run(command, args, { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) || "").trim();
453
- if (profile.pushRef || profile.requirements || profile.preBuild) {
454
- runReleasePreparation(profile, { run, capture, projectDir, push: Boolean(options.push),
455
- platform: dependencies.platform, env: dependencies.env,
456
- releaseMode: releaseContext.mode, log });
457
- }
458
- await checkDocker(run, projectDir, true, dependencies);
459
- const results = [];
460
- const sources = new Map();
461
- const workspaces = new Map();
462
- const resources = [];
463
- const publicSnapshots = new Map();
464
- const verifyFrozen = ({ sourceDir, commit }, name) => {
465
- const git = (...args) => capture("git", ["-C", sourceDir, ...args]);
466
- if (git("status", "--porcelain", "--untracked-files=all")
467
- || git("rev-parse", "HEAD").toLowerCase() !== commit) {
468
- throw new Error(`${name} 源码在冻结后发生变化,已停止本组构建及推送`);
469
- }
470
- };
471
- let releaseError;
472
- try {
473
- const configuration = freezeReleaseSources(plan, {
474
- profile, projectDir, releaseContext, push: options.push, dependencies,
475
- sources, workspaces, publicSnapshots, resources, verifyFrozen, io, run, capture,
476
- });
477
- for (const item of plan) {
478
- const built = buildTargetImage(item, {
479
- target, configuration, projectDir, publicSnapshots, resources, verifyFrozen,
480
- io, run, capture, log, dependencies, buildExecutableSpawn,
481
- });
482
- if (item.health) {
483
- await (dependencies.healthCheckImage || healthCheckImage)(built.image, {
484
- cwd: projectDir, healthTimeout: String(item.health.timeoutSeconds), healthAddHost: item.health.addHost,
485
- });
486
- }
487
- results.push(finishTargetImage(item, built, { target, capture, log }));
488
- }
489
- for (const frozen of sources.values()) verifyFrozen(frozen, frozen.sourceDir);
490
- for (const frozen of workspaces.values()) verifyFrozen(frozen, "monorepo 构建上下文");
491
- if (options.push) pushReleaseImages(results, { projectDir, run, capture });
492
- } catch (error) {
493
- releaseError = error;
494
- } finally {
495
- const cleanupErrors = [];
496
- for (const resource of resources.reverse()) {
497
- try {
498
- // 只移除本次创建的隔离 worktree;移除失败时不删除其父目录。
499
- if (resource.worktree) run("git", ["-C", resource.repository, "worktree", "remove", "--force", resource.worktree], { cwd: projectDir });
500
- io.rmSync(resource.tempRoot, { recursive: true, force: true });
501
- } catch (error) {
502
- log(`临时构建目录清理失败,已保留恢复路径:${resource.tempRoot}`);
503
- cleanupErrors.push(new Error(`清理失败,保留恢复路径:${resource.tempRoot}`, { cause: error }));
504
- }
505
- }
506
- if (cleanupErrors.length) releaseError = new globalThis.AggregateError(
507
- [...(releaseError ? [releaseError] : []), ...cleanupErrors],
508
- [releaseError?.message, ...cleanupErrors.map((error) => error.message)].filter(Boolean).join(";"),
509
- );
510
- }
511
- if (releaseError) throw releaseError;
512
- for (const result of results.filter((entry) => entry.releaseId)) {
513
- const recordRoot = path.join(projectDir, "node_modules", ".cache", "infly-releases");
514
- io.mkdirSync(recordRoot, { recursive: true });
515
- const record = path.join(recordRoot, `${result.releaseId}.json`);
516
- io.writeFileSync(record, `${JSON.stringify(result, null, 2)}\n`, { flag: "wx" });
517
- log(`release_id=${result.releaseId}`);
518
- if (result.deployImage) log(`deploy_image=${result.deployImage}`);
519
- log(`release_record=${record}`);
520
- }
521
-
522
- logReleaseSummary(results, { target, profile, push: options.push, cicdUrl, cicdLink, log, now: dependencies.now });
523
- return { target, results };
524
- }
525
-
526
- module.exports = { buildExecutableSpawn, compareVersions, detectReleaseContext, detectReleaseMode, normalizePreBuildCommand,
527
- parseReleaseArgs, runReleasePreparation, runTargetRelease, validateReleaseProfile, windowsExecutable };
1
+ const { formatTerminalMessage } = require("../../cli/terminal-style");
2
+ const fs = require("node:fs");
3
+ const os = require("node:os");
4
+ const path = require("node:path");
5
+ const { execFileSync } = require("node:child_process");
6
+ const { EXIT_SELECTION, inputText, selectOption, selectOptions } = require("../../cli/select-option");
7
+ const { composeRelease } = require("./compose-release");
8
+ const { formatCicdLink, healthCheckImage } = require("./docker-build-push");
9
+ const { loadDockerConfig } = require("./config-loader");
10
+ const { detectReleaseContext, detectReleaseMode } = require("./release-mode");
11
+ const { prepareWorkspaceSnapshot, verifyWorkspaceRemote } = require("./source-snapshot");
12
+ const { readRegistryDigest } = require("./release-identity");
13
+ const { compareVersions, normalizePreBuildCommand, resolveSourceDirectories, validateComponent,
14
+ validateReleaseProfile, validateRepository } = require("./release-validation");
15
+ const { buildTargetImage, finishTargetImage, resolveBuildSecrets } = require("./target-image");
16
+
17
+ // Jenkins 构建页“镜像版本”与 Webhook 通知均按北京时间展示。
18
+ function beijingDateTime(now = new Date()) {
19
+ const parts = new Intl.DateTimeFormat("en-CA", {
20
+ timeZone: "Asia/Shanghai", year: "numeric", month: "2-digit", day: "2-digit",
21
+ hour: "2-digit", minute: "2-digit", hourCycle: "h23",
22
+ }).formatToParts(now);
23
+ const values = Object.fromEntries(parts.filter((part) => part.type !== "literal").map((part) => [part.type, part.value]));
24
+ return `${values.year}-${values.month}-${values.day} ${values.hour}:${values.minute}`;
25
+ }
26
+
27
+ async function checkDocker(run, projectDir, buildx = true, dependencies = {}, autoStart = true) {
28
+ const quiet = { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] };
29
+ try {
30
+ run("docker", ["info"], quiet);
31
+ } catch (error) {
32
+ const detail = String(error.stderr || error.message || "").trim();
33
+ const env = dependencies.env || process.env;
34
+ const platform = dependencies.platform || process.platform;
35
+ if (autoStart && platform === "win32" && !env.CI && !env.JENKINS_URL && !env.DOCKER_HOST
36
+ && /dockerDesktopLinuxEngine/i.test(detail)) {
37
+ // 只针对明确的本机 Desktop 管道启动软件,不切换 context,也不处理远端服务。
38
+ const log = dependencies.log || console.log;
39
+ log("Docker Desktop Linux 引擎未就绪,正在启动本机 Docker Desktop…");
40
+ run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",
41
+ "Start-Process -FilePath 'C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe' -WindowStyle Hidden"], quiet);
42
+ const sleep = dependencies.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
43
+ for (let attempt = 0; attempt < 60; attempt++) {
44
+ await sleep(2000);
45
+ try { run("docker", ["info"], quiet); }
46
+ catch {
47
+ if (attempt % 10 === 9) log(`等待 Docker Linux 引擎就绪…${(attempt + 1) * 2}s`);
48
+ continue;
49
+ }
50
+ log("Docker 引擎已就绪,继续构建。");
51
+ return checkDocker(run, projectDir, buildx, dependencies, false);
52
+ }
53
+ throw new Error("Docker Desktop 启动后 120 秒内 Linux 引擎仍未就绪,请检查 Docker Desktop 的启动错误后重试。", { cause: error });
54
+ }
55
+ const hint = error.code === "ENOENT"
56
+ ? "未找到 Docker CLI,请安装 Docker 并确认 docker 位于 PATH。"
57
+ : /dockerDesktopLinuxEngine/i.test(detail)
58
+ ? "无法连接 Docker Desktop Linux 引擎。请打开 Docker Desktop,等待 Linux 引擎启动,再运行 docker info 确认 Server 可访问。"
59
+ : "无法连接 Docker 引擎。请检查 docker context show、DOCKER_HOST 和 Docker 服务状态,再运行 docker info。";
60
+ throw new Error(`${hint}\n${detail}`, { cause: error });
61
+ }
62
+ if (buildx) {
63
+ try { run("docker", ["buildx", "version"], quiet); }
64
+ catch (error) { throw new Error("Docker 引擎已连接,但 Buildx 不可用。请检查 docker buildx version。", { cause: error }); }
65
+ }
66
+ }
67
+
68
+ function parseReleaseArgs(argv) {
69
+ const options = { push: false };
70
+ const keys = { "--target": "target", "--platform": "target", "--components": "components",
71
+ "--project-dir": "projectDir", "--backend-dir": "backendDir", "--config": "config", "--output": "output",
72
+ "--cicd-url": "cicdUrl" };
73
+ for (let i = 0; i < argv.length; i++) {
74
+ const [flag, ...suffix] = argv[i].split("=");
75
+ if (flag === "--") continue;
76
+ if (["--push", "--no-push", "--dry-run"].includes(flag) && suffix.length === 0) {
77
+ if (flag === "--dry-run") options.dryRun = true;
78
+ else options.push = flag === "--push";
79
+ continue;
80
+ }
81
+ if (!keys[flag]) throw new Error(`不支持的参数: ${argv[i]}`);
82
+ const value = suffix.length ? suffix.join("=") : argv[++i];
83
+ if (!value || value.startsWith("--")) throw new Error(`${flag} 缺少参数值`);
84
+ options[keys[flag]] = flag === "--components" ? value.split(",") : value;
85
+ }
86
+ return options;
87
+ }
88
+
89
+ function trimPathInput(value) {
90
+ const trimmed = String(value || "").trim();
91
+ return trimmed.length >= 2 && ((trimmed.startsWith('"') && trimmed.endsWith('"'))
92
+ || (trimmed.startsWith("'") && trimmed.endsWith("'")))
93
+ ? trimmed.slice(1, -1).trim()
94
+ : trimmed;
95
+ }
96
+
97
+ const UNSAFE_WINDOWS_SHELL_TOKEN = /[\r\n\0&|<>^%!"]/;
98
+ const WINDOWS_PACKAGE_MANAGERS = new Set(["npm", "npx", "pnpm", "yarn"]);
99
+
100
+ function windowsExecutable(command, platform = process.platform) {
101
+ return platform === "win32" && WINDOWS_PACKAGE_MANAGERS.has(command)
102
+ ? `${command}.cmd`
103
+ : command;
104
+ }
105
+
106
+ function quoteWindowsShellToken(value) {
107
+ const token = String(value);
108
+ if (UNSAFE_WINDOWS_SHELL_TOKEN.test(token)) {
109
+ throw new Error(`Windows 包管理器参数包含不安全字符: ${token}`);
110
+ }
111
+ return /[\s()]/.test(token) ? `"${token}"` : token;
112
+ }
113
+
114
+ function buildExecutableSpawn(command, args, {
115
+ platform = process.platform,
116
+ env = process.env,
117
+ } = {}) {
118
+ if (platform !== "win32" || !WINDOWS_PACKAGE_MANAGERS.has(command)) {
119
+ return { command, args };
120
+ }
121
+ const shellCommand = [command, ...args].map(quoteWindowsShellToken).join(" ");
122
+ return {
123
+ command: env.ComSpec || "cmd.exe",
124
+ args: ["/d", "/s", "/c", shellCommand],
125
+ };
126
+ }
127
+
128
+ function runReleasePreparation(profile, {
129
+ run,
130
+ capture,
131
+ projectDir,
132
+ push,
133
+ platform = process.platform,
134
+ env = process.env,
135
+ releaseMode = detectReleaseMode(projectDir),
136
+ log = console.log,
137
+ }) {
138
+ validateReleaseProfile(profile, profile.label || "Docker target");
139
+ const git = (...args) => capture("git", ["-C", projectDir, ...args]);
140
+ if (git("status", "--porcelain", "--untracked-files=all")) {
141
+ throw new Error("当前项目存在未提交改动,不能构建发布镜像");
142
+ }
143
+ if (push && profile.pushBranch) {
144
+ const branch = git("branch", "--show-current");
145
+ if (branch !== profile.pushBranch) {
146
+ throw new Error(`镜像只允许从 ${profile.pushBranch} 推送;当前分支: ${branch || "detached HEAD"}`);
147
+ }
148
+ const slash = profile.pushRef.indexOf("/");
149
+ const remote = profile.pushRef.slice(0, slash);
150
+ const remoteBranch = profile.pushRef.slice(slash + 1);
151
+ run("git", ["-C", projectDir, "fetch", remote, remoteBranch], { cwd: projectDir });
152
+ const commit = git("rev-parse", "HEAD").toLowerCase();
153
+ const remoteCommit = git("rev-parse", `${profile.pushRef}^{commit}`).toLowerCase();
154
+ if (commit !== remoteCommit) {
155
+ throw new Error(`${profile.pushBranch} 必须已推送并与 ${profile.pushRef} 同步`);
156
+ }
157
+ }
158
+ for (const [tool, requirement] of Object.entries(profile.requirements || {})) {
159
+ const invocation = buildExecutableSpawn(tool, ["--version"], { platform, env });
160
+ const actual = capture(invocation.command, invocation.args);
161
+ if (!compareVersions(actual, requirement)) {
162
+ throw new Error(`${tool} 必须满足 ${requirement},当前版本: ${actual || "无法识别"}`);
163
+ }
164
+ }
165
+ for (const rawCommand of profile.preBuild || []) {
166
+ const { command: commandArgs, when } = normalizePreBuildCommand(
167
+ rawCommand,
168
+ profile.label || "Docker target",
169
+ );
170
+ const [command, ...args] = commandArgs;
171
+ if (when !== "always" && when !== releaseMode) {
172
+ log(`跳过发布准备(当前 ${releaseMode} 模式,仅 ${when} 执行): ${commandArgs.join(" ")}`);
173
+ continue;
174
+ }
175
+ log(`执行发布准备: ${command} ${args.join(" ")}`);
176
+ const invocation = buildExecutableSpawn(command, args, { platform, env });
177
+ run(invocation.command, invocation.args, { cwd: projectDir });
178
+ }
179
+ }
180
+
181
+ function execute(command, args, options = {}) {
182
+ return execFileSync(command, args, { stdio: "inherit", ...options });
183
+ }
184
+
185
+ function freezeReleaseSources(plan, {
186
+ profile, projectDir, releaseContext, push, dependencies,
187
+ sources, workspaces, publicSnapshots, resources, verifyFrozen, io, run, capture,
188
+ }) {
189
+ let configuration;
190
+ if (profile.recordConfigurationRevision || plan.some((item) => item.dockerfileFromConfig || item.contextFiles)) {
191
+ const commit = capture("git", ["-C", projectDir, "rev-parse", "HEAD"]).toLowerCase();
192
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error("无法冻结部署配置版本");
193
+ configuration = { sourceDir: projectDir, commit };
194
+ verifyFrozen(configuration, "部署配置");
195
+ workspaces.set(projectDir, configuration);
196
+ }
197
+ // 所有来源先冻结,再开始任何镜像构建。相同仓库和分支只 fetch 一次,
198
+ // worktree 使用完整 SHA,后续远端分支前移不会把同一组镜像拆成不同版本。
199
+ for (const item of plan) {
200
+ const directory = item.source?.directory || projectDir;
201
+ const sourceKey = JSON.stringify([directory, item.source?.branch || null]);
202
+ let frozen = sources.get(sourceKey);
203
+ if (!frozen) {
204
+ let sourceDir = projectDir;
205
+ let commit;
206
+ if (item.source) {
207
+ run("git", ["-C", directory, "fetch", "origin"], { cwd: projectDir });
208
+ commit = capture("git", ["-C", directory, "rev-parse", `origin/${item.source.branch}^{commit}`]).toLowerCase();
209
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
210
+ const tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
211
+ sourceDir = path.join(tempRoot, "source");
212
+ // add 失败时也保留清理记录;不能安全移除 worktree 时留下目录供人工恢复。
213
+ resources.push({ tempRoot, worktree: sourceDir, repository: directory });
214
+ run("git", ["-C", directory, "worktree", "add", "--detach", sourceDir, commit], { cwd: projectDir });
215
+ } else {
216
+ commit = capture("git", ["-C", sourceDir, "rev-parse", "HEAD"]).toLowerCase();
217
+ }
218
+ if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
219
+ frozen = { sourceDir, commit };
220
+ sources.set(sourceKey, frozen);
221
+ }
222
+ const git = (...args) => capture("git", ["-C", frozen.sourceDir, ...args]);
223
+ if (git("status", "--porcelain", "--untracked-files=all")) throw new Error(`${item.name} 仓库存在未提交改动`);
224
+ const expectedRef = item.source ? null : item.expectedRef;
225
+ if (git("rev-parse", "HEAD").toLowerCase() !== frozen.commit || (expectedRef
226
+ && frozen.commit !== git("rev-parse", `${expectedRef}^{commit}`).toLowerCase())) {
227
+ throw new Error(`${item.name} HEAD 与 ${expectedRef || "冻结提交"} 不一致,请先核对并 fetch 对应仓库`);
228
+ }
229
+ item.frozen = frozen;
230
+ item.releaseContext = item.source
231
+ ? ((!item.source.standalone && (item.dockerfileFromConfig || item.contextFiles))
232
+ ? (dependencies.detectReleaseContext || detectReleaseContext)({ projectDir: item.source.directory })
233
+ : { mode: "standalone", contextRoot: frozen.sourceDir, projectRelativeDir: "." })
234
+ : releaseContext;
235
+ if (item.source && item.releaseContext.mode === "standalone") {
236
+ item.releaseContext = { ...item.releaseContext, contextRoot: frozen.sourceDir, projectRelativeDir: "." };
237
+ }
238
+ if (item.buildStrategy === "source" && item.releaseContext.mode === "monorepo") {
239
+ const contextRoot = item.releaseContext.contextRoot;
240
+ let workspace = workspaces.get(contextRoot);
241
+ if (!workspace) {
242
+ const revision = capture("git", ["-C", contextRoot, "rev-parse", "HEAD"]).toLowerCase();
243
+ if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error(`${item.name} 无法解析合法的 monorepo revision`);
244
+ workspace = { sourceDir: contextRoot, commit: revision };
245
+ verifyFrozen(workspace, `${item.name} 的 monorepo 构建上下文`);
246
+ workspaces.set(contextRoot, workspace);
247
+ }
248
+ item.workspace = workspace;
249
+ if (item.projectInstall) {
250
+ const synchronized = dependencies.rootSynchronization;
251
+ if (synchronized?.verified && synchronized.workspaceRoot === contextRoot && synchronized.revision === workspace.commit) {
252
+ workspace.remote = { expectedRef: synchronized.expectedRef, revision: synchronized.revision, verified: true };
253
+ }
254
+ if (push && !workspace.remote) {
255
+ if (!item.workspaceRef) throw new Error(`${item.name} 正式源码发布必须配置 workspaceRef`);
256
+ workspace.remote = verifyWorkspaceRemote({ workspaceRoot: contextRoot, revision: workspace.commit,
257
+ expectedRef: item.workspaceRef, capture });
258
+ }
259
+ if (workspace.remote && item.workspaceRef !== workspace.remote.expectedRef) throw new Error("同一主仓不能使用不同的 workspaceRef");
260
+ if (!publicSnapshots.has(contextRoot)) {
261
+ const snapshot = (dependencies.prepareWorkspaceSnapshot || prepareWorkspaceSnapshot)({
262
+ workspaceRoot: contextRoot, revision: workspace.commit, run,
263
+ });
264
+ publicSnapshots.set(contextRoot, snapshot);
265
+ resources.push({ tempRoot: snapshot.contextRoot });
266
+ }
267
+ }
268
+ }
269
+ }
270
+ return configuration;
271
+ }
272
+
273
+ function pushReleaseImages(results, { projectDir, run, capture }) {
274
+ // 整组构建及校验通过后才推送。Registry 的多次 push 不具备事务性,
275
+ // 网络失败可能留下部分镜像;不打印成功汇总,部署端仍需校验整组镜像齐备。
276
+ for (const result of results) {
277
+ run("docker", ["push", result.image], { cwd: projectDir });
278
+ if (result.releaseId) {
279
+ result.digest = readRegistryDigest(capture, result.image);
280
+ result.deployImage = `${result.image.slice(0, result.image.lastIndexOf(":"))}@${result.digest}`;
281
+ run("docker", ["pull", "--platform", result.provenance.platform, result.deployImage], { cwd: projectDir });
282
+ if (capture("docker", ["image", "inspect", "--format", "{{.Id}}", result.deployImage]) !== result.imageId) {
283
+ throw new Error("Registry digest 对应的内容与本地已验证镜像不一致");
284
+ }
285
+ }
286
+ if (result.latestImage) run("docker", ["push", result.latestImage], { cwd: projectDir });
287
+ result.pushed = true;
288
+ }
289
+ // 全组精确镜像均验证成功后才更新环境入口;部署端立即解析为 digest,之后不再读取可变标签。
290
+ for (const result of results.filter((entry) => entry.channelImage)) {
291
+ run("docker", ["tag", result.imageId, result.channelImage], { cwd: projectDir });
292
+ run("docker", ["push", result.channelImage], { cwd: projectDir });
293
+ if (readRegistryDigest(capture, result.channelImage) !== result.digest) throw new Error("环境最新镜像入口与本次发布内容不一致");
294
+ }
295
+ }
296
+
297
+ function logReleaseSummary(results, { target, profile, push, cicdUrl, cicdLink, log, now }) {
298
+ // 构建结果汇总采用与 build:docker 一致的成功提示、标签及可选发布系统链接。
299
+ // 构建时已逐组件打印 frontend_commit= 等机器行,供失败前人工留档;这里汇总为可直接复制到
300
+ // 输出同时面向本地核对与 Jenkins 下拉部署,避免再手工复制提交参数。
301
+ if (results.length) {
302
+ const usesMutableTags = results.some((item) => item.latestImage);
303
+ const pushNote = push
304
+ ? profile.deployment?.ready === true
305
+ ? usesMutableTags
306
+ ? "已推送不可变提交标签和 latest 最新推送标签,可直接在 Jenkins 选择部署"
307
+ : "已推送不可变提交标签,可直接在 Jenkins 选择部署"
308
+ : usesMutableTags
309
+ ? "已推送不可变提交标签和 latest 最新推送标签;该平台尚未开放 Jenkins 部署"
310
+ : "已推送不可变提交标签;该平台尚未开放 Jenkins 部署"
311
+ : "仅本地生成,未推送镜像";
312
+ log("");
313
+ log(formatTerminalMessage("success", "构建发布流程已结束"));
314
+ log(`可用标签(${pushNote}):`);
315
+ for (const r of results) {
316
+ log(` ${r.component}=${r.image} (${r.releaseId ? "唯一发布版本" : "不可变提交版本"})`);
317
+ if (r.pushed && r.channelImage) log(` ${r.component}_channel=${r.channelImage} (默认部署入口,部署时固定 digest)`);
318
+ if (r.latestImage) log(` ${r.component}_latest=${r.latestImage} (最新推送镜像,即所选平台 registry 的 latest)`);
319
+ if (r.pushed && profile.deployment?.ready === true && profile.deployment.instructions?.length) {
320
+ log("");
321
+ for (const line of profile.deployment.instructions) {
322
+ log(line.replace(/\{(releaseId|image)\}/g, (_, field) => r[field] || r.commit));
323
+ }
324
+ }
325
+ }
326
+ if (cicdLink && profile.deployment?.ready === true) {
327
+ log("");
328
+ // 单组件推送成功后把平台与完整提交预填进 Jenkins 参数,新平台首次部署无需从历史下拉选项挑选;
329
+ // 多组件对应多个任务时保持原链接,非 /build 地址由 formatCicdLink 原样返回。
330
+ const deployLink = push && profile.deployment?.ready === true
331
+ && results.length === 1 && /^[a-z0-9]+$/.test(target)
332
+ ? formatCicdLink(cicdUrl, { platform: target, platformLabel: profile.label,
333
+ tag: results[0].commit, releaseVersion: results[0].releaseId,
334
+ date: beijingDateTime(now ? now() : undefined) })
335
+ : cicdLink;
336
+ log(deployLink);
337
+ }
338
+ }
339
+ }
340
+
341
+ async function runTargetRelease(options = {}, dependencies = {}) {
342
+ const projectDir = path.resolve(options.projectDir || process.cwd());
343
+ const config = loadDockerConfig({ projectDir, configPath: options.config,
344
+ configObject: options.configObject, configDir: options.configDir });
345
+ const targets = config?.targets;
346
+ if (!targets || !Object.keys(targets).length) throw new Error("请配置 infly.docker.targets");
347
+ const releaseScripts = config?.releaseScripts || {};
348
+ const releaseContext = detectReleaseContext({ projectDir });
349
+ const log = dependencies.log || console.log;
350
+ const target = options.target || await (dependencies.selectOption || selectOption)("请选择构建平台",
351
+ Object.entries(targets).map(([value, item]) => ({ value, label: item.label || value })));
352
+ if (target === EXIT_SELECTION) return { cancelled: true };
353
+ const profile = targets[target];
354
+ const cicdUrl = options.cicdUrl ?? profile?.cicdUrl ?? config.cicdUrl;
355
+ const cicdLink = formatCicdLink(cicdUrl);
356
+ if (profile && !profile.components && profile.file) {
357
+ // 旧目标只有 Compose 文件,保留既有镜像/版本语义,不把前端目标静默升级为前后端生产发布。
358
+ const components = options.components || await (dependencies.selectOptions || selectOptions)("请选择构建范围",
359
+ [{ value: "frontend", label: "前端(Compose)" }]);
360
+ if (components === EXIT_SELECTION) return { cancelled: true };
361
+ if (!Array.isArray(components) || components.length !== 1 || components[0] !== "frontend") {
362
+ throw new Error(`平台 ${target} 只配置了 Compose 前端构建,不支持后端`);
363
+ }
364
+ log(`平台 ${profile.label || target} 使用 Compose 配置中的镜像标签,不自动升级版本;不生成 qc 镜像。`);
365
+ if (!options.dryRun) await checkDocker(dependencies.run || execute, projectDir, false, dependencies);
366
+ const result = await (dependencies.composeRelease || composeRelease)({ projectDir, file: profile.file,
367
+ bump: "none", push: Boolean(options.push), dryRun: Boolean(options.dryRun) });
368
+ if (!options.dryRun && cicdLink && profile.deployment?.ready !== false) {
369
+ log("");
370
+ log(cicdLink);
371
+ }
372
+ return result;
373
+ }
374
+ if (!profile?.components) throw new Error(`平台 ${target} 未配置 components`);
375
+ validateReleaseProfile(profile, target);
376
+ const components = options.components || await (dependencies.selectOptions || selectOptions)("请选择构建范围",
377
+ Object.entries(profile.components).map(([value, item]) => ({ value, label: item.label || value })));
378
+ if (components === EXIT_SELECTION) return { cancelled: true };
379
+ if (!Array.isArray(components) || !components.length || new Set(components).size !== components.length) {
380
+ throw new Error("请至少选择一个构建范围,且不能重复");
381
+ }
382
+ const io = dependencies.fs || fs;
383
+ const plan = components.map((name) => {
384
+ if (!Object.hasOwn(profile.components, name)) throw new Error(`不支持的构建范围: ${name}`);
385
+ const component = profile.components[name];
386
+ validateComponent(component, name, Boolean(profile.pushRef));
387
+ if (component.releaseChannel && !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/.test(`${component.tagPrefix || ""}${target}-latest`)) {
388
+ throw new Error("环境最新镜像标签无效");
389
+ }
390
+ if (!component.source) return { name, ...component };
391
+ const configuredDirectory = name === "backend" && options.backendDir ? options.backendDir : component.source.directory;
392
+ const directoryCandidates = resolveSourceDirectories(projectDir, configuredDirectory, name);
393
+ return { name, ...component, source: { ...component.source,
394
+ directory: directoryCandidates[0], directoryCandidates } };
395
+ });
396
+ // dry-run 只解析配置,不联网、不调用 Git/Docker、不创建临时目录。
397
+ if (options.dryRun) { log(JSON.stringify({ target, push: Boolean(options.push), plan }, null, 2)); return { target, plan }; }
398
+ const env = dependencies.env || process.env;
399
+ const buildSecrets = new Map();
400
+ for (const item of plan) {
401
+ if (item.repositoryEnv) {
402
+ item.repository = env[item.repositoryEnv];
403
+ validateRepository(item.repository, `${item.name} ${item.repositoryEnv}`);
404
+ }
405
+ if (item.buildSecrets) buildSecrets.set(item.name, resolveBuildSecrets(item.buildSecrets, { env, projectDir, io }));
406
+ }
407
+ // 全部组件先预检,数组按顺序采用第一个 Git 仓;交互终端允许补录机器本地路径。
408
+ const stdin = dependencies.stdin || process.stdin;
409
+ const stdout = dependencies.stdout || process.stdout;
410
+ const interactive = dependencies.interactive ?? Boolean(stdin.isTTY && stdout.isTTY);
411
+ for (const item of plan.filter((candidate) => candidate.source)) {
412
+ const matched = item.source.directoryCandidates.find((directory) => io.existsSync(path.join(directory, ".git")));
413
+ if (matched) {
414
+ item.source.directory = matched;
415
+ continue;
416
+ }
417
+ if (!interactive) continue;
418
+ log(`未在 ${item.name} 源码候选路径中找到 Git 仓库:`);
419
+ item.source.directoryCandidates.forEach((directory, index) => log(` ${index + 1}. ${directory}`));
420
+ const example = process.platform === "win32" ? "D:\\Repo\\equity_project" : "/opt/src/equity_project";
421
+ log(`请输入源码仓路径,例如:${example}`);
422
+ log(`也可以退出后使用 --backend-dir "${example}" 重新执行。`);
423
+ while (true) {
424
+ const entered = await (dependencies.inputText || inputText)(
425
+ `请输入 ${item.name} 源码 Git 仓库路径(例如 ${example})`,
426
+ { stdin, stdout },
427
+ );
428
+ if (entered === EXIT_SELECTION) return { cancelled: true };
429
+ const normalized = trimPathInput(entered);
430
+ const candidate = normalized ? path.resolve(projectDir, normalized) : "";
431
+ if (candidate && io.existsSync(path.join(candidate, ".git"))) {
432
+ item.source.directory = candidate;
433
+ item.source.directoryCandidates.push(candidate);
434
+ log(`已使用 ${item.name} 源码仓:${candidate}`);
435
+ break;
436
+ }
437
+ log(`路径不是有效 Git 仓库(缺少 .git):${candidate || "<空>"}`);
438
+ }
439
+ }
440
+ const missing = plan.filter((item) => item.source && !io.existsSync(path.join(item.source.directory, ".git")));
441
+ if (missing.length) {
442
+ for (const item of missing) {
443
+ const source = item.source;
444
+ const releaseScript = releaseScripts[item.name];
445
+ if (releaseScript && !/^[a-z0-9][a-z0-9:._-]*$/i.test(releaseScript)) {
446
+ throw new Error(`${item.name} releaseScripts 配置无效`);
447
+ }
448
+ log(`未找到 ${item.name} 源码仓: ${source.directory}`);
449
+ log("未执行任何构建或推送。请手动完成以下步骤:");
450
+ if (source.url) log(`1. git clone "${source.url}" "${source.directory}"`);
451
+ log(`${source.url ? "2" : "1"}. git -C "${source.directory}" fetch origin "${source.branch}"`);
452
+ const overrides = `${options.backendDir ? ` --backend-dir "${options.backendDir}"` : ""}${options.config ? ` --config "${options.config}"` : ""}`;
453
+ const rerun = releaseScript
454
+ ? `pnpm run ${releaseScript} -- --platform ${target}${overrides}`
455
+ : `pnpm exec infly-libs release:docker --project-dir "${projectDir}" --target ${target} --components ${components.join(",")}${overrides} ${options.push ? "--push" : "--no-push"}`;
456
+ log(`${source.url ? "3" : "2"}. ${rerun}`);
457
+ }
458
+ return { target, missingSources: missing.map((item) => item.name) };
459
+ }
460
+ const run = dependencies.run || execute;
461
+ const capture = (command, args) => String(run(command, args, { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) || "").trim();
462
+ if (profile.pushRef || profile.requirements || profile.preBuild) {
463
+ runReleasePreparation(profile, { run, capture, projectDir, push: Boolean(options.push),
464
+ platform: dependencies.platform, env: dependencies.env,
465
+ releaseMode: releaseContext.mode, log });
466
+ }
467
+ await checkDocker(run, projectDir, true, dependencies);
468
+ const results = [];
469
+ const sources = new Map();
470
+ const workspaces = new Map();
471
+ const resources = [];
472
+ const publicSnapshots = new Map();
473
+ const verifyFrozen = ({ sourceDir, commit }, name) => {
474
+ const git = (...args) => capture("git", ["-C", sourceDir, ...args]);
475
+ if (git("status", "--porcelain", "--untracked-files=all")
476
+ || git("rev-parse", "HEAD").toLowerCase() !== commit) {
477
+ throw new Error(`${name} 源码在冻结后发生变化,已停止本组构建及推送`);
478
+ }
479
+ };
480
+ let releaseError;
481
+ try {
482
+ const configuration = freezeReleaseSources(plan, {
483
+ profile, projectDir, releaseContext, push: options.push, dependencies,
484
+ sources, workspaces, publicSnapshots, resources, verifyFrozen, io, run, capture,
485
+ });
486
+ for (const item of plan) {
487
+ const built = buildTargetImage(item, {
488
+ target, configuration, projectDir, publicSnapshots, resources, verifyFrozen,
489
+ io, run, capture, log, dependencies, buildExecutableSpawn, secrets: buildSecrets.get(item.name),
490
+ });
491
+ if (item.health) {
492
+ await (dependencies.healthCheckImage || healthCheckImage)(built.image, {
493
+ cwd: projectDir, healthTimeout: String(item.health.timeoutSeconds), healthAddHost: item.health.addHost,
494
+ });
495
+ }
496
+ results.push(finishTargetImage(item, built, { target, capture, log }));
497
+ }
498
+ for (const frozen of sources.values()) verifyFrozen(frozen, frozen.sourceDir);
499
+ for (const frozen of workspaces.values()) verifyFrozen(frozen, "monorepo 构建上下文");
500
+ if (options.push) pushReleaseImages(results, { projectDir, run, capture });
501
+ } catch (error) {
502
+ releaseError = error;
503
+ } finally {
504
+ const cleanupErrors = [];
505
+ for (const resource of resources.reverse()) {
506
+ try {
507
+ // 只移除本次创建的隔离 worktree;移除失败时不删除其父目录。
508
+ if (resource.worktree) run("git", ["-C", resource.repository, "worktree", "remove", "--force", resource.worktree], { cwd: projectDir });
509
+ io.rmSync(resource.tempRoot, { recursive: true, force: true });
510
+ } catch (error) {
511
+ log(`临时构建目录清理失败,已保留恢复路径:${resource.tempRoot}`);
512
+ cleanupErrors.push(new Error(`清理失败,保留恢复路径:${resource.tempRoot}`, { cause: error }));
513
+ }
514
+ }
515
+ if (cleanupErrors.length) releaseError = new globalThis.AggregateError(
516
+ [...(releaseError ? [releaseError] : []), ...cleanupErrors],
517
+ [releaseError?.message, ...cleanupErrors.map((error) => error.message)].filter(Boolean).join(";"),
518
+ );
519
+ }
520
+ if (releaseError) throw releaseError;
521
+ for (const result of results.filter((entry) => entry.releaseId)) {
522
+ const recordRoot = path.join(projectDir, "node_modules", ".cache", "infly-releases");
523
+ io.mkdirSync(recordRoot, { recursive: true });
524
+ const record = path.join(recordRoot, `${result.releaseId}.json`);
525
+ io.writeFileSync(record, `${JSON.stringify(result, null, 2)}\n`, { flag: "wx" });
526
+ log(`release_id=${result.releaseId}`);
527
+ if (result.deployImage) log(`deploy_image=${result.deployImage}`);
528
+ log(`release_record=${record}`);
529
+ }
530
+
531
+ logReleaseSummary(results, { target, profile, push: options.push, cicdUrl, cicdLink, log, now: dependencies.now });
532
+ const report = { target, results };
533
+ if (options.output) {
534
+ io.writeFileSync(path.resolve(projectDir, options.output), `${JSON.stringify(report, null, 2)}\n`);
535
+ }
536
+ return report;
537
+ }
538
+
539
+ module.exports = { buildExecutableSpawn, compareVersions, detectReleaseContext, detectReleaseMode, normalizePreBuildCommand,
540
+ parseReleaseArgs, runReleasePreparation, runTargetRelease, validateReleaseProfile, windowsExecutable };