@infly/libs 2.7.0 → 2.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 CHANGED
@@ -147,6 +147,8 @@ infly-libs release:docker --local --health-check --health-timeout=60
147
147
 
148
148
  `infly-libs beforeBuild` 在应用未配置 `infly.buildConfigs.gitAutoPushReposBranchMap` 时,默认使用 `{ "master": "master", "develop": "develop" }`;应用显式配置的映射(包括空对象)会整体覆盖默认值,不合并分支。默认映射不会隐式启用产物仓推送;显式映射仍沿用原有启用行为,`gitAutoPushRepos: false` 始终优先。当前应用、可选产物仓、历史独立 packages 仓以及 monorepo 根仓更新均只允许 fast-forward,分支发生分叉时立即停止,不自动创建 merge commit。只需要更新应用和根仓源码的项目应显式设置 `gitAuto: false` 与 `gitAutoPushRepos: false`,避免进入产物自动提交或产物仓分支处理。兄弟应用依赖会从 `vue.config.js`、`vite.config.js/mjs/ts` 和 `next.config.js/mjs/ts` 的相对路径 alias 中静态识别,不执行配置文件;识别到的兄弟仓同样要求工作树干净并以 fast-forward-only 更新。
149
149
 
150
+ `infly-libs afterBuild` 按产物仓目标分支和输出目录查找上次构建的源码提交,摘要会过滤自动版本提交。根仓批量发布传入 Vite 的实际输出目录和构建前的源码提交,子模块单独发布使用本项目的构建配置和源码提交。产物提交只包含当前输出目录,并用 `Infly-Source-Commit` 记录本次源码提交号。旧产物提交在只涉及当前目录、完整提交说明能在源码历史中唯一匹配时可作为起点。起点无法确认时,通知会说明并附上可识别的提交摘要。
151
+
150
152
  `beforeBuild` 优先使用当前调用的显式 `--mode`:测试发布推荐 `infly-libs beforeBuild --mode staging`,正式发布推荐 `infly-libs beforeBuild --mode production`。未传参数时,按构建/发布脚本名的冒号分段识别 `test/stage/staging` 或 `pro/prod/production`,兼容现有 `build:stage`、`build:prod` 和 `release:*:test:docker`、`release:prod:docker`;不再从整条脚本的其他命令中推测环境。测试模式沿用现有映射选择测试分支,正式模式选择 `master`;环境未知或命令名同时包含两种环境字段时保留原有校验提示,Docker 发布不统一绕过确认。显式未知模式不会回退到命令名识别。
151
153
 
152
154
  受控紧急构建可使用 `--emergency` 跳过 `checks`、覆盖率文件校验和 Sonar,但必须提供 8~200 个字符且无控制字符的 `--emergency-reason`,并同时启用 `--standalone --commit-only --health-check`。紧急模式仍执行工作树干净检查、commit/revision 解析、镜像构建、健康检查和推送;缺少任一保护参数会在调用 Docker 前失败。
@@ -467,7 +469,7 @@ Jenkins 地址可在 Docker 配置顶层或单个 target 设置 `cicdUrl`。解
467
469
 
468
470
  `release:docker` 不是强制构建入口。独立源码仓可以直接使用 Dockerfile 或 Compose 构建,但若镜像要进入这里生成的部署流程,必须自行保证仓库名、不可变完整 40 位提交标签以及 `org.opencontainers.image.revision`、`org.opencontainers.image.version`、`com.infly.platform` 标签与目标配置一致;公共发布入口只是自动化这些校验和映射。部署侧仅为既有镜像保留旧 12 位标签兼容,新构建不再生成 12 位标签。
469
471
 
470
- 远端发布持锁后读取全部组件镜像基线,保存 .release-history;配置 `runtimeEnv` 时先从服务器总环境文件按白名单原子生成应用专用文件,再仅更新传入组件的服务(up -d --no-deps)。首次接入可由发布入口显式传入 `--initialize-baseline`:仅在 `deploy.env` 不存在时,从配置声明的运行中服务读取唯一且仓库匹配的 RepoDigest,保存权限受限的 `.onboarding-backup` 接入证据并原子创建基线;已有基线时拒绝覆盖,未显式初始化时仍要求基线预先存在。失败恢复镜像环境文件、应用专用环境文件及选中服务;回滚验证失败明确报错。不创建总环境文件,不创建/修改数据库,不更新未配置的基础设施。服务器不需要 npm/Node,仍需 Bash、Docker Compose 和 curl。
472
+ 远端发布持锁后读取全部组件镜像基线,保存 .release-history;配置 `runtimeEnv` 时先从服务器总环境文件按白名单原子生成应用专用文件,再仅更新传入组件的服务(up -d --no-deps)。同目录中的发布锁记录持有者 PID。若遇到遗留锁,发布停止并报告 PID 是否可访问,开发人员核对正在运行的发布与恢复状态后处理。首次接入可由发布入口显式传入 `--initialize-baseline`:仅在 `deploy.env` 不存在时,从配置声明的运行中服务读取唯一且仓库匹配的 RepoDigest,保存权限受限的 `.onboarding-backup` 接入证据并原子创建基线;已有基线时拒绝覆盖,未显式初始化时仍要求基线预先存在。失败恢复镜像环境文件、应用专用环境文件及选中服务;回滚验证失败明确报错。不创建总环境文件,不创建/修改数据库,不更新未配置的基础设施。服务器不需要 npm/Node,仍需 Bash、Docker Compose 和 curl。
471
473
 
