@infly/libs 2.2.6 → 2.2.8

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/bin/cli.js CHANGED
@@ -131,6 +131,7 @@ async function main(argv = process.argv.slice(2)) {
131
131
  preview: () => loadPreview().init(),
132
132
  "--preview": () => loadPreview().init(),
133
133
  beforeBuild: () => loadBuildDist().beforeBuild(),
134
+ run: () => require("../cli/run-command").runCommand(argv.slice(1)),
134
135
  scriptOverride: () => {
135
136
  const preview = loadPreview();
136
137
  const buildDist = loadBuildDist();
@@ -29,6 +29,7 @@ const {
29
29
  autoGitProcess,
30
30
  getCurrentBranch,
31
31
  getLatestCommitInfo,
32
+ getBuildUpdateText,
32
33
  getLastCommitByFile,
33
34
  checkAndUpdatePackages,
34
35
  checkSingleDirGitStatus,
@@ -225,11 +226,12 @@ async function init() {
225
226
  const newFileName = baseFileName.replace("{version}", newVersion).replace("{timestamp}", timestamp);
226
227
  const gitInfo = getLatestCommitInfo() || {};
227
228
  const { branch, commitMsg } = gitInfo || {};
229
+ const updateText = getBuildUpdateText(gitAutoCommitText) || commitMsg;
228
230
  let tempLink = typeof links === "object" ? links[branch] : links || "";
229
231
  if (typeof tempLink === "object") {
230
232
  tempLink = tempLink[process.env.VUE_APP_PLATFORM] || tempLink["DEFAULT"] || JSON.stringify(tempLink);
231
233
  }
232
- const publishText = `${tempPlatformName}:\n更新到:${tempLink}\n更新时间:${timestamp}\n版本号:v${newVersion}\n分支:${branch}\n更新环境:${updateDevText}\n更新内容:\n${commitMsg}`;
234
+ const publishText = `${tempPlatformName}:\n更新到:${tempLink}\n更新时间:${timestamp}\n版本号:v${newVersion}\n分支:${branch}\n更新环境:${updateDevText}\n更新内容:\n${updateText}`;
233
235
  const newZipFileInfo = [
234
236
  {
235
237
  version: newVersion,
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const dotenv = require("dotenv");
6
+ const { defaultRunCommand } = require("./project-command");
7
+
8
+ const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
9
+
10
+ function parseRunArgs(argv) {
11
+ const env = {};
12
+ let cwd = ".";
13
+ let envFile;
14
+ let separatorIndex = -1;
15
+
16
+ for (let index = 0; index < argv.length; index++) {
17
+ const arg = argv[index];
18
+ if (arg === "--") {
19
+ separatorIndex = index;
20
+ break;
21
+ }
22
+ if (arg === "--cwd" || arg === "--env-file") {
23
+ const value = argv[index + 1];
24
+ if (!value || value.startsWith("--")) {
25
+ throw new Error(`${arg} requires a value.`);
26
+ }
27
+ if (arg === "--cwd") cwd = value;
28
+ else envFile = value;
29
+ index++;
30
+ continue;
31
+ }
32
+ if (arg !== "--set") {
33
+ throw new Error(`run 不支持的参数: ${arg}`);
34
+ }
35
+
36
+ const assignment = argv[index + 1];
37
+ if (!assignment) throw new Error("--set requires NAME=VALUE.");
38
+ const equalsIndex = assignment.indexOf("=");
39
+ const name = equalsIndex > 0 ? assignment.slice(0, equalsIndex) : "";
40
+ if (!ENV_NAME_PATTERN.test(name)) {
41
+ throw new Error(`Invalid environment assignment: ${assignment}`);
42
+ }
43
+ env[name] = assignment.slice(equalsIndex + 1);
44
+ index++;
45
+ }
46
+
47
+ if (separatorIndex < 0 || !argv[separatorIndex + 1]) {
48
+ throw new Error("Usage: infly-libs run [--set NAME=VALUE] -- <command> [...args]");
49
+ }
50
+
51
+ return {
52
+ env,
53
+ cwd,
54
+ envFile,
55
+ command: argv[separatorIndex + 1],
56
+ args: argv.slice(separatorIndex + 2)
57
+ };
58
+ }
59
+
60
+ async function runCommand(argv, dependencies = {}) {
61
+ const {
62
+ run = defaultRunCommand,
63
+ cwd: baseCwd = process.cwd(),
64
+ baseEnv = process.env
65
+ } = dependencies;
66
+ const parsed = parseRunArgs(argv);
67
+ const commandCwd = path.resolve(baseCwd, parsed.cwd);
68
+ let fileEnv = {};
69
+ if (parsed.envFile) {
70
+ const envPath = path.resolve(baseCwd, parsed.envFile);
71
+ if (!fs.existsSync(envPath)) throw new Error(`Environment file not found: ${envPath}`);
72
+ fileEnv = dotenv.parse(fs.readFileSync(envPath));
73
+ }
74
+ await run(parsed.command, parsed.args, {
75
+ cwd: commandCwd,
76
+ env: { ...fileEnv, ...baseEnv, ...parsed.env }
77
+ });
78
+ return parsed;
79
+ }
80
+
81
+ module.exports = { parseRunArgs, runCommand };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infly/libs",
3
- "version": "2.2.6",
3
+ "version": "2.2.8",
4
4
  "description": "不受前端框架限制的独立工具库",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -18,15 +18,17 @@ function getCurrentBranch() {
18
18
  * 获取 Git 提交信息
19
19
  * @returns {Object} 包含提交信息的对象,如果获取失败则返回空对象
20
20
  */
21
- function getLatestCommitInfo() {
21
+ function getLatestCommitInfo(cwd = process.cwd()) {
22
22
  // 定义 Git 命令
23
23
  const commands = {
24
- commitMsg: "git log -1 --no-merges --pretty=%B",
24
+ // 构建元数据必须全部对应源码 HEAD。跳过 merge commit 会导致 fullHash 指向
25
+ // 当前合并提交,而文案、作者却回退到更早的版本构建提交。
26
+ commitMsg: "git log -1 --pretty=%B",
25
27
  branch: "git rev-parse --abbrev-ref HEAD",
26
28
  fullHash: "git rev-parse HEAD",
27
- author: "git log -1 --no-merges --pretty=%an",
28
- email: "git log -1 --no-merges --pretty=%ae",
29
- date: "git log -1 --no-merges --pretty=%cd --date=iso"
29
+ author: "git log -1 --pretty=%an",
30
+ email: "git log -1 --pretty=%ae",
31
+ date: "git log -1 --pretty=%cd --date=iso"
30
32
  };
31
33
 
32
34
  // 结果对象
@@ -34,12 +36,12 @@ function getLatestCommitInfo() {
34
36
 
35
37
  try {
36
38
  // 检查当前目录是否是 Git 仓库
37
- execSync("git rev-parse --is-inside-work-tree", { stdio: "ignore" });
39
+ execSync("git rev-parse --is-inside-work-tree", { cwd, stdio: "ignore" });
38
40
 
39
41
  // 遍历命令并执行
40
42
  for (const [key, command] of Object.entries(commands)) {
41
43
  try {
42
- commitInfo[key] = execSync(`${command}`, { encoding: "utf-8" }).trim();
44
+ commitInfo[key] = execSync(`${command}`, { cwd, encoding: "utf-8" }).trim();
43
45
  } catch (cmdError) {
44
46
  console.warn(global.logColor.warning, `⚠️️ 获取 Git 信息失败(${key}):${cmdError.message}`);
45
47
  commitInfo[key] = ""; // 失败时设置为空字符串
@@ -56,6 +58,64 @@ function getLatestCommitInfo() {
56
58
  return commitInfo;
57
59
  }
58
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
+ /**
71
+ * 获取上一次自动版本提交之后的业务提交摘要。
72
+ * Merge 提交只描述 Git 操作,不作为企业微信中的更新内容。
73
+ * @param {String} gitAutoCommitText 自动版本提交模板
74
+ * @param {String} cwd Git 仓库目录
75
+ * @param {Number} limit 最多展示的提交数
76
+ * @returns {String} 构建更新摘要;无法识别版本基线时返回空字符串
77
+ */
78
+ function getBuildUpdateText(gitAutoCommitText, cwd = process.cwd(), limit = 10) {
79
+ const matcher = createCommitTextMatcher(gitAutoCommitText);
80
+ if (!matcher) return "";
81
+
82
+ try {
83
+ const history = execSync("git log --format=%H%x1f%s", { cwd, encoding: "utf-8" })
84
+ .trim()
85
+ .split(/\r?\n/)
86
+ .filter(Boolean)
87
+ .map((line) => {
88
+ const separatorIndex = line.indexOf("\x1f");
89
+ return {
90
+ hash: line.slice(0, separatorIndex),
91
+ subject: line.slice(separatorIndex + 1)
92
+ };
93
+ });
94
+ const previousBuild = history.find(({ hash, subject }) => /^[0-9a-f]{40}$/i.test(hash) && matcher.test(subject));
95
+
96
+ if (!previousBuild) return "";
97
+
98
+ const subjects = execSync(`git log --no-merges --format=%s ${previousBuild.hash}..HEAD`, {
99
+ cwd,
100
+ encoding: "utf-8"
101
+ })
102
+ .trim()
103
+ .split(/\r?\n/)
104
+ .filter(Boolean);
105
+
106
+ if (subjects.length === 0) return "无源码提交变更";
107
+
108
+ const visibleSubjects = subjects.slice(0, limit);
109
+ if (subjects.length > limit) {
110
+ visibleSubjects.push(`...另 ${subjects.length - limit} 条提交`);
111
+ }
112
+ return visibleSubjects.map((subject) => `- ${subject}`).join("\n");
113
+ } catch (error) {
114
+ console.warn(global.logColor.warning, `⚠️️ 获取构建更新摘要失败:${error.message}`);
115
+ return "";
116
+ }
117
+ }
118
+
59
119
  /**
60
120
  * 获取指定文件的最后一次提交信息
61
121
  * @param {String} filePath - 文件路径
@@ -703,6 +763,7 @@ async function checkAndUpdatePackages(outPackagesDir, targetBranch = "master") {
703
763
  module.exports = {
704
764
  getCurrentBranch,
705
765
  getLatestCommitInfo,
766
+ getBuildUpdateText,
706
767
  getLastCommitByFile,
707
768
  checkGitStatus,
708
769
  autoGitProcess,