@infly/libs 2.7.0 → 2.7.2

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
 
@@ -1,57 +1,57 @@
1
1
  /**
2
2
  * Webpack require.context 适配器。
3
- * 自动导出目录下所有文件
4
- * @param {Function} requireContext - require.context 返回的函数
5
- * @returns {Object} 导出对象,key 为文件名(不含扩展名),value 为模块内容
6
- *
7
- * @example
8
- * // 在 components/Dialog/index.js 中使用
3
+ * 自动导出目录下所有文件
4
+ * @param {Function} requireContext - require.context 返回的函数
5
+ * @returns {Object} 导出对象,key 为文件名(不含扩展名),value 为模块内容
6
+ *
7
+ * @example
8
+ * // 在 components/Dialog/index.js 中使用
9
9
  * import { autoExportFiles } from '@infly/libs/adapters/webpack/auto-export';
10
- * const components = autoExportFiles(require.context('./', false, /\.vue$/));
11
- * Object.keys(components).forEach(name => {
12
- * module.exports[name] = components[name];
13
- * });
14
- *
15
- * // 或者直接一行
16
- * Object.assign(module.exports, autoExportFiles(require.context('./', false, /\.vue$/)));
17
- */
18
- const { logTerminal } = require("../../cli/terminal-style");
19
- function autoExportFiles(requireContext) {
20
- if (!requireContext || typeof requireContext !== 'function') {
21
- logTerminal("error", 'autoExportFiles: requireContext 必须是 require.context 返回的函数');
22
- return {};
23
- }
24
-
25
- const exports = {};
26
-
27
- requireContext.keys().forEach(fileName => {
28
- // 跳过 index 文件自身
29
- if (fileName.includes('index')) return;
30
-
31
- const componentConfig = requireContext(fileName);
32
- const componentName = fileName
33
- .replace(/^\.\//, '') // 移除 './'
34
- .replace(/\.\w+$/, ''); // 移除扩展名
35
-
36
- exports[componentName] = componentConfig.default || componentConfig;
37
- });
38
-
39
- return exports;
40
- }
41
-
42
- /**
43
- * 简化版:直接挂载到 module.exports
44
- * @param {Function} requireContext - require.context 返回的函数
45
- * @param {Object} targetExports - 目标导出对象(通常是 module.exports)
46
- *
47
- * @example
48
- * // 在 components/Dialog/index.js 中使用
10
+ * const components = autoExportFiles(require.context('./', false, /\.vue$/));
11
+ * Object.keys(components).forEach(name => {
12
+ * module.exports[name] = components[name];
13
+ * });
14
+ *
15
+ * // 或者直接一行
16
+ * Object.assign(module.exports, autoExportFiles(require.context('./', false, /\.vue$/)));
17
+ */
18
+ const { logTerminal } = require("../../cli/terminal-style");
19
+ function autoExportFiles(requireContext) {
20
+ if (!requireContext || typeof requireContext !== 'function') {
21
+ logTerminal("error", 'autoExportFiles: requireContext 必须是 require.context 返回的函数');
22
+ return {};
23
+ }
24
+
25
+ const exports = {};
26
+
27
+ requireContext.keys().forEach(fileName => {
28
+ // 跳过 index 文件自身
29
+ if (fileName.includes('index')) return;
30
+
31
+ const componentConfig = requireContext(fileName);
32
+ const componentName = fileName
33
+ .replace(/^\.\//, '') // 移除 './'
34
+ .replace(/\.\w+$/, ''); // 移除扩展名
35
+
36
+ exports[componentName] = componentConfig.default || componentConfig;
37
+ });
38
+
39
+ return exports;
40
+ }
41
+
42
+ /**
43
+ * 简化版:直接挂载到 module.exports
44
+ * @param {Function} requireContext - require.context 返回的函数
45
+ * @param {Object} targetExports - 目标导出对象(通常是 module.exports)
46
+ *
47
+ * @example
48
+ * // 在 components/Dialog/index.js 中使用
49
49
  * import { autoExportToModule } from '@infly/libs/adapters/webpack/auto-export';
50
- * autoExportToModule(require.context('./', false, /\.vue$/), module.exports);
51
- */
52
- function autoExportToModule(requireContext, targetExports) {
53
- const files = autoExportFiles(requireContext);
54
- Object.assign(targetExports, files);
55
- }
56
-
57
- export { autoExportFiles, autoExportToModule };
50
+ * autoExportToModule(require.context('./', false, /\.vue$/), module.exports);
51
+ */
52
+ function autoExportToModule(requireContext, targetExports) {
53
+ const files = autoExportFiles(requireContext);
54
+ Object.assign(targetExports, files);
55
+ }
56
+
57
+ export { autoExportFiles, autoExportToModule };
@@ -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
 
@@ -1,20 +1,20 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
-
4
- /**
5
- * 从项目的 webpack/vite 等构建配置中解析对兄弟 app 的依赖。
6
- *
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+
4
+ /**
5
+ * 从项目的 webpack/vite 等构建配置中解析对兄弟 app 的依赖。
6
+ *
7
7
  * 规则:如果 vue.config.js / vite.config.* / next.config.* 的 alias 中存在指向 ../ 的路径,
8
- * 则认为当前项目依赖该兄弟 app,构建前需要确保兄弟 app 源码是最新的。
9
- *
10
- * 示例(vue.config.js):
11
- * alias: {
12
- * "@example-admin": projectResolve("../example-admin/src")
13
- * }
14
- *
15
- * @param {string} appDir - 当前 app 目录的绝对路径
16
- * @returns {string[]} 兄弟 app 根目录(含 package.json)的绝对路径列表
17
- */
8
+ * 则认为当前项目依赖该兄弟 app,构建前需要确保兄弟 app 源码是最新的。
9
+ *
10
+ * 示例(vue.config.js):
11
+ * alias: {
12
+ * "@example-admin": projectResolve("../example-admin/src")
13
+ * }
14
+ *
15
+ * @param {string} appDir - 当前 app 目录的绝对路径
16
+ * @returns {string[]} 兄弟 app 根目录(含 package.json)的绝对路径列表
17
+ */
18
18
  function resolveSiblingAppDeps(appDir) {
19
19
  const siblings = [];
20
20
  const configFiles = [
@@ -51,13 +51,13 @@ function resolveSiblingAppDeps(appDir) {
51
51
  addSibling(match[2]);
52
52
  }
53
53
  }
54
-
55
- for (const configFile of configFiles) {
56
- const configPath = path.join(appDir, configFile);
57
- if (!fs.existsSync(configPath)) continue;
58
-
59
- const content = fs.readFileSync(configPath, "utf8");
60
-
54
+
55
+ for (const configFile of configFiles) {
56
+ const configPath = path.join(appDir, configFile);
57
+ if (!fs.existsSync(configPath)) continue;
58
+
59
+ const content = fs.readFileSync(configPath, "utf8");
60
+
61
61
  // 匹配 alias 中指向 ../ 兄弟目录的值,兼容以下写法:
62
62
  // "@foo": projectResolve("../foo/src")
63
63
  // "@foo": resolve("../foo/src")
@@ -77,8 +77,8 @@ function resolveSiblingAppDeps(appDir) {
77
77
 
78
78
  [...objectAliasPatterns, ...arrayAliasPatterns].forEach((pattern) => collectMatches(content, pattern));
79
79
  }
80
-
81
- return siblings;
82
- }
83
-
84
- module.exports = { resolveSiblingAppDeps };
80
+
81
+ return siblings;
82
+ }
83
+
84
+ module.exports = { resolveSiblingAppDeps };
@@ -1,135 +1,135 @@
1
- const fs = require("fs");
2
- const { formatReleaseResult, resolveWebhookUrl } = require("../release-result");
3
-
4
- function shouldSkipWebhook(args = process.argv, env = process.env) {
5
- return args.some((arg) => ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg))
6
- || [env.npm_config_nowebhook, env.npm_config_noWebhook, env.NO_WEBHOOK, env.DISABLE_WEBHOOK]
7
- .some((value) => ["1", "true", "yes", "on"].includes(String(value || "").toLowerCase()));
8
- }
9
-
10
- function getWebhookMessage(args = process.argv, env = process.env) {
11
- const configured = env.npm_config_m || env.npm_config_message || env.WEBHOOK_MESSAGE || env.BUILD_MESSAGE;
12
- if (configured) return String(configured).trim();
13
- for (let index = 0; index < args.length; index++) {
14
- const arg = args[index] || "";
15
- if (["-m", "--message"].includes(arg)) return String(args[index + 1] || "").trim();
16
- if (arg.startsWith("-m=")) return arg.slice(3).trim();
17
- if (arg.startsWith("--message=")) return arg.slice(10).trim();
18
- }
19
- return "";
20
- }
21
-
22
- async function sendWebhookContent(content, options = {}, dependencies = {}) {
23
- const env = dependencies.env || process.env;
24
- const logger = dependencies.logger || console;
25
- const webhookUrl = resolveWebhookUrl(options, env);
26
- if (!webhookUrl) return false;
27
- const { webhookAtUser = [], gitInfo = {} } = options;
28
- const mentions = Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[gitInfo.branch];
29
- try {
30
- const response = await (dependencies.httpClient || require("axios")).post(webhookUrl, {
31
- msgtype: "text", text: {
32
- content: String(content || "").replace(/%s/g, ""), mentioned_mobile_list: mentions,
33
- },
34
- }, { timeout: 15000, headers: { "Content-Type": "application/json" } });
35
- if (response.data?.errcode !== 0) throw new Error('WEBHOOK_REJECTED');
36
- return true;
37
- } catch (error) {
38
- // Axios error/config 可能包含完整凭据 URL,日志只输出受限错误码。
39
- const code = /^[A-Z0-9_]{1,40}$/.test(error.code || '') ? error.code : 'WEBHOOK_FAILED';
40
- logger.error("企业微信推送失败", code);
41
- return false;
42
- }
43
- }
44
-
45
- function getRecordContent(record, deployUrl) {
46
- if (record?.extraParams?.releaseResult) return formatReleaseResult(record.extraParams.releaseResult);
47
- const { publishText = "", extraParams = {} } = record || {};
48
- const {
49
- gitInfo = {},
50
- gitAutoPushReposBranchMap,
51
- repos,
52
- newFileName,
53
- projectName,
54
- webhookExtraText = ""
55
- } = extraParams;
56
- const { branch, author } = gitInfo || {};
57
-
58
- if (gitAutoPushReposBranchMap) {
59
- const targetBranch = gitAutoPushReposBranchMap[branch] || branch || "";
60
- return [
61
- publishText,
62
- `构建文件:已推送对应仓库【${repos || ""}】- 分支【${targetBranch}】`,
63
- `构建人:${author || ""}`,
64
- deployUrl ? `部署系统:${deployUrl}` : ""
65
- ]
66
- .filter(Boolean)
67
- .join("\n");
68
- }
69
-
70
- const gitPath =
71
- projectName && branch && newFileName
72
- ? `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`
73
- : "";
74
-
75
- return [
76
- publishText,
77
- gitPath ? `构建文件下载地址:${gitPath}` : "",
78
- webhookExtraText
79
- ]
80
- .filter(Boolean)
81
- .join("\n");
82
- }
83
-
84
- async function postBatchWebhook(batchWebhookFile, extraArgs = [], mode, dependencies = {}) {
85
- if (shouldSkipWebhook(extraArgs, dependencies.env || process.env)) {
86
- console.log("\n已跳过企业微信机器人汇总推送(nowebhook)");
87
- return;
88
- }
89
-
90
- if (!fs.existsSync(batchWebhookFile)) {
91
- return;
92
- }
93
-
94
- const records = fs
95
- .readFileSync(batchWebhookFile, "utf8")
96
- .split(/\r?\n/)
97
- .filter(Boolean)
98
- .map((line) => JSON.parse(line));
99
-
100
- if (records.length === 0) {
101
- return;
102
- }
103
-
104
- const [firstRecord] = records;
105
- const { deployUrl = "" } =
106
- firstRecord.extraParams || {};
107
-
108
- let content = [
109
- records.map((record) => getRecordContent(record, deployUrl)).join("\n\n")
110
- ].join("\n");
111
- // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
112
- content = (content || "").replace(/%s/g, "");
113
- if (await sendWebhookContent(content, firstRecord.extraParams, dependencies)) {
114
- console.log("\n已发送批量构建企业微信汇总推送");
115
- }
116
- }
117
-
118
- function postVersionFileAndMsg(publishText, extraParams = {}, dependencies = {}) {
119
- const env = dependencies.env || process.env;
120
- const args = dependencies.args || process.argv;
121
- if (shouldSkipWebhook(args, env)) return;
122
- let content = getRecordContent({ publishText, extraParams }, extraParams.deployUrl);
123
- const message = getWebhookMessage(args, env);
124
- if (message && !extraParams.releaseResult) content += `\n${message}`;
125
- return sendWebhookContent(content, extraParams, dependencies);
126
- }
127
-
128
- module.exports = {
129
- getRecordContent,
130
- getWebhookMessage,
131
- shouldSkipWebhook,
132
- sendWebhookContent,
133
- postVersionFileAndMsg,
134
- postBatchWebhook
135
- };
1
+ const fs = require("fs");
2
+ const { formatReleaseResult, resolveWebhookUrl } = require("../release-result");
3
+
4
+ function shouldSkipWebhook(args = process.argv, env = process.env) {
5
+ return args.some((arg) => ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg))
6
+ || [env.npm_config_nowebhook, env.npm_config_noWebhook, env.NO_WEBHOOK, env.DISABLE_WEBHOOK]
7
+ .some((value) => ["1", "true", "yes", "on"].includes(String(value || "").toLowerCase()));
8
+ }
9
+
10
+ function getWebhookMessage(args = process.argv, env = process.env) {
11
+ const configured = env.npm_config_m || env.npm_config_message || env.WEBHOOK_MESSAGE || env.BUILD_MESSAGE;
12
+ if (configured) return String(configured).trim();
13
+ for (let index = 0; index < args.length; index++) {
14
+ const arg = args[index] || "";
15
+ if (["-m", "--message"].includes(arg)) return String(args[index + 1] || "").trim();
16
+ if (arg.startsWith("-m=")) return arg.slice(3).trim();
17
+ if (arg.startsWith("--message=")) return arg.slice(10).trim();
18
+ }
19
+ return "";
20
+ }
21
+
22
+ async function sendWebhookContent(content, options = {}, dependencies = {}) {
23
+ const env = dependencies.env || process.env;
24
+ const logger = dependencies.logger || console;
25
+ const webhookUrl = resolveWebhookUrl(options, env);
26
+ if (!webhookUrl) return false;
27
+ const { webhookAtUser = [], gitInfo = {} } = options;
28
+ const mentions = Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[gitInfo.branch];
29
+ try {
30
+ const response = await (dependencies.httpClient || require("axios")).post(webhookUrl, {
31
+ msgtype: "text", text: {
32
+ content: String(content || "").replace(/%s/g, ""), mentioned_mobile_list: mentions,
33
+ },
34
+ }, { timeout: 15000, headers: { "Content-Type": "application/json" } });
35
+ if (response.data?.errcode !== 0) throw new Error('WEBHOOK_REJECTED');
36
+ return true;
37
+ } catch (error) {
38
+ // Axios error/config 可能包含完整凭据 URL,日志只输出受限错误码。
39
+ const code = /^[A-Z0-9_]{1,40}$/.test(error.code || '') ? error.code : 'WEBHOOK_FAILED';
40
+ logger.error("企业微信推送失败", code);
41
+ return false;
42
+ }
43
+ }
44
+
45
+ function getRecordContent(record, deployUrl) {
46
+ if (record?.extraParams?.releaseResult) return formatReleaseResult(record.extraParams.releaseResult);
47
+ const { publishText = "", extraParams = {} } = record || {};
48
+ const {
49
+ gitInfo = {},
50
+ gitAutoPushReposBranchMap,
51
+ repos,
52
+ newFileName,
53
+ projectName,
54
+ webhookExtraText = ""
55
+ } = extraParams;
56
+ const { branch, author } = gitInfo || {};
57
+
58
+ if (gitAutoPushReposBranchMap) {
59
+ const targetBranch = gitAutoPushReposBranchMap[branch] || branch || "";
60
+ return [
61
+ publishText,
62
+ `构建文件:已推送对应仓库【${repos || ""}】- 分支【${targetBranch}】`,
63
+ `构建人:${author || ""}`,
64
+ deployUrl ? `部署系统:${deployUrl}` : ""
65
+ ]
66
+ .filter(Boolean)
67
+ .join("\n");
68
+ }
69
+
70
+ const gitPath =
71
+ projectName && branch && newFileName
72
+ ? `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`
73
+ : "";
74
+
75
+ return [
76
+ publishText,
77
+ gitPath ? `构建文件下载地址:${gitPath}` : "",
78
+ webhookExtraText
79
+ ]
80
+ .filter(Boolean)
81
+ .join("\n");
82
+ }
83
+
84
+ async function postBatchWebhook(batchWebhookFile, extraArgs = [], mode, dependencies = {}) {
85
+ if (shouldSkipWebhook(extraArgs, dependencies.env || process.env)) {
86
+ console.log("\n已跳过企业微信机器人汇总推送(nowebhook)");
87
+ return;
88
+ }
89
+
90
+ if (!fs.existsSync(batchWebhookFile)) {
91
+ return;
92
+ }
93
+
94
+ const records = fs
95
+ .readFileSync(batchWebhookFile, "utf8")
96
+ .split(/\r?\n/)
97
+ .filter(Boolean)
98
+ .map((line) => JSON.parse(line));
99
+
100
+ if (records.length === 0) {
101
+ return;
102
+ }
103
+
104
+ const [firstRecord] = records;
105
+ const { deployUrl = "" } =
106
+ firstRecord.extraParams || {};
107
+
108
+ let content = [
109
+ records.map((record) => getRecordContent(record, deployUrl)).join("\n\n")
110
+ ].join("\n");
111
+ // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
112
+ content = (content || "").replace(/%s/g, "");
113
+ if (await sendWebhookContent(content, firstRecord.extraParams, dependencies)) {
114
+ console.log("\n已发送批量构建企业微信汇总推送");
115
+ }
116
+ }
117
+
118
+ function postVersionFileAndMsg(publishText, extraParams = {}, dependencies = {}) {
119
+ const env = dependencies.env || process.env;
120
+ const args = dependencies.args || process.argv;
121
+ if (shouldSkipWebhook(args, env)) return;
122
+ let content = getRecordContent({ publishText, extraParams }, extraParams.deployUrl);
123
+ const message = getWebhookMessage(args, env);
124
+ if (message && !extraParams.releaseResult) content += `\n${message}`;
125
+ return sendWebhookContent(content, extraParams, dependencies);
126
+ }
127
+
128
+ module.exports = {
129
+ getRecordContent,
130
+ getWebhookMessage,
131
+ shouldSkipWebhook,
132
+ sendWebhookContent,
133
+ postVersionFileAndMsg,
134
+ postBatchWebhook
135
+ };
@@ -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; }