472
474
  ### 部署仓拥有镜像打包规则
473
475
 
@@ -16,6 +16,7 @@ const { buildList } = require("../../script");
16
16
  const { init: previewInit } = require("../../adapters/vue2/project-preview.js");
17
17
  const { postVersionFileAndMsg } = require("../build-utils/webhook-single.js");
18
18
  const { resolveWebhookUrl } = require("../release-result");
19
+ const { parseBuildContext } = require("../build-utils/env");
19
20
  const { scriptWrite, targetProjectFileResolve, currentProjectFileResolve } = require("../project-files.js");
20
21
  const { shouldManageBuildScripts } = require("./script-management.js");
21
22
  const { applyBuildConfigDefaults } = require("./config.js");
@@ -43,6 +44,7 @@ const npmPackageConfigKey = "infly";
43
44
  const currentBranch = getCurrentBranch();
44
45
 
45
46
  const projectRoot = process.cwd();
47
+ const buildContext = parseBuildContext();
46
48
  // 构建配置可以位于主仓中的子目录(例如合并后的 level/)。配置、产物仍以
47
49
  // projectRoot 为基准,只有 Git 检查与分支更新定位到实际工作树根目录。
48
50
  const projectGitRoot = resolveGitWorktreeRoot(projectRoot);
@@ -77,7 +79,7 @@ const isPkg = versionFileName === "package.json";
77
79
 
78
80
  const targetProjectVueConfig = isExistVueConfigFile ? require(targetProjectVueConfigPath) : {};
79
81
  const { outputDir: vueOutputDir, configureWebpack } = targetProjectVueConfig || {};
80
- let targetProjectOutputDir = vueOutputDir;
82
+ const batchOutputDir = buildContext.targetOutputDir;
81
83
 
82
84
  const { updateDevText = "测试环境" } = { master: { updateDevText: "正式环境" } }[currentBranch] || {}; // 更新环境和处理分支
83
85
 
@@ -103,29 +105,15 @@ const {
103
105
  enableClipboard, // 启用粘贴板
104
106
  disableUpdateVersionEnv // 禁止更新版本信息环境
105
107
  } = buildConfigs || {};
106
- // Next.js 项目:优先使用 infly.buildConfigs.outputPath
107
- if (!targetProjectOutputDir && outputPath) {
108
- targetProjectOutputDir = outputPath;
109
- }
110
- if (targetProjectOutputDir && !path.isAbsolute(targetProjectOutputDir)) {
111
- targetProjectOutputDir = path.resolve(projectRoot, targetProjectOutputDir);
112
- }
113
- const buildFoldName = zipBuildFoldName || targetProjectOutputDir || "dist";
108
+ const configuredOutputDir = vueOutputDir || outputPath;
109
+ const resolvedOutputDir = configuredOutputDir && path.resolve(projectRoot, configuredOutputDir);
110
+ const targetProjectOutputDir = batchOutputDir ? path.resolve(projectRoot, batchOutputDir) : resolvedOutputDir;
111
+ const buildFoldName = zipBuildFoldName || resolvedOutputDir || "dist";
114
112
  const { mainVersion: verMainVersion, baseName, versionList = [], links } = versionConfig || {};
115
113
  const mainVersion = verMainVersion || major; // 主版本号
116
114
  const [lastestVersionItem] = versionList || [];
117
115
  const { lastVersion = projectVersion || "1.0.0" } = lastestVersionItem || {};
118
116
 
119
- function getBuildContext() {
120
- try {
121
- return JSON.parse(process.env.INFLY_BUILD_CONTEXT || "{}");
122
- } catch {
123
- return {};
124
- }
125
- }
126
-
127
- const buildContext = getBuildContext();
128
-
129
117
  function hasArg(name) {
130
118
  return process.argv.includes(name);
131
119
  }
