@infly/libs 2.6.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.
@@ -1,828 +1,862 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const crypto = require("crypto");
4
- const { execSync, exec } = require("child_process");
5
- const { promisify } = require("util");
6
- const { getGitCommonDir } = require("./git-utils");
7
- const execAsync = promisify(exec);
8
-
9
- /**
10
- * 获取当前 Git 分支名称
11
- * @returns
12
- */
13
- function getCurrentBranch() {
14
- return execSync("git rev-parse --abbrev-ref HEAD").toString().trim();
15
- }
16
-
17
- /**
18
- * 获取 Git 提交信息
19
- * @returns {Object} 包含提交信息的对象,如果获取失败则返回空对象
20
- */
21
- function getLatestCommitInfo(cwd = process.cwd()) {
22
- // 定义 Git 命令
23
- const commands = {
24
- // 构建元数据必须全部对应源码 HEAD。跳过 merge commit 会导致 fullHash 指向
25
- // 当前合并提交,而文案、作者却回退到更早的版本构建提交。
26
- commitMsg: "git log -1 --pretty=%B",
27
- branch: "git rev-parse --abbrev-ref HEAD",
28
- fullHash: "git rev-parse HEAD",
29
- author: "git log -1 --pretty=%an",
30
- email: "git log -1 --pretty=%ae",
31
- date: "git log -1 --pretty=%cd --date=iso"
32
- };
33
-
34
- // 结果对象
35
- const commitInfo = {};
36
-
37
- try {
38
- // 检查当前目录是否是 Git 仓库
39
- execSync("git rev-parse --is-inside-work-tree", { cwd, stdio: "ignore" });
40
-
41
- // 遍历命令并执行
42
- for (const [key, command] of Object.entries(commands)) {
43
- try {
44
- commitInfo[key] = execSync(`${command}`, { cwd, encoding: "utf-8" }).trim();
45
- } catch (cmdError) {
46
- console.warn(global.logColor.warning, `⚠️️ 获取 Git 信息失败(${key}):${cmdError.message}`);
47
- commitInfo[key] = ""; // 失败时设置为空字符串
48
- }
49
- }
50
- } catch (error) {
51
- console.error(
52
- global.logColor.error,
53
- `❌ 获取 Git 信息失败:当前目录不是 Git 仓库或 Git 未安装。错误信息:${error.message}`
54
- );
55
- return {}; // 返回空对象
56
- }
57
-
58
- return commitInfo;
59
- }
60
-
61
- function createCommitTextMatcher(template = "") {
62
- if (!template) return null;
63
-
64
- const escapedParts = template
65
- .split("{version}")
66
- .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
67
- return new RegExp(`^${escapedParts.join(".+?")}$`);
68
- }
69
-
70
- function isAncestorCommit(ancestor, descendant, cwd) {
71
- try {
72
- execSync(`git merge-base --is-ancestor ${ancestor} ${descendant}`, { cwd, stdio: "ignore" });
73
- return true;
74
- } catch {
75
- return false;
76
- }
77
- }
78
-
79
- /**
80
- * 将侧分支上的版本提交映射到它首次进入当前分支第一父链的合并提交。
81
- * 否则 `versionCommit..HEAD` 会把当前分支上与侧分支互不为祖先的大量旧提交误算为本次更新。
82
- */
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" })
87
- .trim()
88
- .split(/\r?\n/)
89
- .filter(Boolean);
90
-
91
- if (firstParentHistory.includes(versionCommit)) return versionCommit;
92
-
93
- // 第一父链从新到旧排列;“包含版本提交”在链上形成连续前缀,可以二分找到最早引入点。
94
- let low = 0;
95
- let high = firstParentHistory.length - 1;
96
- let oldestContainingIndex = -1;
97
- while (low <= high) {
98
- const middle = Math.floor((low + high) / 2);
99
- if (isAncestorCommit(versionCommit, firstParentHistory[middle], cwd)) {
100
- oldestContainingIndex = middle;
101
- low = middle + 1;
102
- } else {
103
- high = middle - 1;
104
- }
105
- }
106
-
107
- return oldestContainingIndex >= 0 ? firstParentHistory[oldestContainingIndex] : versionCommit;
108
- }
109
-
110
- function getCommitSubjectKey(subject) {
111
- const workItem = subject.match(/#[a-z][a-z0-9]*-\d+\b/i)?.[0];
112
- if (workItem) return `work-item:${workItem.toUpperCase()}`;
113
-
114
- return subject
115
- .trim()
116
- .replace(/\s+/g, " ")
117
- .replace(/\s+([,.;:!?#])/g, "$1")
118
- .toLowerCase();
119
- }
120
-
121
- function deduplicateCommitSubjects(subjects) {
122
- const seen = new Set();
123
- return subjects.filter((subject) => {
124
- const key = getCommitSubjectKey(subject);
125
- if (seen.has(key)) return false;
126
- seen.add(key);
127
- return true;
128
- });
129
- }
130
-
131
- function getHeadParents(cwd) {
132
- const headWithParents = execSync("git rev-list --parents -n 1 HEAD", { cwd, encoding: "utf-8" }).trim();
133
- return headWithParents ? headWithParents.split(/\s+/).slice(1) : [];
134
- }
135
-
136
- /**
137
- * 获取上一次自动版本提交之后的业务提交摘要。
138
- * Merge 提交只描述 Git 操作,不作为企业微信中的更新内容。
139
- * @param {String} gitAutoCommitText 自动版本提交模板
140
- * @param {String} cwd Git 仓库目录
141
- * @param {Number} limit 最多展示的提交数
142
- * @returns {String} 构建更新摘要;无法识别版本基线时返回空字符串
143
- */
144
- function getBuildUpdateText(gitAutoCommitText, cwd = process.cwd(), limit = 10) {
145
- const matcher = createCommitTextMatcher(gitAutoCommitText);
146
- if (!matcher) return "";
147
-
148
- try {
149
- const history = execSync("git log --format=%H%x1f%s", { cwd, encoding: "utf-8" })
150
- .trim()
151
- .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 "";
163
-
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 "无源码提交变更";
177
-
178
- const visibleSubjects = subjects.slice(0, limit);
179
- if (subjects.length > limit) {
180
- visibleSubjects.push(`...另 ${subjects.length - limit} 条提交`);
181
- }
182
- return visibleSubjects.map((subject) => `- ${subject}`).join("\n");
183
- } catch (error) {
184
- console.warn(global.logColor.warning, `⚠️️ 获取构建更新摘要失败:${error.message}`);
185
- return "";
186
- }
187
- }
188
-
189
- /**
190
- * 获取指定文件的最后一次提交信息
191
- * @param {String} filePath - 文件路径
192
- * @returns {Object|null} 包含提交信息的对象,如果获取失败则返回 null
193
- */
194
- function getLastCommitByFile(filePath) {
195
- try {
196
- // 执行 Git 命令获取最后一次提交信息‌:ml-citation{ref="3,5" data="citationList"}
197
- const cmd = `git log -1 --format="%H|%an|%ae|%at|%s" -- ${filePath}`;
198
- const output = execSync(cmd, { encoding: "utf8" }).trim();
199
- if (!output) return null;
200
-
201
- // 解析提交信息‌:ml-citation{ref="1,5" data="citationList"}
202
- const [hash, author, email, timestamp, message] = output.split("|");
203
- return {
204
- commitMsg: message.trim(),
205
- hash,
206
- author,
207
- email,
208
- date: new Date(parseInt(timestamp) * 1000).toISOString()
209
- };
210
- } catch {
211
- return null;
212
- }
213
- }
214
-
215
- /**
216
- * 检查是否构建文件
217
- * @param {String} targetProjectOutputDir 构建文件输出绝对路径
218
- * @param {String} gitStatusLine 带文件状态的
219
- * @returns
220
- */
221
- function isBuildFile(targetProjectOutputDir = "", gitLine = "", sliceLen = -1) {
222
- if (!targetProjectOutputDir) {
223
- return true;
224
- }
225
- // 统一路径分隔符
226
- targetProjectOutputDir = targetProjectOutputDir.replace(/\\/g, "/");
227
-
228
- // 取目录的最后 N 级,比如 frontend/ea
229
- const dirFragment = targetProjectOutputDir.split("/").slice(sliceLen).join("/");
230
-
231
- // 去掉状态前缀 (M, A, D, ?? 等)
232
- const gitPath = gitLine.trim().slice(2).trim();
233
-
234
- // 判断是否以 dirFragment 开头
235
- return gitPath.startsWith(dirFragment + "/");
236
- }
237
-
238
- /**
239
- * 检查 Git 状态
240
- * @param {String} excludeDir - 排除的目录
241
- * @param {String} extraFilter - 额外过滤条件
242
- * @param {Object} extraParams - 额外的配置
243
- */
244
- function checkGitStatus(excludeDir, extraFilter, extraParams) {
245
- const {
246
- deleteOldFile = [],
247
- versionFileName = "version-config.json",
248
- gitAutoPushRepos,
249
- targetProjectOutputDir,
250
- targetProjectOutputDirCmd = gitAutoPushRepos ? ` -C ${targetProjectOutputDir}` : "",
251
- onlyCheckStatus,
252
- startLogText = "Git自动提交开始执行, 正在检查非构建文件"
253
- } = extraParams || {};
254
-
255
- // 如果指定了构建输出目录但目录不存在,则自动创建并初始化 Git 仓库
256
- if (targetProjectOutputDir && !fs.existsSync(targetProjectOutputDir)) {
257
- console.log(global.logColor.warning, `⚠️ 构建目录不存在,正在自动创建:${targetProjectOutputDir}`);
258
- fs.mkdirSync(targetProjectOutputDir, { recursive: true });
259
- console.log(global.logColor.success, `✅ 构建目录已创建并初始化 Git 仓库:${targetProjectOutputDir}`);
260
- }
261
-
262
- try {
263
- // 获取所有未跟踪和已修改的文件列表
264
- const files = execSync(`git${targetProjectOutputDirCmd} status --porcelain -z`, { encoding: "utf8" })
265
- .toString()
266
- .split("\u0000")
267
- .filter((file) => file.trim() && isBuildFile(targetProjectOutputDir, file));
268
- const excludeFiles = []; // 非指定构建相关文件
269
- const includeFiles = []; // 指定的构建相关文件
270
-
271
- if (onlyCheckStatus || targetProjectOutputDirCmd) {
272
- return files || [];
273
- }
274
-
275
- console.log(global.logColor.success, `🚀 ${startLogText}`);
276
-
277
- // 进行当前项目文件检查,如果有其它非配置文件则取消自动提交改为用户手动确认
278
- files.forEach((file) => {
279
- const existsDelFile = deleteOldFile.find((item) => file.includes(item));
280
- if (
281
- file.includes(`${excludeDir}/`) ||
282
- file.includes(versionFileName) ||
283
- file.includes(extraFilter) ||
284
- existsDelFile
285
- ) {
286
- includeFiles.push(file);
287
- } else {
288
- excludeFiles.push(file);
289
- }
290
- });
291
-
292
- if (excludeFiles.length > 0) {
293
- throw new Error(`存在非构建文件未提交,请手动确定提交信息,本次自动提交终止\n${excludeFiles.join("\n")}`);
294
- }
295
-
296
- return includeFiles || [];
297
- } catch (err) {
298
- console.error(global.logColor.error, `❌ 自动化构建Git状态检查存在问题:${err.message}`);
299
- process.exit(1);
300
- }
301
- }
302
-
303
- function runGitCommand(command, options = {}) {
304
- try {
305
- const result = execSync(command, {
306
- ...options,
307
- encoding: "utf8"
308
- });
309
- if (result) {
310
- return result.trim();
311
- }
312
- } catch (error) {
313
- console.error(global.logColor.error, `❌ 执行 Git 命令失败:${error.message}`);
314
- process.exit(1);
315
- }
316
- }
317
-
318
- function hasStagedChanges(targetProjectOutputDirCmd = "") {
319
- try {
320
- execSync(`git${targetProjectOutputDirCmd} diff --cached --quiet`, {
321
- stdio: "ignore"
322
- });
323
- return false;
324
- } catch (error) {
325
- return error.status === 1;
326
- }
327
- }
328
-
329
- function sleepSync(ms) {
330
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
331
- }
332
-
333
- function withGitRepoLock(lockDir, lockKey, task) {
334
- if (!lockDir || !lockKey) {
335
- return task();
336
- }
337
-
338
- fs.mkdirSync(lockDir, { recursive: true });
339
- const lockName = crypto.createHash("md5").update(lockKey).digest("hex");
340
- const lockPath = path.join(lockDir, `${lockName}.lock`);
341
- const startTime = Date.now();
342
- const timeout = 10 * 60 * 1000;
343
-
344
- while (true) {
345
- try {
346
- fs.mkdirSync(lockPath);
347
- break;
348
- } catch (error) {
349
- if (error.code !== "EEXIST") {
350
- throw error;
351
- }
352
-
353
- if (Date.now() - startTime > timeout) {
354
- throw new Error(`等待 Git 仓库锁超时: ${lockKey}`);
355
- }
356
-
357
- sleepSync(500);
358
- }
359
- }
360
-
361
- try {
362
- return task();
363
- } finally {
364
- fs.rmSync(lockPath, { recursive: true, force: true });
365
- }
366
- }
367
-
368
- /**
369
- * git自动推送
370
- * @param {String} buildFoldName 构建文件名称
371
- * @param {String} newFileName 新压缩文件名
372
- * @param {Object} extraParams 额外的参数
373
- * @returns
374
- */
375
- function autoGitProcess(buildFoldName, newFileName, extraParams = {}) {
376
- const {
377
- newVersion,
378
- gitInfo = {},
379
- gitAutoCommitText = gitInfo.commitMsg,
380
- gitAutoPushRepos,
381
- targetProjectOutputDir,
382
- gitAutoPushReposBranchMap = {},
383
- targetProjectOutputDirCmd = gitAutoPushRepos ? ` -C ${targetProjectOutputDir}` : "",
384
- projectName,
385
- gitLockDir,
386
- gitProcessOrder
387
- } = extraParams || {};
388
- const appFirst = gitAutoPushRepos && gitProcessOrder === "app-first";
389
- const runAppGitProcess = () => {
390
- const overrideParams = {
391
- ...extraParams,
392
- targetProjectOutputDir: "",
393
- targetProjectOutputDirCmd: "",
394
- gitAutoPushRepos: false
395
- };
396
- autoGitProcess(buildFoldName, newFileName, overrideParams);
397
- };
398
-
399
- if (appFirst) {
400
- runAppGitProcess();
401
- }
402
-
403
- const { commitMsg, branch } = gitInfo || {};
404
- const gitRepos = gitAutoPushRepos ? `构建仓库: ${targetProjectOutputDir}` : `当前项目: ${projectName}`;
405
- let tempGitAutoCommitText = gitAutoCommitText ? gitAutoCommitText.replace("{version}", newVersion) : "";
406
-
407
- if (gitAutoPushRepos) {
408
- tempGitAutoCommitText = commitMsg;
409
- }
410
-
411
- 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}`;
415
-
416
- if (!tempBranch) {
417
- console.log(global.logColor.error, `❌ 缺少分支配置`);
418
- return;
419
- }
420
-
421
- const checkCommitAndPush = () => {
422
- const fileList = checkGitStatus(buildFoldName, newFileName, extraParams) || [];
423
-
424
- if (fileList.length === 0) {
425
- return;
426
- }
427
-
428
- runGitCommand(addCmd);
429
- if (!hasStagedChanges(targetProjectOutputDirCmd)) {
430
- console.log(global.logColor.warning, `⚠️ Git ${gitRepos} 没有可提交的变更,跳过自动提交`);
431
- } else {
432
- runGitCommand(commitCmd);
433
- runGitCommand(pushCommand);
434
- }
435
- };
436
-
437
- if (gitAutoPushRepos) {
438
- withGitRepoLock(gitLockDir, getGitCommonDir(targetProjectOutputDir), checkCommitAndPush);
439
- } else {
440
- checkCommitAndPush();
441
- }
442
-
443
- if (gitAutoPushRepos && !appFirst) {
444
- runAppGitProcess();
445
- }
446
-
447
- console.log(global.logColor.success, `✅ Git \x1b[34m${gitRepos}\x1b[32m 自动提交和推送成功!`);
448
- }
449
- /**
450
- * 自动分支处理
451
- * @param {Object} config - 分支配置
452
- */
453
- async function autoBranchProcess(config) {
454
- const { gitAutoPushRepos, gitAutoPushReposBranchMap, currentBranch, targetProjectOutputDir, validateConfig } =
455
- config || {};
456
- 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}`;
460
- const fileList = checkGitStatus(undefined, undefined, {
461
- onlyCheckStatus: true,
462
- targetProjectOutputDir,
463
- targetProjectOutputDirCmd,
464
- startLogText: "Git自动化开始执行..."
465
- });
466
-
467
- if (validateConfig && typeof validateConfig === "function") {
468
- validateConfig();
469
- }
470
-
471
- if (!tempBranch) {
472
- console.error(global.logColor.error, `❌ 缺少项目分支对应构建仓库分支配置,当前分支:${currentBranch},请检查`);
473
- process.exit(1);
474
- }
475
-
476
- if (fileList.length > 0) {
477
- console.error(global.logColor.error, `❌ 构建仓库 ${targetProjectOutputDir} 存在未提交文件,请检查`);
478
- process.exit(1);
479
- }
480
-
481
- runGitCommand(checkoutCmd);
482
- runGitCommand(pullCmd);
483
- }
484
-
485
- /**
486
- * 检查 packages 下的所有模块是否有未提交的代码
487
- * @param {string} packagesDir - packages 目录的绝对路径
488
- * @returns {Object} 检查结果
489
- */
490
- async function checkPackagesGitStatus(packagesDir) {
491
- const fs = require("fs");
492
-
493
- if (!fs.existsSync(packagesDir)) {
494
- console.error(global.logColor.error, `❌ packages 目录不存在: ${packagesDir}`);
495
- return { hasUncommitted: false, modules: [] };
496
- }
497
-
498
- const modules = fs.readdirSync(packagesDir).filter((item) => {
499
- const modulePath = path.join(packagesDir, item);
500
- return fs.statSync(modulePath).isDirectory();
501
- });
502
-
503
- // console.log(global.logColor.info, `📦 检查 packages 下的 ${modules.length} 个模块...`);
504
-
505
- const uncommittedModules = await Promise.all(
506
- modules.map(async (module) => {
507
- const modulePath = path.join(packagesDir, module);
508
- const gitPath = path.join(modulePath, ".git");
509
-
510
- // 检查是否是 git 仓库
511
- if (!fs.existsSync(gitPath)) {
512
- console.log(global.logColor.warning, `⚠️ ${module}: 不是 git 仓库,跳过检查`);
513
- return null;
514
- }
515
-
516
- try {
517
- // 切换到模块目录并检查 git status
518
- const { stdout } = await execAsync("git status --porcelain", { cwd: modulePath });
519
- const statusOutput = stdout.trim();
520
-
521
- if (statusOutput) {
522
- console.log(global.logColor.error, `❌ ${module}: 存在未提交的更改`);
523
- console.log(global.logColor.error, ` ${statusOutput.split("\n").join("\n ")}`);
524
- return {
525
- name: module,
526
- path: modulePath,
527
- changes: statusOutput.split("\n")
528
- };
529
- }
530
- return null;
531
- } catch (error) {
532
- console.error(global.logColor.error, `❌ ${module}: 检查失败 - ${error.message}`);
533
- return {
534
- name: module,
535
- path: modulePath,
536
- error: error.message
537
- };
538
- }
539
- })
540
- ).then(results => results.filter(r => r !== null));
541
-
542
- return {
543
- hasUncommitted: uncommittedModules.length > 0,
544
- modules: uncommittedModules,
545
- totalModules: modules.length,
546
- checkedModules: modules
547
- };
548
- }
549
-
550
- /**
551
- * 切换所有 packages 模块到 master 分支并拉取最新代码
552
- * @param {string} packagesDir - packages 目录的绝对路径
553
- * @param {string} targetBranch - 目标分支名,默认为 'master'
554
- */
555
- async function pullPackagesFromMaster(packagesDir, targetBranch = "master") {
556
- const fs = require("fs");
557
-
558
- if (!fs.existsSync(packagesDir)) {
559
- console.error(global.logColor.error, `❌ packages 目录不存在: ${packagesDir}`);
560
- return;
561
- }
562
-
563
- const modules = fs.readdirSync(packagesDir).filter((item) => {
564
- const modulePath = path.join(packagesDir, item);
565
- return fs.statSync(modulePath).isDirectory();
566
- });
567
-
568
- // console.log(global.logColor.info, `🔄 切换 packages 下的模块到 ${targetBranch} 分支并拉取最新代码...`);
569
-
570
- const results = await Promise.all(
571
- modules.map(async (module) => {
572
- const modulePath = path.join(packagesDir, module);
573
- const gitPath = path.join(modulePath, ".git");
574
-
575
- // 检查是否是 git 仓库
576
- if (!fs.existsSync(gitPath)) {
577
- console.log(global.logColor.warning, `⚠️ ${module}: 不是 git 仓库,跳过操作`);
578
- return { module, success: false, reason: "不是 git 仓库" };
579
- }
580
-
581
- try {
582
- // 获取当前分支
583
- const { stdout: branchOut } = await execAsync("git rev-parse --abbrev-ref HEAD", { cwd: modulePath });
584
- const currentBranch = branchOut.trim();
585
-
586
- // 如果不在目标分支,则切换
587
- if (currentBranch !== targetBranch) {
588
- await execAsync(`git checkout ${targetBranch}`, { cwd: modulePath });
589
- }
590
-
591
- // 拉取最新代码
592
- await execAsync(`git pull --ff-only origin ${targetBranch}`, { cwd: modulePath });
593
-
594
- console.log(global.logColor.success, `✅ \x1b[34m${module}\x1b[32m[${targetBranch}]: 更新到最新代码`);
595
- return { module, success: true };
596
- } catch (error) {
597
- console.error(global.logColor.error, `❌ ${module}: 操作失败 - ${error.message}`);
598
- return { module, success: false, reason: error.message };
599
- }
600
- })
601
- );
602
-
603
- // 输出结果摘要
604
- const successful = results.filter((r) => r.success).length;
605
- const failed = results.filter((r) => !r.success).length;
606
-
607
- // console.log(global.logColor.info, `\n📊 操作完成: 成功 ${successful} 个,失败 ${failed} 个`);
608
-
609
- return results;
610
- }
611
-
612
- // 获取 packages 目录路径(相对于当前项目根目录)
613
- function hasGitModules(packagesDir) {
614
- if (!fs.existsSync(packagesDir)) {
615
- return false;
616
- }
617
-
618
- return ["infly-libs", "infly-ui"].some((item) => fs.existsSync(path.join(packagesDir, item, ".git")));
619
- }
620
-
621
- function checkAndUpdateRootPackages(packagesDir, targetBranch = "master") {
622
- return checkAndUpdateRootRepository(path.resolve(packagesDir, ".."), targetBranch);
623
- }
624
-
625
- function checkAndUpdateRootRepository(rootDir, targetBranch = "master") {
626
- const gitPath = path.join(rootDir, ".git");
627
-
628
- if (!fs.existsSync(gitPath)) {
629
- console.log(global.logColor.warning, `⚠️ packages 不属于独立 git 仓库,也未找到根仓库,跳过 packages 更新`);
630
- return [];
631
- }
632
-
633
- require("./root-update").updateRootRepository(rootDir, targetBranch);
634
- console.log(global.logColor.success, `✅ admin-monorepo: 已同步 ${targetBranch} 公共源码`);
635
- return [{ module: "admin-monorepo", success: true }];
636
- }
637
-
638
- function findPackagesDir(currentDir) {
639
- let searchDir = currentDir || process.cwd();
640
-
641
- // 旧版 packages/* 独立仓库模式保留近层目录查找。
642
- for (let i = 0; i < 3; i++) {
643
- const packagesPath = path.resolve(searchDir, "packages");
644
- if (fs.existsSync(packagesPath)) {
645
- return packagesPath;
646
- }
647
- const parentDir = path.dirname(searchDir);
648
- if (parentDir === searchDir) break; // 已到根目录
649
- searchDir = parentDir;
650
- }
651
-
652
- return null;
653
- }
654
-
655
- /**
656
- * 检查指定目录的 Git 状态
657
- * @param {string} dirPath - 目录的绝对路径
658
- * @param {string} dirName - 目录名称(用于日志显示)
659
- */
660
- function checkSingleDirGitStatus(dirPath, dirName) {
661
- const fs = require("fs");
662
-
663
- if (!fs.existsSync(dirPath)) {
664
- console.log(global.logColor.warning, `⚠️ ${dirName} 目录不存在: ${dirPath}`);
665
- return { hasUncommitted: false, changes: [] };
666
- }
667
-
668
- const gitPath = path.join(dirPath, ".git");
669
- if (!fs.existsSync(gitPath)) {
670
- console.log(global.logColor.warning, `⚠️ ${dirName} 不是 git 仓库,跳过检查`);
671
- return { hasUncommitted: false, changes: [] };
672
- }
673
-
674
- try {
675
- const statusOutput = execSync("git status --porcelain", {
676
- cwd: dirPath,
677
- encoding: "utf8"
678
- }).trim();
679
-
680
- if (statusOutput) {
681
- console.log(global.logColor.error, `❌ ${dirName}: 存在未提交的更改`);
682
- console.log(global.logColor.error, ` ${statusOutput.split("\n").join("\n ")}`);
683
- return {
684
- hasUncommitted: true,
685
- changes: statusOutput.split("\n"),
686
- path: dirPath
687
- };
688
- } else {
689
- // console.log(global.logColor.success, `✅ ${dirName}: 工作区干净`);
690
- return { hasUncommitted: false, changes: [] };
691
- }
692
- } catch (error) {
693
- console.error(global.logColor.error, `❌ ${dirName}: 检查失败 - ${error.message}`);
694
- return {
695
- hasUncommitted: true,
696
- error: error.message,
697
- path: dirPath
698
- };
699
- }
700
- }
701
-
702
- /**
703
- * 切换指定目录到目标分支并拉取最新代码
704
- * @param {string} dirPath - 目录的绝对路径
705
- * @param {string} dirName - 目录名称(用于日志显示)
706
- * @param {string} targetBranch - 目标分支名
707
- */
708
- function pullSingleDirFromBranch(dirPath, dirName, targetBranch = "master", buildProjectName = "") {
709
- const fs = require("fs");
710
-
711
- if (!fs.existsSync(dirPath)) {
712
- console.log(global.logColor.warning, `⚠️ ${dirName} 目录不存在: ${dirPath}`);
713
- return { success: false, reason: "目录不存在" };
714
- }
715
-
716
- const gitPath = path.join(dirPath, ".git");
717
- if (!fs.existsSync(gitPath)) {
718
- console.log(global.logColor.warning, `⚠️ ${dirName} 不是 git 仓库,跳过操作`);
719
- return { success: false, reason: "不是 git 仓库" };
720
- }
721
-
722
- try {
723
- // 获取当前分支
724
- const currentBranch = execSync("git rev-parse --abbrev-ref HEAD", {
725
- cwd: dirPath,
726
- encoding: "utf8"
727
- }).trim();
728
-
729
- // 如果不在目标分支,则切换
730
- if (currentBranch !== targetBranch) {
731
- // console.log(global.logColor.info, ` ${dirName}: 切换到 ${targetBranch} 分支...`);
732
- execSync(`git checkout ${targetBranch}`, {
733
- cwd: dirPath,
734
- stdio: "pipe"
735
- });
736
- }
737
-
738
- // 拉取最新代码
739
- // console.log(global.logColor.info, ` ${dirName}: 拉取 ${targetBranch} 最新代码...`);
740
- execSync(`git pull --ff-only origin ${targetBranch}`, {
741
- cwd: dirPath,
742
- stdio: "pipe"
743
- });
744
-
745
- const buildProjectText = buildProjectName ? `(构建项目:${buildProjectName})` : "";
746
- console.log(global.logColor.success, `✅ \x1b[34m${dirName}\x1b[32m[${targetBranch}]: 更新到最新代码${buildProjectText}`);
747
- return { success: true };
748
- } catch (error) {
749
- console.error(global.logColor.error, `❌ ${dirName}: 操作失败 - ${error.message}`);
750
- return { success: false, reason: error.message };
751
- }
752
- }
753
-
754
- /**
755
- * 完整的 packages 检查和更新流程
756
- * @param {string} packagesDir - packages 目录的绝对路径
757
- * @param {string} targetBranch - 目标分支名,默认为 'master'
758
- */
759
- async function checkAndUpdatePackages(outPackagesDir, targetBranch = "master", buildProjectName = "", rootDir = "") {
760
- try {
761
- if (rootDir) {
762
- return checkAndUpdateRootRepository(rootDir, targetBranch);
763
- }
764
-
765
- const packagesDir = outPackagesDir || findPackagesDir();
766
-
767
- // 检查 packages 目录是否存在
768
- if (!packagesDir) {
769
- const warning = buildProjectName
770
- ? `⚠️ 内嵌项目 ${buildProjectName} 的构建目录未解析到 packages,跳过本次公共包源码更新`
771
- : `⚠️ packages 目录不存在,跳过检查`;
772
- console.log(global.logColor.warning, warning);
773
- return;
774
- }
775
-
776
- console.log(global.logColor.info, `\n🚀 开始检查和更新 packages 模块...`);
777
-
778
- // 1. 检查未提交的更改
779
- if (!hasGitModules(packagesDir)) {
780
- return checkAndUpdateRootPackages(packagesDir, targetBranch);
781
- }
782
-
783
- const checkResult = await checkPackagesGitStatus(packagesDir);
784
-
785
- if (checkResult.hasUncommitted) {
786
- // console.log(global.logColor.error, `\n❌ 发现 ${checkResult.modules.length} 个模块存在未提交的更改:`);
787
- checkResult.modules.forEach((module) => {
788
- // console.log(global.logColor.error, ` - ${module.name}`);
789
- });
790
- console.log(global.logColor.error, `\n请先提交或储藏这些更改后再继续执行!`);
791
- process.exit(1);
792
- }
793
-
794
- // console.log(global.logColor.success, `\n✅ 所有模块工作区都是干净的,继续执行...`);
795
-
796
- // 2. 切换到 master 并拉取最新代码
797
- const updateResults = await pullPackagesFromMaster(packagesDir, targetBranch);
798
-
799
- // 3. 检查是否有失败的操作
800
- const failedUpdates = updateResults.filter((r) => !r.success);
801
- if (failedUpdates.length > 0) {
802
- console.log(global.logColor.warning, `\n⚠️ 有 ${failedUpdates.length} 个模块更新失败,但可以继续执行`);
803
- }
804
-
805
- // console.log(global.logColor.success, `\n🎉 packages 检查和更新流程完成!`);
806
- return updateResults;
807
- } catch (error) {
808
- console.error(global.logColor.error, `❌ packages 检查失败: ${error.message}`);
809
- console.error(global.logColor.error, "请检查 packages 下的模块是否有未提交的更改");
810
- process.exit(1);
811
- }
812
- }
813
-
814
- module.exports = {
815
- getCurrentBranch,
816
- getLatestCommitInfo,
817
- getBuildUpdateText,
818
- getLastCommitByFile,
819
- checkGitStatus,
820
- autoGitProcess,
821
- runGitCommand,
822
- autoBranchProcess,
823
- checkPackagesGitStatus,
824
- pullPackagesFromMaster,
825
- checkAndUpdatePackages,
826
- checkSingleDirGitStatus,
827
- pullSingleDirFromBranch
828
- };
1
+ const { formatTerminalMessage, logTerminal } = require("../../cli/terminal-style");
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+ const crypto = require("crypto");
5
+ const childProcess = require("child_process");
6
+ const { execSync, exec } = childProcess;
7
+ const { promisify } = require("util");
8
+ const { getGitCommonDir } = require("./git-utils");
9
+ const execAsync = promisify(exec);
10
+
11
+ /**
12
+ * 获取当前 Git 分支名称
13
+ * @returns
14
+ */
15
+ function getCurrentBranch() {
16
+ return execSync("git rev-parse --abbrev-ref HEAD").toString().trim();
17
+ }
18
+
19
+ /**
20
+ * 获取 Git 提交信息
21
+ * @returns {Object} 包含提交信息的对象,如果获取失败则返回空对象
22
+ */
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
+
32
+ // 定义 Git 命令
33
+ const commands = {
34
+ // 构建元数据必须全部对应源码 HEAD。跳过 merge commit 会导致 fullHash 指向
35
+ // 当前合并提交,而文案、作者却回退到更早的版本构建提交。
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]
41
+ };
42
+
43
+ // 结果对象
44
+ const commitInfo = { fullHash };
45
+
46
+ try {
47
+ // 检查当前目录是否是 Git 仓库
48
+ readGit(cwd, ["rev-parse", "--is-inside-work-tree"]);
49
+
50
+ // 遍历命令并执行
51
+ for (const [key, command] of Object.entries(commands)) {
52
+ try {
53
+ commitInfo[key] = readGit(cwd, command).trim();
54
+ } catch (cmdError) {
55
+ logTerminal("warning", `获取 Git 信息失败(${key}):${cmdError.message}`);
56
+ commitInfo[key] = ""; // 失败时设置为空字符串
57
+ }
58
+ }
59
+ } catch (error) {
60
+ logTerminal(
61
+ "error", `获取 Git 信息失败:当前目录不是 Git 仓库或 Git 未安装。错误信息:${error.message}`
62
+ );
63
+ return {}; // 返回空对象
64
+ }
65
+
66
+ return commitInfo;
67
+ }
68
+
69
+ function createCommitTextMatcher(template = "") {
70
+ if (!template) return null;
71
+
72
+ const escapedParts = template
73
+ .split("{version}")
74
+ .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
75
+ return new RegExp(`^${escapedParts.join(".+?")}$`);
76
+ }
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
+
88
+ function isAncestorCommit(ancestor, descendant, cwd) {
89
+ if (!COMMIT_HASH.test(ancestor)) return false;
90
+ try {
91
+ readGit(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]);
92
+ return true;
93
+ } catch {
94
+ return false;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * 将侧分支上的版本提交映射到它首次进入当前分支第一父链的合并提交。
100
+ * 否则 `versionCommit..HEAD` 会把当前分支上与侧分支互不为祖先的大量旧提交误算为本次更新。
101
+ */
102
+ function resolveBuildSummaryBaseline(versionCommit, cwd, head) {
103
+ const firstParentHistory = readGit(cwd, ["rev-list", "--first-parent", head])
104
+ .trim()
105
+ .split(/\r?\n/)
106
+ .filter(Boolean);
107
+
108
+ if (firstParentHistory.includes(versionCommit)) return versionCommit;
109
+
110
+ // 第一父链从新到旧排列;“包含版本提交”在链上形成连续前缀,可以二分找到最早引入点。
111
+ let low = 0;
112
+ let high = firstParentHistory.length - 1;
113
+ let oldestContainingIndex = -1;
114
+ while (low <= high) {
115
+ const middle = Math.floor((low + high) / 2);
116
+ if (isAncestorCommit(versionCommit, firstParentHistory[middle], cwd)) {
117
+ oldestContainingIndex = middle;
118
+ low = middle + 1;
119
+ } else {
120
+ high = middle - 1;
121
+ }
122
+ }
123
+
124
+ return oldestContainingIndex >= 0 ? firstParentHistory[oldestContainingIndex] : versionCommit;
125
+ }
126
+
127
+ function getCommitSubjectKey(subject) {
128
+ const workItem = subject.match(/#[a-z][a-z0-9]*-\d+\b/i)?.[0];
129
+ if (workItem) return `work-item:${workItem.toUpperCase()}`;
130
+
131
+ return subject
132
+ .trim()
133
+ .replace(/\s+/g, " ")
134
+ .replace(/\s+([,.;:!?#])/g, "$1")
135
+ .toLowerCase();
136
+ }
137
+
138
+ function deduplicateCommitSubjects(subjects) {
139
+ const seen = new Set();
140
+ return subjects.filter((subject) => {
141
+ const key = getCommitSubjectKey(subject);
142
+ if (seen.has(key)) return false;
143
+ seen.add(key);
144
+ return true;
145
+ });
146
+ }
147
+
148
+ function getHeadParents(cwd, head) {
149
+ const headWithParents = readGit(cwd, ["rev-list", "--parents", "-n", "1", head]).trim();
150
+ return headWithParents ? headWithParents.split(/\s+/).slice(1) : [];
151
+ }
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
+
200
+ /**
201
+ * 产物仓发布按目标分支和目录比较源码;旧构建保留源码仓版本范围作为参考。
202
+ */
203
+ function getBuildUpdateText(gitAutoCommitText, cwd = process.cwd(), limit = 10, options = {}) {
204
+ const matcher = createCommitTextMatcher(gitAutoCommitText);
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 "";
209
+
210
+ try {
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
221
+ .trim()
222
+ .split(/\r?\n/)
223
+ .filter((subject) => subject && !matcher?.test(subject) && !DEFAULT_BUILD_SUBJECT.test(subject)));
224
+
225
+ if (subjects.length === 0) return unknownBaseline ? UNKNOWN_ARTIFACT_BASELINE : NO_SOURCE_CHANGES;
226
+
227
+ const visibleSubjects = subjects.slice(0, limit);
228
+ if (subjects.length > limit) {
229
+ visibleSubjects.push(`...另 ${subjects.length - limit} 条提交`);
230
+ }
231
+ const summary = visibleSubjects.map((subject) => `- ${subject}`).join("\n");
232
+ return unknownBaseline ? `${UNKNOWN_ARTIFACT_BASELINE},以下为可识别的提交\n${summary}` : summary;
233
+ } catch (error) {
234
+ logTerminal("warning", `获取构建更新摘要失败:${error.message}`);
235
+ return hasArtifact ? UNKNOWN_ARTIFACT_BASELINE : "";
236
+ }
237
+ }
238
+
239
+ /**
240
+ * 获取指定文件的最后一次提交信息
241
+ * @param {String} filePath - 文件路径
242
+ * @returns {Object|null} 包含提交信息的对象,如果获取失败则返回 null
243
+ */
244
+ function getLastCommitByFile(filePath) {
245
+ try {
246
+ // 执行 Git 命令获取最后一次提交信息‌:ml-citation{ref="3,5" data="citationList"}
247
+ const cmd = `git log -1 --format="%H|%an|%ae|%at|%s" -- ${filePath}`;
248
+ const output = execSync(cmd, { encoding: "utf8" }).trim();
249
+ if (!output) return null;
250
+
251
+ // 解析提交信息‌:ml-citation{ref="1,5" data="citationList"}
252
+ const [hash, author, email, timestamp, message] = output.split("|");
253
+ return {
254
+ commitMsg: message.trim(),
255
+ hash,
256
+ author,
257
+ email,
258
+ date: new Date(parseInt(timestamp) * 1000).toISOString()
259
+ };
260
+ } catch {
261
+ return null;
262
+ }
263
+ }
264
+
265
+ /**
266
+ * 检查是否构建文件
267
+ * @param {String} targetProjectOutputDir 构建文件输出绝对路径
268
+ * @param {String} gitStatusLine 带文件状态的
269
+ * @returns
270
+ */
271
+ function isBuildFile(targetProjectOutputDir = "", gitLine = "", sliceLen = -1) {
272
+ if (!targetProjectOutputDir) {
273
+ return true;
274
+ }
275
+ // 统一路径分隔符
276
+ targetProjectOutputDir = targetProjectOutputDir.replace(/\\/g, "/");
277
+
278
+ // 取目录的最后 N 级,比如 frontend/ea
279
+ const dirFragment = targetProjectOutputDir.split("/").slice(sliceLen).join("/");
280
+
281
+ // 去掉状态前缀 (M, A, D, ?? 等)
282
+ const gitPath = gitLine.trim().slice(2).trim();
283
+
284
+ // 判断是否以 dirFragment 开头
285
+ return gitPath.startsWith(dirFragment + "/");
286
+ }
287
+
288
+ /**
289
+ * 检查 Git 状态
290
+ * @param {String} excludeDir - 排除的目录
291
+ * @param {String} extraFilter - 额外过滤条件
292
+ * @param {Object} extraParams - 额外的配置
293
+ */
294
+ function checkGitStatus(excludeDir, extraFilter, extraParams) {
295
+ const {
296
+ deleteOldFile = [],
297
+ versionFileName = "version-config.json",
298
+ gitAutoPushRepos,
299
+ targetProjectOutputDir,
300
+ targetProjectOutputDirCmd = gitAutoPushRepos ? ` -C ${targetProjectOutputDir}` : "",
301
+ onlyCheckStatus,
302
+ startLogText = "Git自动提交开始执行, 正在检查非构建文件"
303
+ } = extraParams || {};
304
+
305
+ // 如果指定了构建输出目录但目录不存在,则自动创建并初始化 Git 仓库
306
+ if (targetProjectOutputDir && !fs.existsSync(targetProjectOutputDir)) {
307
+ logTerminal("warning", `构建目录不存在,正在自动创建:${targetProjectOutputDir}`);
308
+ fs.mkdirSync(targetProjectOutputDir, { recursive: true });
309
+ logTerminal("success", `构建目录已创建并初始化 Git 仓库:${targetProjectOutputDir}`);
310
+ }
311
+
312
+ try {
313
+ // 获取所有未跟踪和已修改的文件列表
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
318
+ .split("\u0000")
319
+ .filter((file) => file.trim() && (targetProjectOutputDirCmd || isBuildFile(targetProjectOutputDir, file)));
320
+ const excludeFiles = []; // 非指定构建相关文件
321
+ const includeFiles = []; // 指定的构建相关文件
322
+
323
+ if (onlyCheckStatus || targetProjectOutputDirCmd) {
324
+ return files || [];
325
+ }
326
+
327
+ logTerminal("info", `${startLogText}`);
328
+
329
+ // 进行当前项目文件检查,如果有其它非配置文件则取消自动提交改为用户手动确认
330
+ files.forEach((file) => {
331
+ const existsDelFile = deleteOldFile.find((item) => file.includes(item));
332
+ if (
333
+ file.includes(`${excludeDir}/`) ||
334
+ file.includes(versionFileName) ||
335
+ file.includes(extraFilter) ||
336
+ existsDelFile
337
+ ) {
338
+ includeFiles.push(file);
339
+ } else {
340
+ excludeFiles.push(file);
341
+ }
342
+ });
343
+
344
+ if (excludeFiles.length > 0) {
345
+ throw new Error(`存在非构建文件未提交,请手动确定提交信息,本次自动提交终止\n${excludeFiles.join("\n")}`);
346
+ }
347
+
348
+ return includeFiles || [];
349
+ } catch (err) {
350
+ logTerminal("error", `自动化构建Git状态检查存在问题:${err.message}`);
351
+ process.exit(1);
352
+ }
353
+ }
354
+
355
+ function runGitCommand(command, options = {}) {
356
+ try {
357
+ const commandOptions = { ...options, encoding: "utf8" };
358
+ const result = Array.isArray(command)
359
+ ? childProcess.execFileSync("git", command, commandOptions)
360
+ : execSync(command, commandOptions);
361
+ if (result) {
362
+ return result.trim();
363
+ }
364
+ } catch (error) {
365
+ logTerminal("error", `执行 Git 命令失败:${error.message}`);
366
+ process.exit(1);
367
+ }
368
+ }
369
+
370
+ function hasStagedChanges(scope, options) {
371
+ try {
372
+ childProcess.execFileSync("git", ["diff", "--cached", "--quiet", ...scope], { ...options, stdio: "ignore" });
373
+ return false;
374
+ } catch (error) {
375
+ if (error.status === 1) return true;
376
+ throw error;
377
+ }
378
+ }
379
+
380
+ function sleepSync(ms) {
381
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
382
+ }
383
+
384
+ function withGitRepoLock(lockDir, lockKey, task) {
385
+ if (!lockDir || !lockKey) {
386
+ return task();
387
+ }
388
+
389
+ fs.mkdirSync(lockDir, { recursive: true });
390
+ const lockName = crypto.createHash("md5").update(lockKey).digest("hex");
391
+ const lockPath = path.join(lockDir, `${lockName}.lock`);
392
+ const startTime = Date.now();
393
+ const timeout = 10 * 60 * 1000;
394
+
395
+ while (true) {
396
+ try {
397
+ fs.mkdirSync(lockPath);
398
+ break;
399
+ } catch (error) {
400
+ if (error.code !== "EEXIST") {
401
+ throw error;
402
+ }
403
+
404
+ if (Date.now() - startTime > timeout) {
405
+ throw new Error(`等待 Git 仓库锁超时: ${lockKey}`);
406
+ }
407
+
408
+ sleepSync(500);
409
+ }
410
+ }
411
+
412
+ try {
413
+ return task();
414
+ } finally {
415
+ fs.rmSync(lockPath, { recursive: true, force: true });
416
+ }
417
+ }
418
+
419
+ /**
420
+ * git自动推送
421
+ * @param {String} buildFoldName 构建文件名称
422
+ * @param {String} newFileName 新压缩文件名
423
+ * @param {Object} extraParams 额外的参数
424
+ * @returns
425
+ */
426
+ function autoGitProcess(buildFoldName, newFileName, extraParams = {}) {
427
+ const {
428
+ newVersion,
429
+ gitInfo = {},
430
+ gitAutoCommitText = gitInfo.commitMsg,
431
+ gitAutoPushRepos,
432
+ targetProjectOutputDir,
433
+ gitAutoPushReposBranchMap = {},
434
+ projectName,
435
+ gitLockDir,
436
+ gitProcessOrder
437
+ } = extraParams || {};
438
+ const appFirst = gitAutoPushRepos && gitProcessOrder === "app-first";
439
+ const runAppGitProcess = () => {
440
+ const overrideParams = {
441
+ ...extraParams,
442
+ targetProjectOutputDir: "",
443
+ targetProjectOutputDirCmd: "",
444
+ gitAutoPushRepos: false
445
+ };
446
+ autoGitProcess(buildFoldName, newFileName, overrideParams);
447
+ };
448
+
449
+ if (appFirst) {
450
+ runAppGitProcess();
451
+ }
452
+
453
+ const { commitMsg, branch, fullHash } = gitInfo || {};
454
+ const gitRepos = gitAutoPushRepos ? `构建仓库: ${targetProjectOutputDir}` : `当前项目: ${projectName}`;
455
+ const tempBranch = gitAutoPushRepos ? gitAutoPushReposBranchMap[branch] : branch;
456
+ const commitText = gitAutoPushRepos ? String(commitMsg || "") : (gitAutoCommitText || "").replace("{version}", newVersion);
457
+ const gitOptions = gitAutoPushRepos ? { cwd: targetProjectOutputDir } : {};
458
+ const scope = gitAutoPushRepos ? ["--", "."] : [];
459
+
460
+ if (!tempBranch) {
461
+ logTerminal("error", `缺少分支配置`);
462
+ return;
463
+ }
464
+
465
+ const checkCommitAndPush = () => {
466
+ const fileList = checkGitStatus(buildFoldName, newFileName, extraParams) || [];
467
+
468
+ if (fileList.length === 0) {
469
+ return;
470
+ }
471
+
472
+ runGitCommand(["add", "-A", ...scope], gitOptions);
473
+ if (!hasStagedChanges(scope, gitOptions)) {
474
+ logTerminal("warning", `Git ${gitRepos} 没有可提交的变更,跳过自动提交`);
475
+ return;
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);
486
+ };
487
+
488
+ if (gitAutoPushRepos) {
489
+ withGitRepoLock(gitLockDir, getGitCommonDir(targetProjectOutputDir), checkCommitAndPush);
490
+ } else {
491
+ checkCommitAndPush();
492
+ }
493
+
494
+ if (gitAutoPushRepos && !appFirst) {
495
+ runAppGitProcess();
496
+ }
497
+
498
+ logTerminal("success", `Git ${gitRepos} 自动提交和推送成功!`);
499
+ }
500
+ /**
501
+ * 自动分支处理
502
+ * @param {Object} config - 分支配置
503
+ */
504
+ async function autoBranchProcess(config) {
505
+ const { gitAutoPushRepos, gitAutoPushReposBranchMap, currentBranch, targetProjectOutputDir, validateConfig } =
506
+ config || {};
507
+ const tempBranch = gitAutoPushRepos ? gitAutoPushReposBranchMap[currentBranch] : currentBranch;
508
+ const gitOptions = gitAutoPushRepos ? { cwd: targetProjectOutputDir } : {};
509
+ const fileList = checkGitStatus(undefined, undefined, {
510
+ onlyCheckStatus: true,
511
+ targetProjectOutputDir,
512
+ gitAutoPushRepos,
513
+ startLogText: "Git自动化开始执行..."
514
+ });
515
+
516
+ if (validateConfig && typeof validateConfig === "function") {
517
+ validateConfig();
518
+ }
519
+
520
+ if (!tempBranch) {
521
+ logTerminal("error", `缺少项目分支对应构建仓库分支配置,当前分支:${currentBranch},请检查`);
522
+ process.exit(1);
523
+ }
524
+
525
+ if (fileList.length > 0) {
526
+ logTerminal("error", `构建仓库 ${targetProjectOutputDir} 存在未提交文件,请检查`);
527
+ process.exit(1);
528
+ }
529
+
530
+ runGitCommand(["checkout", tempBranch], gitOptions);
531
+ runGitCommand(["pull", "--ff-only", "origin", tempBranch], gitOptions);
532
+ }
533
+
534
+ /**
535
+ * 检查 packages 下的所有模块是否有未提交的代码
536
+ * @param {string} packagesDir - packages 目录的绝对路径
537
+ * @returns {Object} 检查结果
538
+ */
539
+ async function checkPackagesGitStatus(packagesDir) {
540
+ const fs = require("fs");
541
+
542
+ if (!fs.existsSync(packagesDir)) {
543
+ logTerminal("error", `packages 目录不存在: ${packagesDir}`);
544
+ return { hasUncommitted: false, modules: [] };
545
+ }
546
+
547
+ const modules = fs.readdirSync(packagesDir).filter((item) => {
548
+ const modulePath = path.join(packagesDir, item);
549
+ return fs.statSync(modulePath).isDirectory();
550
+ });
551
+
552
+ const uncommittedModules = await Promise.all(
553
+ modules.map(async (module) => {
554
+ const modulePath = path.join(packagesDir, module);
555
+ const gitPath = path.join(modulePath, ".git");
556
+
557
+ // 检查是否是 git 仓库
558
+ if (!fs.existsSync(gitPath)) {
559
+ logTerminal("warning", `${module}: 不是 git 仓库,跳过检查`);
560
+ return null;
561
+ }
562
+
563
+ try {
564
+ // 切换到模块目录并检查 git status
565
+ const { stdout } = await execAsync("git status --porcelain", { cwd: modulePath });
566
+ const statusOutput = stdout.trim();
567
+
568
+ if (statusOutput) {
569
+ logTerminal("error", `${module}: 存在未提交的更改`);
570
+ logTerminal("error", ` ${statusOutput.split("\n").join("\n ")}`);
571
+ return {
572
+ name: module,
573
+ path: modulePath,
574
+ changes: statusOutput.split("\n")
575
+ };
576
+ }
577
+ return null;
578
+ } catch (error) {
579
+ logTerminal("error", `${module}: 检查失败 - ${error.message}`);
580
+ return {
581
+ name: module,
582
+ path: modulePath,
583
+ error: error.message
584
+ };
585
+ }
586
+ })
587
+ ).then(results => results.filter(r => r !== null));
588
+
589
+ return {
590
+ hasUncommitted: uncommittedModules.length > 0,
591
+ modules: uncommittedModules,
592
+ totalModules: modules.length,
593
+ checkedModules: modules
594
+ };
595
+ }
596
+
597
+ /**
598
+ * 切换所有 packages 模块到 master 分支并拉取最新代码
599
+ * @param {string} packagesDir - packages 目录的绝对路径
600
+ * @param {string} targetBranch - 目标分支名,默认为 'master'
601
+ */
602
+ async function pullPackagesFromMaster(packagesDir, targetBranch = "master") {
603
+ const fs = require("fs");
604
+
605
+ if (!fs.existsSync(packagesDir)) {
606
+ logTerminal("error", `packages 目录不存在: ${packagesDir}`);
607
+ return;
608
+ }
609
+
610
+ const modules = fs.readdirSync(packagesDir).filter((item) => {
611
+ const modulePath = path.join(packagesDir, item);
612
+ return fs.statSync(modulePath).isDirectory();
613
+ });
614
+
615
+ const results = await Promise.all(
616
+ modules.map(async (module) => {
617
+ const modulePath = path.join(packagesDir, module);
618
+ const gitPath = path.join(modulePath, ".git");
619
+
620
+ // 检查是否是 git 仓库
621
+ if (!fs.existsSync(gitPath)) {
622
+ logTerminal("warning", `${module}: 不是 git 仓库,跳过操作`);
623
+ return { module, success: false, reason: "不是 git 仓库" };
624
+ }
625
+
626
+ try {
627
+ // 获取当前分支
628
+ const { stdout: branchOut } = await execAsync("git rev-parse --abbrev-ref HEAD", { cwd: modulePath });
629
+ const currentBranch = branchOut.trim();
630
+
631
+ // 如果不在目标分支,则切换
632
+ if (currentBranch !== targetBranch) {
633
+ await execAsync(`git checkout ${targetBranch}`, { cwd: modulePath });
634
+ }
635
+
636
+ // 拉取最新代码
637
+ await execAsync(`git pull --ff-only origin ${targetBranch}`, { cwd: modulePath });
638
+
639
+ logTerminal("success", `${module}[${targetBranch}]: 更新到最新代码`);
640
+ return { module, success: true };
641
+ } catch (error) {
642
+ logTerminal("error", `${module}: 操作失败 - ${error.message}`);
643
+ return { module, success: false, reason: error.message };
644
+ }
645
+ })
646
+ );
647
+
648
+ // 输出结果摘要
649
+ const successful = results.filter((r) => r.success).length;
650
+ const failed = results.filter((r) => !r.success).length;
651
+
652
+ return results;
653
+ }
654
+
655
+ // 获取 packages 目录路径(相对于当前项目根目录)
656
+ function hasGitModules(packagesDir) {
657
+ if (!fs.existsSync(packagesDir)) {
658
+ return false;
659
+ }
660
+
661
+ return ["infly-libs", "infly-ui"].some((item) => fs.existsSync(path.join(packagesDir, item, ".git")));
662
+ }
663
+
664
+ function checkAndUpdateRootPackages(packagesDir, targetBranch = "master") {
665
+ return checkAndUpdateRootRepository(path.resolve(packagesDir, ".."), targetBranch);
666
+ }
667
+
668
+ function checkAndUpdateRootRepository(rootDir, targetBranch = "master") {
669
+ const gitPath = path.join(rootDir, ".git");
670
+
671
+ if (!fs.existsSync(gitPath)) {
672
+ logTerminal("warning", `packages 不属于独立 git 仓库,也未找到根仓库,跳过 packages 更新`);
673
+ return [];
674
+ }
675
+
676
+ require("./root-update").updateRootRepository(rootDir, targetBranch);
677
+ logTerminal("success", `admin-monorepo: 已同步 ${targetBranch} 公共源码`);
678
+ return [{ module: "admin-monorepo", success: true }];
679
+ }
680
+
681
+ function findPackagesDir(currentDir) {
682
+ let searchDir = currentDir || process.cwd();
683
+
684
+ // 旧版 packages/* 独立仓库模式保留近层目录查找。
685
+ for (let i = 0; i < 3; i++) {
686
+ const packagesPath = path.resolve(searchDir, "packages");
687
+ if (fs.existsSync(packagesPath)) {
688
+ return packagesPath;
689
+ }
690
+ const parentDir = path.dirname(searchDir);
691
+ if (parentDir === searchDir) break; // 已到根目录
692
+ searchDir = parentDir;
693
+ }
694
+
695
+ return null;
696
+ }
697
+
698
+ /**
699
+ * 检查指定目录的 Git 状态
700
+ * @param {string} dirPath - 目录的绝对路径
701
+ * @param {string} dirName - 目录名称(用于日志显示)
702
+ */
703
+ function checkSingleDirGitStatus(dirPath, dirName) {
704
+ const fs = require("fs");
705
+
706
+ if (!fs.existsSync(dirPath)) {
707
+ logTerminal("warning", `${dirName} 目录不存在: ${dirPath}`);
708
+ return { hasUncommitted: false, changes: [] };
709
+ }
710
+
711
+ const gitPath = path.join(dirPath, ".git");
712
+ if (!fs.existsSync(gitPath)) {
713
+ logTerminal("warning", `${dirName} 不是 git 仓库,跳过检查`);
714
+ return { hasUncommitted: false, changes: [] };
715
+ }
716
+
717
+ try {
718
+ const statusOutput = execSync("git status --porcelain", {
719
+ cwd: dirPath,
720
+ encoding: "utf8"
721
+ }).trim();
722
+
723
+ if (statusOutput) {
724
+ logTerminal("error", `${dirName}: 存在未提交的更改`);
725
+ logTerminal("error", ` ${statusOutput.split("\n").join("\n ")}`);
726
+ return {
727
+ hasUncommitted: true,
728
+ changes: statusOutput.split("\n"),
729
+ path: dirPath
730
+ };
731
+ } else {
732
+ return { hasUncommitted: false, changes: [] };
733
+ }
734
+ } catch (error) {
735
+ logTerminal("error", `${dirName}: 检查失败 - ${error.message}`);
736
+ return {
737
+ hasUncommitted: true,
738
+ error: error.message,
739
+ path: dirPath
740
+ };
741
+ }
742
+ }
743
+
744
+ /**
745
+ * 切换指定目录到目标分支并拉取最新代码
746
+ * @param {string} dirPath - 目录的绝对路径
747
+ * @param {string} dirName - 目录名称(用于日志显示)
748
+ * @param {string} targetBranch - 目标分支名
749
+ */
750
+ function pullSingleDirFromBranch(dirPath, dirName, targetBranch = "master", buildProjectName = "") {
751
+ const fs = require("fs");
752
+
753
+ if (!fs.existsSync(dirPath)) {
754
+ logTerminal("warning", `${dirName} 目录不存在: ${dirPath}`);
755
+ return { success: false, reason: "目录不存在" };
756
+ }
757
+
758
+ const gitPath = path.join(dirPath, ".git");
759
+ if (!fs.existsSync(gitPath)) {
760
+ logTerminal("warning", `${dirName} 不是 git 仓库,跳过操作`);
761
+ return { success: false, reason: "不是 git 仓库" };
762
+ }
763
+
764
+ try {
765
+ // 获取当前分支
766
+ const currentBranch = execSync("git rev-parse --abbrev-ref HEAD", {
767
+ cwd: dirPath,
768
+ encoding: "utf8"
769
+ }).trim();
770
+
771
+ // 如果不在目标分支,则切换
772
+ if (currentBranch !== targetBranch) {
773
+ execSync(`git checkout ${targetBranch}`, {
774
+ cwd: dirPath,
775
+ stdio: "pipe"
776
+ });
777
+ }
778
+
779
+ // 拉取最新代码
780
+ execSync(`git pull --ff-only origin ${targetBranch}`, {
781
+ cwd: dirPath,
782
+ stdio: "pipe"
783
+ });
784
+
785
+ const buildProjectText = buildProjectName ? `(构建项目:${buildProjectName})` : "";
786
+ logTerminal("success", `${dirName}[${targetBranch}]: 更新到最新代码${buildProjectText}`);
787
+ return { success: true };
788
+ } catch (error) {
789
+ logTerminal("error", `${dirName}: 操作失败 - ${error.message}`);
790
+ return { success: false, reason: error.message };
791
+ }
792
+ }
793
+
794
+ /**
795
+ * 完整的 packages 检查和更新流程
796
+ * @param {string} packagesDir - packages 目录的绝对路径
797
+ * @param {string} targetBranch - 目标分支名,默认为 'master'
798
+ */
799
+ async function checkAndUpdatePackages(outPackagesDir, targetBranch = "master", buildProjectName = "", rootDir = "") {
800
+ try {
801
+ if (rootDir) {
802
+ return checkAndUpdateRootRepository(rootDir, targetBranch);
803
+ }
804
+
805
+ const packagesDir = outPackagesDir || findPackagesDir();
806
+
807
+ // 检查 packages 目录是否存在
808
+ if (!packagesDir) {
809
+ const warning = buildProjectName
810
+ ? formatTerminalMessage("warning", `内嵌项目 ${buildProjectName} 的构建目录未解析到 packages,跳过本次公共包源码更新`)
811
+ : formatTerminalMessage("warning", `packages 目录不存在,跳过检查`);
812
+ logTerminal("warning", warning);
813
+ return;
814
+ }
815
+
816
+ logTerminal("info", `\n开始检查和更新 packages 模块...`);
817
+
818
+ // 1. 检查未提交的更改
819
+ if (!hasGitModules(packagesDir)) {
820
+ return checkAndUpdateRootPackages(packagesDir, targetBranch);
821
+ }
822
+
823
+ const checkResult = await checkPackagesGitStatus(packagesDir);
824
+
825
+ if (checkResult.hasUncommitted) {
826
+ checkResult.modules.forEach((module) => {
827
+ });
828
+ logTerminal("error", `\n请先提交或储藏这些更改后再继续执行!`);
829
+ process.exit(1);
830
+ }
831
+
832
+ // 2. 切换到 master 并拉取最新代码
833
+ const updateResults = await pullPackagesFromMaster(packagesDir, targetBranch);
834
+
835
+ // 3. 检查是否有失败的操作
836
+ const failedUpdates = updateResults.filter((r) => !r.success);
837
+ if (failedUpdates.length > 0) {
838
+ logTerminal("warning", `\n有 ${failedUpdates.length} 个模块更新失败,但可以继续执行`);
839
+ }
840
+ return updateResults;
841
+ } catch (error) {
842
+ logTerminal("error", `packages 检查失败: ${error.message}`);
843
+ logTerminal("error", "请检查 packages 下的模块是否有未提交的更改");
844
+ process.exit(1);
845
+ }
846
+ }
847
+
848
+ module.exports = {
849
+ getCurrentBranch,
850
+ getLatestCommitInfo,
851
+ getBuildUpdateText,
852
+ getLastCommitByFile,
853
+ checkGitStatus,
854
+ autoGitProcess,
855
+ runGitCommand,
856
+ autoBranchProcess,
857
+ checkPackagesGitStatus,
858
+ pullPackagesFromMaster,
859
+ checkAndUpdatePackages,
860
+ checkSingleDirGitStatus,
861
+ pullSingleDirFromBranch
862
+ };