@@ -195,6 +183,11 @@ async function init() {
195
183
  try {
196
184
  // validateConfig(buildConfig);
197
185
  validateFileExists(configPath, versionFileName);
186
+ const gitInfo = getLatestCommitInfo(projectRoot, buildContext.sourceCommit);
187
+ const { branch, commitMsg, fullHash } = gitInfo;
188
+ if (buildContext.sourceCommit && fullHash !== buildContext.sourceCommit) {
189
+ throw new Error("无法读取本次批量构建的源码提交 " + buildContext.sourceCommit);
190
+ }
198
191
 
199
192
  // 处理版本信息
200
193
  const zipFiles = handleZipFiles(`-${buildFoldName}-v`);
@@ -208,9 +201,11 @@ async function init() {
208
201
  const baseFileName = `${tempPlatformName}-${buildFoldName}-${baseName}`;
209
202
  const newVersion = isMaster ? incrementVersion(lastVersion, mainVersion) : lastVersion; // 非正式环境构建不更新版本信息
210
203
  const newFileName = baseFileName.replace("{version}", newVersion).replace("{timestamp}", timestamp);
211
- const gitInfo = getLatestCommitInfo() || {};
212
- const { branch, commitMsg } = gitInfo || {};
213
- const updateText = getBuildUpdateText(gitAutoCommitText) || commitMsg;
204
+ const updateText = getBuildUpdateText(gitAutoCommitText, projectRoot, undefined, {
205
+ sourceCommit: fullHash,
206
+ targetOutputDir: gitAutoPushRepos ? targetProjectOutputDir : undefined,
207
+ targetBranch: gitAutoPushReposBranchMap?.[branch]
208
+ }) || commitMsg;
214
209
  let tempLink = typeof links === "object" ? links[branch] : links || "";
215
210
  if (typeof tempLink === "object") {
216
211
  tempLink = tempLink[process.env.VUE_APP_PLATFORM] || tempLink["DEFAULT"] || JSON.stringify(tempLink);
@@ -230,7 +225,7 @@ async function init() {
230
225
  // 处理文件路径
231
226
  const outputDir = path.resolve(projectRoot, "./", outputPath);
232
227
  const outputPathFull = path.join(outputDir, newFileName);
233
- const distPath = gitAutoPushRepos ? targetProjectOutputDir : path.resolve(projectRoot, "./" + buildFoldName);
228
+ const distPath = gitAutoPushRepos || batchOutputDir ? targetProjectOutputDir : path.resolve(projectRoot, "./" + buildFoldName);
234
229
  // Next.js standalone 项目检查 server.js,Vue/SPA 项目检查 index.html
235
230
  const validatePath = hasNextConfig ? getNextStandaloneServerPath(distPath) : path.join(distPath, "index.html");
236
231
 
@@ -13,7 +13,24 @@ for file in "$compose_file" "$secret_env_file" "$bundle_dir/docker-compose.relea
13
13
  [[ -f "$file" ]] || { echo "部署缺少文件: $file" >&2; exit 1; }
14
14
  done
15
15
  # 先持有目录锁再读基线,避免前后端两个任务同时发布时使用过期基线。
16
- mkdir "$lock_dir" 2>/dev/null || { echo "已有发布任务持有锁: $project_dir/$lock_dir" >&2; exit 1; }
16
+ if ! mkdir "$lock_dir" 2>/dev/null; then
17
+ if [[ ! -d "$lock_dir" ]]; then
18
+ echo "无法创建发布锁: $project_dir/$lock_dir" >&2
19
+ exit 1
20
+ fi
21
+ lock_owner=""
22
+ if [[ -f "$lock_dir/pid" ]]; then IFS= read -r lock_owner < "$lock_dir/pid" || true; fi
23
+ if [[ "$lock_owner" =~ ^[1-9][0-9]*$ ]]; then
24
+ if kill -0 "$lock_owner" 2>/dev/null; then
25
+ echo "发布锁记录的 PID $lock_owner 当前可访问: $project_dir/$lock_dir" >&2
26
+ else
27
+ echo "发布锁记录的 PID $lock_owner 不可访问,可能有中断的发布,请先人工核对: $project_dir/$lock_dir" >&2
28
+ fi
29
+ else
30
+ echo "发布锁缺少有效 PID,请核对旧版本或中断任务: $project_dir/$lock_dir" >&2
31
+ fi
32
+ exit 1
33
+ fi
17
34
  next_env=""
18
35
  baseline_env_tmp=""
19
36
  runtime_env_backup=""
@@ -39,10 +56,12 @@ cleanup() {
39
56
  [[ -z "$next_env" ]] || rm -f -- "$next_env"
40
57
  [[ -z "$baseline_env_tmp" ]] || rm -f -- "$baseline_env_tmp"
41
58
  [[ -z "$runtime_env_backup" ]] || rm -f -- "$runtime_env_backup"
59
+ rm -f -- "$lock_dir/pid"
42
60
  rmdir "$lock_dir" 2>/dev/null || true
43
61
  return "$status"
44
62
  }
45
63
  trap cleanup EXIT
64
+ (umask 077; printf '%s\n' "$$" > "$lock_dir/pid")
46
65
  initialize_release_baseline() {
47
66
  [[ "$initialize_baseline" == true ]] || {
48
67
  [[ -f "$release_env_file" ]] || { echo "部署缺少文件: $release_env_file;首次接入请显式选择初始化部署基线" >&2; return 1; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infly/libs",
3
- "version": "2.7.0",
3
+ "version": "2.7.1",
4
4
  "description": "不受前端框架限制的独立工具库",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -90,11 +90,11 @@
90
90
  "@vitest/coverage-v8": "4.1.10"
91
91
  },
92
92
  "peerDependencies": {
93
- "axios": "^0.27.2",
93
+ "axios": "^0.35.0",
94
94
  "html-webpack-plugin": "^5.5.3"
95
95
  },
96
96
  "optionalDependencies": {
97
- "axios": "^0.27.2",
97
+ "axios": "^0.35.0",
98
98
  "html-webpack-plugin": "^5.5.3"
99
99
  },
100
100
  "infly": {
@@ -2,7 +2,8 @@ const { formatTerminalMessage, logTerminal } = require("../../cli/terminal-style
2
2
  const fs = require("fs");
3
3
  const path = require("path");
4
4
  const crypto = require("crypto");
5
- const { execSync, exec } = require("child_process");
5
+ const childProcess = require("child_process");
6
+ const { execSync, exec } = childProcess;
6
7
  const { promisify } = require("util");
7
8
  const { getGitCommonDir } = require("./git-utils");
8
9
  const execAsync = promisify(exec);
@@ -19,30 +20,37 @@ function getCurrentBranch() {
19
20
  * 获取 Git 提交信息
20
21
  * @returns {Object} 包含提交信息的对象,如果获取失败则返回空对象
21
22
  */
22
- function getLatestCommitInfo(cwd = process.cwd()) {
23
+ function getLatestCommitInfo(cwd = process.cwd(), sourceCommit = "HEAD") {
24
+ let fullHash;
25
+ try {
26
+ fullHash = readGit(cwd, ["rev-parse", "--verify", "--end-of-options", sourceCommit + "^{commit}"]).trim();
27
+ } catch (error) {
28
+ logTerminal("error", "无法读取构建源码提交:" + error.message);
29
+ return {};
30
+ }
31
+
23
32
  // 定义 Git 命令
24
33
  const commands = {
25
34
  // 构建元数据必须全部对应源码 HEAD。跳过 merge commit 会导致 fullHash 指向
26
35
  // 当前合并提交,而文案、作者却回退到更早的版本构建提交。
27
- commitMsg: "git log -1 --pretty=%B",
28
- branch: "git rev-parse --abbrev-ref HEAD",
29
- fullHash: "git rev-parse HEAD",
30
- author: "git log -1 --pretty=%an",
31
- email: "git log -1 --pretty=%ae",
32
- date: "git log -1 --pretty=%cd --date=iso"
36
+ commitMsg: ["log", "-1", "--pretty=%B", fullHash],
37
+ branch: ["rev-parse", "--abbrev-ref", "HEAD"],
38
+ author: ["log", "-1", "--pretty=%an", fullHash],
39
+ email: ["log", "-1", "--pretty=%ae", fullHash],
40
+ date: ["log", "-1", "--pretty=%cd", "--date=iso", fullHash]
33
41
  };
34
42
 
35
43
  // 结果对象
36
- const commitInfo = {};
44
+ const commitInfo = { fullHash };
37
45
 
38
46
  try {
39
47
  // 检查当前目录是否是 Git 仓库
40
- execSync("git rev-parse --is-inside-work-tree", { cwd, stdio: "ignore" });
48
+ readGit(cwd, ["rev-parse", "--is-inside-work-tree"]);
41
49
 
42
50
  // 遍历命令并执行
43
51
  for (const [key, command] of Object.entries(commands)) {
44
52
  try {
45
- commitInfo[key] = execSync(`${command}`, { cwd, encoding: "utf-8" }).trim();
53
+ commitInfo[key] = readGit(cwd, command).trim();
46
54
  } catch (cmdError) {
47
55
  logTerminal("warning", `获取 Git 信息失败(${key}):${cmdError.message}`);
48
56
  commitInfo[key] = ""; // 失败时设置为空字符串
@@ -67,9 +75,20 @@ function createCommitTextMatcher(template = "") {
67
75
  return new RegExp(`^${escapedParts.join(".+?")}$`);
68
76
  }
69
77
 
78
+ const SOURCE_COMMIT_TRAILER = "Infly-Source-Commit";
79
+ const COMMIT_HASH = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
80
+ const DEFAULT_BUILD_SUBJECT = /^build: 更新版本为v\S+ --build by @infly\/libs$/;
81
+ const NO_SOURCE_CHANGES = "无源码提交变更";
82
+ const UNKNOWN_ARTIFACT_BASELINE = "上次该产物的源码提交无法确认";
83
+
84
+ function readGit(cwd, args) {
85
+ return childProcess.execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
86
+ }
87
+
70
88
  function isAncestorCommit(ancestor, descendant, cwd) {
89
+ if (!COMMIT_HASH.test(ancestor)) return false;
71
90
  try {
72
- execSync(`git merge-base --is-ancestor ${ancestor} ${descendant}`, { cwd, stdio: "ignore" });
91
+ readGit(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]);
73
92
  return true;
74
93
  } catch {
75
94
  return false;
@@ -80,10 +99,8 @@ function isAncestorCommit(ancestor, descendant, cwd) {
80
99
  * 将侧分支上的版本提交映射到它首次进入当前分支第一父链的合并提交。
81
100
  * 否则 `versionCommit..HEAD` 会把当前分支上与侧分支互不为祖先的大量旧提交误算为本次更新。
82
101
  */
83
- function resolveBuildSummaryBaseline(versionCommit, cwd) {
84
- if (!/^[0-9a-f]{40}$/i.test(versionCommit)) return versionCommit;
85
-
86
- const firstParentHistory = execSync("git rev-list --first-parent HEAD", { cwd, encoding: "utf-8" })
102
+ function resolveBuildSummaryBaseline(versionCommit, cwd, head) {
103
+ const firstParentHistory = readGit(cwd, ["rev-list", "--first-parent", head])
87
104
  .trim()
88
105
  .split(/\r?\n/)
89
106
  .filter(Boolean);
@@ -128,61 +145,94 @@ function deduplicateCommitSubjects(subjects) {
128
145
  });
129
146
  }
130
147
 
131
- function getHeadParents(cwd) {
132
- const headWithParents = execSync("git rev-list --parents -n 1 HEAD", { cwd, encoding: "utf-8" }).trim();
148
+ function getHeadParents(cwd, head) {
149
+ const headWithParents = readGit(cwd, ["rev-list", "--parents", "-n", "1", head]).trim();
133
150
  return headWithParents ? headWithParents.split(/\s+/).slice(1) : [];
134
151
  }
135
152
 
153
+ function getPreviousArtifactSource(cwd, head, outputDir, branch) {
154
+ try {
155
+ const previous = readGit(outputDir, ["log", "-1", "--first-parent", "--format=%H",
156
+ `refs/remotes/origin/${branch}`, "--", "."]).trim();
157
+ if (!COMMIT_HASH.test(previous)) return "";
158
+
159
+ const prefix = readGit(outputDir, ["rev-parse", "--show-prefix"]).trimEnd();
160
+ if (prefix) {
161
+ // 旧构建会把兄弟目录一起提交,其提交说明无法证明当前端使用的是哪份源码。
162
+ const files = readGit(outputDir, ["diff-tree", "--root", "--no-commit-id", "--name-only",
163
+ "--no-renames", "-r", "-z", previous]).split("\0").filter(Boolean);
164
+ if (!files.length || files.some((file) => !file.startsWith(prefix))) return "";
165
+ }
166
+
167
+ const [trailers, body] = readGit(outputDir, ["show", "-s",
168
+ `--format=%(trailers:key=${SOURCE_COMMIT_TRAILER},valueonly,separator=%x1f)%x00%B`, previous]).split("\0");
169
+ const recorded = trailers.split("\x1f").at(-1).trim();
170
+ if (trailers.trim()) return isAncestorCommit(recorded, head, cwd) ? recorded : "";
171
+
172
+ // 兼容旧产物提交复制源码提交说明的行为,只接受完整说明在当前源码历史中唯一匹配。
173
+ const message = body.trim();
174
+ if (!message) return "";
175
+ const records = readGit(cwd, ["log", "--format=%H%x00%B%x00", "--fixed-strings",
176
+ `--grep=${message.split(/\r?\n/, 1)[0]}`, head]).split("\0");
177
+ const matches = [];
178
+ for (let index = 0; index + 1 < records.length; index += 2) {
179
+ const hash = records[index].trim();
180
+ if (COMMIT_HASH.test(hash) && records[index + 1].trim() === message) matches.push(hash);
181
+ }
182
+ return matches.length === 1 ? matches[0] : "";
183
+ } catch {
184
+ return "";
185
+ }
186
+ }
187
+
188
+ function getLegacySummaryRange(matcher, cwd, head, parents) {
189
+ if (!matcher) return "";
190
+ const history = readGit(cwd, ["log", "--format=%H%x1f%s", head]).split(/\r?\n/);
191
+ const previous = history.map((line) => line.split("\x1f", 2))
192
+ .find(([hash, subject]) => COMMIT_HASH.test(hash) && matcher.test(subject));
193
+ if (!previous) return "";
194
+
195
+ // 缺少产物基线时,沿用合并构建展示本次合入内容的历史口径。
196
+ const baseline = parents.length > 1 ? parents[0] : resolveBuildSummaryBaseline(previous[0], cwd, head);
197
+ return `${baseline}..${head}`;
198
+ }
199
+
136
200
  /**
137
- * 获取上一次自动版本提交之后的业务提交摘要。
138
- * Merge 提交只描述 Git 操作,不作为企业微信中的更新内容。
139
- * @param {String} gitAutoCommitText 自动版本提交模板
140
- * @param {String} cwd Git 仓库目录
141
- * @param {Number} limit 最多展示的提交数
142
- * @returns {String} 构建更新摘要;无法识别版本基线时返回空字符串
201
+ * 产物仓发布按目标分支和目录比较源码;旧构建保留源码仓版本范围作为参考。
143
202
  */
144
- function getBuildUpdateText(gitAutoCommitText, cwd = process.cwd(), limit = 10) {
203
+ function getBuildUpdateText(gitAutoCommitText, cwd = process.cwd(), limit = 10, options = {}) {
145
204
  const matcher = createCommitTextMatcher(gitAutoCommitText);
146
- if (!matcher) return "";
205
+ const { sourceCommit, targetOutputDir, targetBranch } = options;
206
+ const head = COMMIT_HASH.test(sourceCommit) ? sourceCommit : "HEAD";
207
+ const hasArtifact = Boolean(targetOutputDir && targetBranch);
208
+ if (!matcher && !hasArtifact) return "";
147
209
 
148
210
  try {
149
- const history = execSync("git log --format=%H%x1f%s", { cwd, encoding: "utf-8" })
211
+ const baseline = hasArtifact ? getPreviousArtifactSource(cwd, head, targetOutputDir, targetBranch) : "";
212
+ const parents = baseline ? [] : getHeadParents(cwd, head);
213
+ const unknownBaseline = hasArtifact && !baseline;
214
+ const range = baseline ? `${baseline}..${head}`
215
+ : getLegacySummaryRange(matcher, cwd, head, parents) || (unknownBaseline && parents.length > 1 ? `${parents[0]}..${head}` : "");
216
+ if (!range && !unknownBaseline) return "";
217
+
218
+ const logArgs = range ? [range] : ["-1", head];
219
+ const history = readGit(cwd, ["log", "--no-merges", "--format=%s", ...logArgs]);
220
+ const subjects = deduplicateCommitSubjects(history
150
221
  .trim()
151
222
  .split(/\r?\n/)
152
- .filter(Boolean)
153
- .map((line) => {
154
- const separatorIndex = line.indexOf("\x1f");
155
- return {
156
- hash: line.slice(0, separatorIndex),
157
- subject: line.slice(separatorIndex + 1)
158
- };
159
- });
160
- const previousBuild = history.find(({ hash, subject }) => /^[0-9a-f]{40}$/i.test(hash) && matcher.test(subject));
161
-
162
- if (!previousBuild) return "";
223
+ .filter((subject) => subject && !matcher?.test(subject) && !DEFAULT_BUILD_SUBJECT.test(subject)));
163
224
 
164
- const baseline = resolveBuildSummaryBaseline(previousBuild.hash, cwd);
165
- // 构建正好发生在 Merge HEAD 时,更新内容应描述本次合入的分支,而不是第一父链上更早的待发布提交。
166
- const headParents = getHeadParents(cwd);
167
- const range = headParents.length > 1 ? `${headParents[0]}..HEAD` : `${baseline}..HEAD`;
168
- const subjects = deduplicateCommitSubjects(execSync(`git log --no-merges --format=%s ${range}`, {
169
- cwd,
170
- encoding: "utf-8"
171
- })
172
- .trim()
173
- .split(/\r?\n/)
174
- .filter(Boolean));
175
-
176
- if (subjects.length === 0) return "无源码提交变更";
225
+ if (subjects.length === 0) return unknownBaseline ? UNKNOWN_ARTIFACT_BASELINE : NO_SOURCE_CHANGES;
177
226
 
178
227
  const visibleSubjects = subjects.slice(0, limit);
179
228
  if (subjects.length > limit) {
180
229
  visibleSubjects.push(`...另 ${subjects.length - limit} 条提交`);
181
230
  }
182
- return visibleSubjects.map((subject) => `- ${subject}`).join("\n");
231
+ const summary = visibleSubjects.map((subject) => `- ${subject}`).join("\n");
232
+ return unknownBaseline ? `${UNKNOWN_ARTIFACT_BASELINE},以下为可识别的提交\n${summary}` : summary;
183
233
  } catch (error) {
184
234
  logTerminal("warning", `获取构建更新摘要失败:${error.message}`);
185
- return "";
235
+ return hasArtifact ? UNKNOWN_ARTIFACT_BASELINE : "";
186
236
  }
187
237
  }
188
238
 
@@ -261,10 +311,12 @@ function checkGitStatus(excludeDir, extraFilter, extraParams) {
261
311
 
262
312
  try {
263
313
  // 获取所有未跟踪和已修改的文件列表
264
- const files = execSync(`git${targetProjectOutputDirCmd} status --porcelain -z`, { encoding: "utf8" })
265
- .toString()
314
+ if (targetProjectOutputDirCmd && !targetProjectOutputDir) throw new Error("未配置构建产物目录");
315
+ const scope = targetProjectOutputDirCmd ? ["--", "."] : [];
316
+ const status = readGit(targetProjectOutputDirCmd ? targetProjectOutputDir : process.cwd(), ["status", "--porcelain", "-z", ...scope]);
317
+ const files = status
266
318
  .split("\u0000")
267
- .filter((file) => file.trim() && isBuildFile(targetProjectOutputDir, file));
319
+ .filter((file) => file.trim() && (targetProjectOutputDirCmd || isBuildFile(targetProjectOutputDir, file)));
268
320
  const excludeFiles = []; // 非指定构建相关文件
269
321
  const includeFiles = []; // 指定的构建相关文件
270
322
 
@@ -302,10 +354,10 @@ function checkGitStatus(excludeDir, extraFilter, extraParams) {
302
354
 
303
355
  function runGitCommand(command, options = {}) {
304
356
  try {
305
- const result = execSync(command, {
306
- ...options,
307
- encoding: "utf8"
308
- });
357
+ const commandOptions = { ...options, encoding: "utf8" };
358
+ const result = Array.isArray(command)
359
+ ? childProcess.execFileSync("git", command, commandOptions)
360
+ : execSync(command, commandOptions);
309
361
  if (result) {
310
362
  return result.trim();
311
363
  }
@@ -315,14 +367,13 @@ function runGitCommand(command, options = {}) {
315
367
  }
316
368
  }
317
369
 
318
- function hasStagedChanges(targetProjectOutputDirCmd = "") {
370
+ function hasStagedChanges(scope, options) {
319
371
  try {
320
- execSync(`git${targetProjectOutputDirCmd} diff --cached --quiet`, {
321
- stdio: "ignore"
322
- });
372
+ childProcess.execFileSync("git", ["diff", "--cached", "--quiet", ...scope], { ...options, stdio: "ignore" });
323
373
  return false;
324
374
  } catch (error) {
325
- return error.status === 1;
375
+ if (error.status === 1) return true;
376
+ throw error;
326
377
  }
327
378
  }
328
379
 
@@ -380,7 +431,6 @@ function autoGitProcess(buildFoldName, newFileName, extraParams = {}) {
380
431
  gitAutoPushRepos,
381
432
  targetProjectOutputDir,
382
433
  gitAutoPushReposBranchMap = {},
383
- targetProjectOutputDirCmd = gitAutoPushRepos ? ` -C ${targetProjectOutputDir}` : "",
384
434
  projectName,
385
435
  gitLockDir,
386
436
  gitProcessOrder
@@ -400,18 +450,12 @@ function autoGitProcess(buildFoldName, newFileName, extraParams = {}) {
400
450
  runAppGitProcess();
401
451
  }
402
452
 
403
- const { commitMsg, branch } = gitInfo || {};
453
+ const { commitMsg, branch, fullHash } = gitInfo || {};
404
454
  const gitRepos = gitAutoPushRepos ? `构建仓库: ${targetProjectOutputDir}` : `当前项目: ${projectName}`;
405
- let tempGitAutoCommitText = gitAutoCommitText ? gitAutoCommitText.replace("{version}", newVersion) : "";
406
-
407
- if (gitAutoPushRepos) {
408
- tempGitAutoCommitText = commitMsg;
409
- }
410
-
411
455
  const tempBranch = gitAutoPushRepos ? gitAutoPushReposBranchMap[branch] : branch;
412
- const addCmd = `git${targetProjectOutputDirCmd} add -A`;
413
- const commitCmd = `git${targetProjectOutputDirCmd} commit -m "${tempGitAutoCommitText}"`;
414
- const pushCommand = `git${targetProjectOutputDirCmd} push origin ${tempBranch}`;
456
+ const commitText = gitAutoPushRepos ? String(commitMsg || "") : (gitAutoCommitText || "").replace("{version}", newVersion);
457
+ const gitOptions = gitAutoPushRepos ? { cwd: targetProjectOutputDir } : {};
458
+ const scope = gitAutoPushRepos ? ["--", "."] : [];
415
459
 
416
460
  if (!tempBranch) {
417
461
  logTerminal("error", `缺少分支配置`);
@@ -425,13 +469,20 @@ function autoGitProcess(buildFoldName, newFileName, extraParams = {}) {
425
469
  return;
426
470
  }
427
471
 
428
- runGitCommand(addCmd);
429
- if (!hasStagedChanges(targetProjectOutputDirCmd)) {
472
+ runGitCommand(["add", "-A", ...scope], gitOptions);
473
+ if (!hasStagedChanges(scope, gitOptions)) {
430
474
  logTerminal("warning", `Git ${gitRepos} 没有可提交的变更,跳过自动提交`);
431
- } else {
432
- runGitCommand(commitCmd);
433
- runGitCommand(pushCommand);
475
+ return;
434
476
  }
477
+
478
+ const commitArgs = ["commit", "-m", commitText];
479
+ if (gitAutoPushRepos) {
480
+ if (COMMIT_HASH.test(fullHash)) commitArgs.push("--trailer", `${SOURCE_COMMIT_TRAILER}: ${fullHash}`);
481
+ // 同仓可能同时生成多个端的产物,只提交当前目录,避免给兄弟端写错源码基线。
482
+ commitArgs.push("--only", ...scope);
483
+ }
484
+ runGitCommand(commitArgs, gitOptions);
485
+ runGitCommand(["push", "origin", tempBranch], gitOptions);
435
486
  };
436
487
 
437
488
  if (gitAutoPushRepos) {
@@ -454,13 +505,11 @@ async function autoBranchProcess(config) {
454
505
  const { gitAutoPushRepos, gitAutoPushReposBranchMap, currentBranch, targetProjectOutputDir, validateConfig } =
455
506
  config || {};
456
507
  const tempBranch = gitAutoPushRepos ? gitAutoPushReposBranchMap[currentBranch] : currentBranch;
457
- const targetProjectOutputDirCmd = gitAutoPushRepos ? ` -C ${targetProjectOutputDir}` : "";
458
- const checkoutCmd = `git${targetProjectOutputDirCmd} checkout ${tempBranch}`;
459
- const pullCmd = `git${targetProjectOutputDirCmd} pull --ff-only origin ${tempBranch}`;
508
+ const gitOptions = gitAutoPushRepos ? { cwd: targetProjectOutputDir } : {};
460
509
  const fileList = checkGitStatus(undefined, undefined, {
461
510
  onlyCheckStatus: true,
462
511
  targetProjectOutputDir,
463
- targetProjectOutputDirCmd,
512
+ gitAutoPushRepos,
464
513
  startLogText: "Git自动化开始执行..."
465
514
  });
466
515
 
@@ -478,8 +527,8 @@ async function autoBranchProcess(config) {
478
527
  process.exit(1);
479
528
  }
480
529
 
481
- runGitCommand(checkoutCmd);
482
- runGitCommand(pullCmd);
530
+ runGitCommand(["checkout", tempBranch], gitOptions);
531
+ runGitCommand(["pull", "--ff-only", "origin", tempBranch], gitOptions);
483
532
  }
484
533
 
485
534
  /**