@infly/libs 2.5.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +502 -469
  2. package/adapters/vue2/project-preview.js +9 -16
  3. package/adapters/webpack/auto-export.js +53 -52
  4. package/bin/cli.js +3 -2
  5. package/build/build-dist/index.js +34 -44
  6. package/build/build-utils/command.js +58 -57
  7. package/build/build-utils/deps.js +28 -28
  8. package/build/build-utils/git.js +246 -254
  9. package/build/build-utils/preview.js +79 -78
  10. package/build/build-utils/webhook.js +135 -135
  11. package/build/docker/compose-release.js +7 -9
  12. package/build/docker/deployment/health-check.sh +5 -1
  13. package/build/docker/deployment/promote-image.sh +75 -5
  14. package/build/docker/deployment/release.sh +5 -1
  15. package/build/docker/docker-build-push.js +23 -23
  16. package/build/docker/project-install.js +42 -35
  17. package/build/docker/release-docker.js +7 -25
  18. package/build/docker/release-mode.js +7 -25
  19. package/build/docker/release-paths.js +30 -0
  20. package/build/docker/release-validation.js +248 -0
  21. package/build/docker/source-snapshot.js +2 -1
  22. package/build/docker/target-image.js +227 -0
  23. package/build/docker/target-release.js +540 -860
  24. package/build/project-files.js +47 -47
  25. package/cli/progress.js +4 -11
  26. package/cli/terminal-style.js +40 -0
  27. package/core/async/concurrency.js +29 -29
  28. package/jenkins/README.md +94 -0
  29. package/jenkins/src/com/infly/jenkins/BuildProvenance.groovy +16 -0
  30. package/jenkins/src/com/infly/jenkins/PipelineJson.groovy +28 -0
  31. package/jenkins/src/com/infly/jenkins/ReleaseNotification.groovy +86 -0
  32. package/jenkins/vars/inflyNotify.groovy +83 -0
  33. package/package.json +4 -1
  34. package/script/git-automation/check-packages.js +5 -12
  35. package/script/git-automation/git-clone.js +6 -5
  36. package/script/git-automation/git-configure.js +3 -3
  37. package/script/git-automation/git-submodule.js +3 -2
  38. package/script/git-automation/git-utils.js +59 -59
  39. package/script/git-automation/index.js +813 -828
  40. package/script/git-automation/submodule-utils.js +16 -16
  41. package/workspace/config.js +144 -144
@@ -3,53 +3,53 @@ const path = require("path");
3
3
 
4
4
  // 兼容旧 tools/file-process.js 的 __dirname 路径语义。
5
5
  const legacyToolsDir = path.resolve(__dirname, "../tools");
6
-
7
- /**
8
- * 覆盖写入构建脚本
9
- * @param {String} filePath - 覆盖文件路径
10
- * @param {Array | Object} scriptsList - 写入脚本配置
11
- * @param {String} 更新字段值
12
- */
13
- function scriptWrite(filePath, scriptsList, updateKey = "scripts") {
14
- const pkg = JSON.parse(fs.readFileSync(filePath));
15
- pkg[updateKey] = pkg[updateKey] || {};
16
- if (Array.isArray(scriptsList)) {
17
- scriptsList.forEach(item => {
18
- if (pkg[updateKey][item.key]) {
19
- pkg[updateKey][`origin:${item.key}`] = pkg[updateKey][item.key];
20
- }
21
- pkg[updateKey][item.key] = item.value;
22
- });
23
- } else if (typeof scriptsList === "object") {
24
- pkg[updateKey] = scriptsList;
25
- }
26
-
27
- fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2));
28
- }
29
-
30
- /**
31
- * 获取文件绝对路径
32
- * @param {String} filePath - 文件路径
33
- * @returns
34
- */
35
- function targetProjectFileResolve(filePath) {
36
- // 初始脚本自动执行路径会自动读取node_modules
37
- const projectRoot = process.cwd();
38
- const absoluteProjectRoot = projectRoot.replace(/\\node_modules.*$/g, "");
39
- return path.resolve(absoluteProjectRoot, filePath);
40
- }
41
-
42
- /**
43
- * 获取文件绝对路径
44
- * @param {String} filePath - 文件路径
45
- * @returns
46
- */
6
+
7
+ /**
8
+ * 覆盖写入构建脚本
9
+ * @param {String} filePath - 覆盖文件路径
10
+ * @param {Array | Object} scriptsList - 写入脚本配置
11
+ * @param {String} 更新字段值
12
+ */
13
+ function scriptWrite(filePath, scriptsList, updateKey = "scripts") {
14
+ const pkg = JSON.parse(fs.readFileSync(filePath));
15
+ pkg[updateKey] = pkg[updateKey] || {};
16
+ if (Array.isArray(scriptsList)) {
17
+ scriptsList.forEach(item => {
18
+ if (pkg[updateKey][item.key]) {
19
+ pkg[updateKey][`origin:${item.key}`] = pkg[updateKey][item.key];
20
+ }
21
+ pkg[updateKey][item.key] = item.value;
22
+ });
23
+ } else if (typeof scriptsList === "object") {
24
+ pkg[updateKey] = scriptsList;
25
+ }
26
+
27
+ fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2));
28
+ }
29
+
30
+ /**
31
+ * 获取文件绝对路径
32
+ * @param {String} filePath - 文件路径
33
+ * @returns
34
+ */
35
+ function targetProjectFileResolve(filePath) {
36
+ // 初始脚本自动执行路径会自动读取node_modules
37
+ const projectRoot = process.cwd();
38
+ const absoluteProjectRoot = projectRoot.replace(/\\node_modules.*$/g, "");
39
+ return path.resolve(absoluteProjectRoot, filePath);
40
+ }
41
+
42
+ /**
43
+ * 获取文件绝对路径
44
+ * @param {String} filePath - 文件路径
45
+ * @returns
46
+ */
47
47
  function currentProjectFileResolve(filePath) {
48
48
  return path.join(legacyToolsDir, filePath);
49
49
  }
50
-
51
- module.exports = {
52
- scriptWrite,
53
- targetProjectFileResolve,
54
- currentProjectFileResolve
55
- };
50
+
51
+ module.exports = {
52
+ scriptWrite,
53
+ targetProjectFileResolve,
54
+ currentProjectFileResolve
55
+ };
package/cli/progress.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // CLI 与终端流程的进度呈现能力。
2
+ const { formatTerminalMessage } = require("./terminal-style");
2
3
  function formatProgressLine({ label, completed, total, path = "" }) {
3
4
  const safeTotal = Math.max(total, 1);
4
5
  const percentage = total === 0 ? 100 : Math.round((completed / safeTotal) * 100);
@@ -10,10 +11,6 @@ function formatProgressLine({ label, completed, total, path = "" }) {
10
11
  function createProgressReporter(options = {}) {
11
12
  const stream = options.stream || process.stdout;
12
13
  const quiet = Boolean(options.quiet);
13
- const env = options.env || process.env;
14
- const useColor = Boolean(stream.isTTY)
15
- && !Object.prototype.hasOwnProperty.call(env, "NO_COLOR")
16
- && env.FORCE_COLOR !== "0";
17
14
  const defaultLabels = {
18
15
  status: "检查状态",
19
16
  deinit: "停用模块",
@@ -28,11 +25,7 @@ function createProgressReporter(options = {}) {
28
25
  label: labels[event.phase],
29
26
  });
30
27
  if (stream.isTTY) {
31
- const label = labels[event.phase];
32
- const displayedLine = useColor
33
- ? `\x1b[36m${label}\x1b[0m${line.slice(label.length)}`
34
- : line;
35
- stream.write(`\r${displayedLine}\x1b[K${event.done || event.completed >= event.total ? "\n" : ""}`);
28
+ stream.write(`\r${line}\x1b[K${event.done || event.completed >= event.total ? "\n" : ""}`);
36
29
  return;
37
30
  }
38
31
  if (event.completed === 0 || event.done || event.completed >= event.total) stream.write(`${line}\n`);
@@ -43,9 +36,9 @@ function formatSwitchSummary(name, totalMs, dependencyResult) {
43
36
  const seconds = (totalMs / 1000).toFixed(1);
44
37
  const dependencyLabel = dependencyResult.installed ? ",依赖已更新" : "";
45
38
  const skipWarning = dependencyResult.reason === "skipped"
46
- ? "\n⚠️ 已跳过依赖安装,后续 dev 缺依赖时请手动 pnpm install"
39
+ ? formatTerminalMessage("warning", "\n已跳过依赖安装,后续 dev 缺依赖时请手动 pnpm install")
47
40
  : "";
48
- return `\n✅ ${name}(${seconds}s${dependencyLabel})${skipWarning}`;
41
+ return formatTerminalMessage("success", `\n${name}(${seconds}s${dependencyLabel})${skipWarning}`);
49
42
  }
50
43
 
51
44
  function formatSlowStatusDetails(details, thresholdMs = 2000) {
@@ -0,0 +1,40 @@
1
+ // 与根仓自举脚本的 CLI 格式保持一致。发布包可独立运行。
2
+ const { format } = require("node:util");
3
+
4
+ function supportsTerminalColor(stream = process.stdout, env = process.env) {
5
+ return Boolean(stream.isTTY) && !Object.hasOwn(env, "NO_COLOR") && env.FORCE_COLOR !== "0";
6
+ }
7
+
8
+ function formatTerminalMessage(level, message, stream = process.stdout, env = process.env) {
9
+ let prefix;
10
+ switch (level) {
11
+ case "success":
12
+ prefix = stream.isTTY ? "√ " : "完成: ";
13
+ break;
14
+ case "warning":
15
+ prefix = "warning: ";
16
+ break;
17
+ case "error":
18
+ prefix = "error: ";
19
+ break;
20
+ default:
21
+ return String(message);
22
+ }
23
+ const text = String(message);
24
+ const trimmed = text.trimStart();
25
+ const color = level === "success" && supportsTerminalColor(stream, env);
26
+ if (color && trimmed.startsWith(`\x1b[32m${prefix.trimEnd()}`)) return text;
27
+ const line = trimmed.startsWith(prefix.trimEnd()) ? text : text.replace(/^\s*/, (indent) => indent + prefix);
28
+ return color ? line.replace(/\S[^\r\n]*/, (summary) => `\x1b[32m${summary}\x1b[0m`) : line;
29
+ }
30
+
31
+ function logTerminal(level, ...args) {
32
+ const isDiagnostic = level === "warning" || level === "error";
33
+ const stream = isDiagnostic ? process.stderr : process.stdout;
34
+ const message = formatTerminalMessage(level, format(...args), stream);
35
+ if (level === "error") console.error(message);
36
+ else if (level === "warning") console.warn(message);
37
+ else console.log(message);
38
+ }
39
+
40
+ module.exports = { formatTerminalMessage, logTerminal, supportsTerminalColor };
@@ -1,31 +1,31 @@
1
1
  /**
2
2
  * 框架无关的异步并发控制。
3
- * 异步并发限流器。
4
- * 对 items 数组中的每一项执行 worker,同时最多运行 concurrency 个 worker。
5
- *
6
- * @param {Array} items - 待处理项
7
- * @param {number} concurrency - 最大并发数
8
- * @param {Function} worker - 处理函数 (item, index) => Promise
9
- * @returns {Promise<Array>} 结果数组,索引与 items 一一对应
10
- */
11
- async function runWithConcurrency(items, concurrency, worker) {
12
- if (!Number.isInteger(concurrency) || concurrency < 1) {
13
- throw new TypeError("concurrency must be a positive integer");
14
- }
15
-
16
- const results = new Array(items.length);
17
- let nextIndex = 0;
18
- const runWorker = async () => {
19
- while (nextIndex < items.length) {
20
- const index = nextIndex;
21
- nextIndex += 1;
22
- results[index] = await worker(items[index], index);
23
- }
24
- };
25
-
26
- const workerCount = Math.min(concurrency, items.length);
27
- await Promise.all(Array.from({ length: workerCount }, runWorker));
28
- return results;
29
- }
30
-
31
- module.exports = { runWithConcurrency };
3
+ * 异步并发限流器。
4
+ * 对 items 数组中的每一项执行 worker,同时最多运行 concurrency 个 worker。
5
+ *
6
+ * @param {Array} items - 待处理项
7
+ * @param {number} concurrency - 最大并发数
8
+ * @param {Function} worker - 处理函数 (item, index) => Promise
9
+ * @returns {Promise<Array>} 结果数组,索引与 items 一一对应
10
+ */
11
+ async function runWithConcurrency(items, concurrency, worker) {
12
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
13
+ throw new TypeError("concurrency must be a positive integer");
14
+ }
15
+
16
+ const results = new Array(items.length);
17
+ let nextIndex = 0;
18
+ const runWorker = async () => {
19
+ while (nextIndex < items.length) {
20
+ const index = nextIndex;
21
+ nextIndex += 1;
22
+ results[index] = await worker(items[index], index);
23
+ }
24
+ };
25
+
26
+ const workerCount = Math.min(concurrency, items.length);
27
+ await Promise.all(Array.from({ length: workerCount }, runWorker));
28
+ return results;
29
+ }
30
+
31
+ module.exports = { runWithConcurrency };
@@ -0,0 +1,94 @@
1
+ # Jenkins 公共部署能力
2
+
3
+ 积分商城、智慧场景案例集、邮惠权益的前后端流水线共用 `inflyNotify`。模板、组件名称、更新时间、日志链接、所有人提醒、请求超时、响应校验和临时文件清理由本目录维护。
4
+
5
+ Jenkins 从主仓 Git 源码加载该目录。更新模板后,后续构建读取 `master` 上的共享库,无需安装 Node 或等待 npm 包发布。独立克隆的业务仓同样通过 Jenkins 配置的 Git 地址读取公共库。
6
+
7
+ ## Jenkins 登记
8
+
9
+ 由管理员在“系统管理 → 系统配置 → Global Trusted Pipeline Libraries”新增一项。
10
+
11
+ - Name 填 `infly-jenkins`。
12
+ - Default version 填 `master`。
13
+ - Load implicitly 保持不勾选,各流水线显式引用。
14
+ - Allow default version to be overridden 保持勾选,支持验证与回退。
15
+ - Retrieval method 选 `Modern SCM`,Source Code Management 选 `Git`。
16
+ - 项目仓库填 `https://gitee.com/gdinfly_1/admin-monorepo.git`。
17
+ - Credentials 选择具有主仓读取权限的凭据,例如已配置的 `gitee-credential`。
18
+ - 向下找到 **Library Path**,填 `packages/infly-libs/jenkins`。该路径相对于 Git 仓库根目录。
19
+
20
+ `@Library` 在流水线编译期加载。启用顺序为主仓共享库代码先由开发人员提交并推送、管理员登记上述配置,然后开发人员提交并推送各部署仓的接入代码。共享库路径或分支无法读取时,流水线会在进入阶段前失败。
21
+
22
+ 通过 `load` 复用其他 Jenkinsfile 时,最外层 SCM 入口同样必须声明 `@Library('infly-jenkins') _`,让共享库在外层编译时加载;被加载脚本可保留相同声明以支持直接作为独立入口。不能只在 `load` 的子脚本中首次声明,否则编译插件复用外层已记录的库列表时可能报告 `Could not find any definition of libraries`,即使全局配置已经存在。
23
+
24
+ 管理员保存后可先用一个测试任务验证通知,确认无误再使用正式任务。配置回退可把共享库 Default version 指向本次已验证的主仓完整提交号。撤销接入需同时回退消费者 Jenkinsfile,并在所有消费者移除引用后处理共享库登记。
25
+
26
+ ## 项目调用
27
+
28
+ ```groovy
29
+ @Library('infly-jenkins') _
30
+
31
+ // 在流水线 post 等已有通知入口内调用。
32
+ inflyNotify(
33
+ project: '项目名称',
34
+ environment: '测试环境',
35
+ components: ['web', 'api'],
36
+ status: '成功',
37
+ sourceVersion: env.RESOLVED_COMMIT,
38
+ imageVersion: env.RESOLVED_IMAGE_TAG,
39
+ commitAuthor: env.BUSINESS_COMMIT_AUTHOR,
40
+ commitMessage: env.BUSINESS_COMMIT_MESSAGE,
41
+ commitSource: '业务代码',
42
+ note: params['发布说明'],
43
+ credentialsId: '项目的企微凭据ID',
44
+ jenkinsUrl: 'https://cicd.sutpay.com',
45
+ extras: ['Host': env.DEPLOY_SERVER, '分支': env.BUSINESS_BRANCH],
46
+ links: ['健康地址': env.HEALTH_URL_1]
47
+ )
48
+ ```
49
+
50
+ `web/admin/api/celery_worker` 分别展示为 `前端(web)`、`前端(admin)`、`后端(api)`、`后端(celery_worker)`。其他组件可直接传明确的显示名称。`extras` 保留项目诊断字段,`links` 用于可点击的附加入口。
51
+
52
+ 构建号默认取任务名与本次构建号。触发人默认取 Jenkins 用户构建原因,自动任务显示 Jenkins,也可通过 `actor` 显式传入。更新时间统一采用北京时间。`enabled: false` 可暂停发送。通知失败返回 `false` 并输出受限提示,缺少工作目录时的清理异常也会隔离。
53
+
54
+ 通知主体设置 30 秒 Jenkins 超时,覆盖正文生成、凭据绑定、文件和发送步骤。HTTP 连接和请求仍分别限制为 5 秒和 15 秒,临时文件清理另设 5 秒超时。超时取消步骤仍受 Jenkins 插件中断和 Agent 响应影响,这些值不等于服务器失联时的强制进程结束保证。
55
+
56
+ 库依赖标准 `timeout` 步骤的中断语义。该步骤在自身超时异常越过自身边界时,将 `FlowInterruptedException.actualInterruption` 标记清除。因此仅吸收该标记已清除且原因为 `ExceededTimeout` 的通知自身超时,作为通知失败处理;人工取消及尚未越过外层边界的流水线超时继续上抛。清理不会覆盖已有的原始中断,通知也不会通过修改 `currentBuild.result` 改写发布结果。
57
+
58
+ `commitAuthor`、`commitMessage` 必须对应通知中 `sourceVersion` 指向的同一冻结提交,提交说明使用该提交的 subject(`git show -s --format=%s <commit>`),不读取当前分支的最新说明。业务仓作者、产物仓作者和部署脚本作者用 `commitSource` 明确区分。公共镜像构建在 `com.infly.source.author`、`com.infly.source.message` 标签中记录与 OCI revision 相同提交的 Git 作者及提交说明,邮惠权益正式后端在校验不可变镜像 revision 后读取这些标签。历史镜像缺少标签时显示未解析,后续重新构建的镜像会携带元数据;旧调用方不传 `commitMessage` 仍可正常发送。
59
+
60
+ 正文使用企业微信 Markdown,日志显示为“点击查看”,结尾保留所有人提醒。URL 清除认证信息、查询和片段,Jenkins 任务路径保留原编码。正文超过 4096 字节时截短正文并保留日志入口和提醒。
61
+
62
+ ## 流水线数据解析
63
+
64
+ `src/com/infly/jenkins` 还提供两个纯数据入口,供独立部署仓通过现有共享库复用,不需要安装 Node 或读取主仓目录:
65
+
66
+ ```groovy
67
+ @Library('infly-jenkins') _
68
+ import com.infly.jenkins.PipelineJson
69
+ import com.infly.jenkins.BuildProvenance
70
+
71
+ def config = PipelineJson.parseObject(readFile('resolved-config.json'))
72
+ def provenance = BuildProvenance.parse(readFile('provenance.json'))
73
+ ```
74
+
75
+ `PipelineJson.parseObject(String)` 只接受 JSON 对象,返回递归转换后的普通 `LinkedHashMap`、`ArrayList` 和 JSON 标量,避免惰性解析对象跨 Pipeline 步骤持久化。非法 JSON 或非对象根值抛出 `IllegalArgumentException`。它不展开项目配置、不执行命令、不读取环境或凭据。
76
+
77
+ `BuildProvenance.parse(String)` 投影固定的来源字段:`schemaVersion`、`releaseId`、`component`、`businessRevision`、`workspaceRevision`、`configurationRevision`、`platform`、`mode`、`target`、`buildArgsSha256`,以及展开的 `workspaceRemoteVerified`、`workspaceRemoteRevision`、`workspaceRemoteRef`。缺失值保留 `null`,版本和标识字段沿用消费者现有字符串化语义;额外字段不进入结果。期望的源码版本、组件、平台、来源模式及远端同步状态仍由项目校验。
78
+
79
+ 镜像元数据应由执行节点按白名单投影后解析,不把 Docker 的完整 `Config` 或环境变量交给日志;这些纯类不代为拉取镜像、晋升、部署或发送通知。新增数据入口必须先由开发人员提交并推送主仓共享库,再更新消费者 Jenkinsfile;消费者回退时同步回退共享库版本或删除对应导入。
80
+
81
+ ## 本地验证
82
+
83
+ `test/notifications.groovy` 使用纯数据与 Jenkins 步骤替身验证,不发送网络请求。需要 Java 和 Groovy 2.4.21 的 `groovy`、`groovy-json` 运行库。使用 UTF-8 运行,类路径包含两份 jar 和本目录的 `src`。
84
+
85
+ Windows PowerShell 示例中,`$env:GROOVY_HOME` 指向已解压的 Groovy 安装目录。
86
+
87
+ ```powershell
88
+ $library = 'D:/Project/admin-monorepo-vite/packages/infly-libs/jenkins'
89
+ $groovyClasspath = "$env:GROOVY_HOME/lib/*;$library/src"
90
+ java '-Dfile.encoding=UTF-8' -cp $groovyClasspath groovy.ui.GroovyMain "$library/test/notifications.groovy" $library
91
+ java '-Dfile.encoding=UTF-8' -cp $groovyClasspath groovy.ui.GroovyMain "$library/test/pipeline-data.groovy" $library
92
+ ```
93
+
94
+ 库目录之后可追加 Jenkinsfile 的完整路径,测试会用注解替身执行 Groovy 语法编译。该检查覆盖语法与通知步骤的本地行为,Jenkins 插件、CPS 持久化和企业微信实际展示需要管理员在测试任务中验证。
@@ -0,0 +1,16 @@
1
+ package com.infly.jenkins
2
+ import com.cloudbees.groovy.cps.NonCPS
3
+
4
+ // 统一来源记录的安全字段投影;各项目继续校验自己期望的版本、平台和组件。
5
+ class BuildProvenance implements Serializable {
6
+ @NonCPS
7
+ static Map parse(String text) {
8
+ Map value = PipelineJson.parseObject(text)
9
+ return [schemaVersion: value.schemaVersion, releaseId: value.releaseId?.toString(),
10
+ component: value.component?.toString(), businessRevision: value.businessRevision?.toString(),
11
+ workspaceRevision: value.workspaceRevision?.toString(), configurationRevision: value.configurationRevision?.toString(),
12
+ platform: value.platform, mode: value.mode, target: value.target, buildArgsSha256: value.buildArgsSha256,
13
+ workspaceRemoteVerified: value.workspaceRemote?.verified, workspaceRemoteRevision: value.workspaceRemote?.revision,
14
+ workspaceRemoteRef: value.workspaceRemote?.expectedRef]
15
+ }
16
+ }
@@ -0,0 +1,28 @@
1
+ package com.infly.jenkins
2
+ import com.cloudbees.groovy.cps.NonCPS
3
+
4
+ // 仅做数据转换;不读取文件、环境、凭据或执行 Pipeline 步骤。
5
+ class PipelineJson implements Serializable {
6
+ @NonCPS
7
+ static Map parseObject(String text) {
8
+ Object value
9
+ try {
10
+ value = new groovy.json.JsonSlurperClassic().parseText(text)
11
+ } catch (Exception ignored) {
12
+ throw new IllegalArgumentException('JSON 对象格式无效')
13
+ }
14
+ if (!(value instanceof Map)) throw new IllegalArgumentException('JSON 根值必须是对象')
15
+ return copyValue(value) as Map
16
+ }
17
+
18
+ @NonCPS
19
+ private static Object copyValue(Object value) {
20
+ if (value instanceof Map) {
21
+ Map result = new LinkedHashMap()
22
+ value.each { key, item -> result[key] = copyValue(item) }
23
+ return result
24
+ }
25
+ if (value instanceof List) return value.collect { item -> copyValue(item) } as ArrayList
26
+ return value
27
+ }
28
+ }
@@ -0,0 +1,86 @@
1
+ package com.infly.jenkins
2
+
3
+ // 纯正文转换,不访问 Jenkins、凭据或项目目录。
4
+ class ReleaseNotification implements Serializable {
5
+ static String text(Object value) {
6
+ if (value instanceof Collection) return value.collect { text(it) }.join(', ')
7
+ if (value == null) return '未解析'
8
+ String result = value.toString().replaceAll(/[\x00-\x1f\x7f]+/, ' ').trim().take(512)
9
+ return result ?: '未解析'
10
+ }
11
+
12
+ static String markdown(Object value) {
13
+ return text(value).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
14
+ .replace('\\', '\\\\').replace('*', '\\*').replace('_', '\\_')
15
+ .replace('[', '\\[').replace(']', '\\]').replace('`', '\\`')
16
+ }
17
+
18
+ static String safeUrl(Object value) {
19
+ if (!value) return null
20
+ try {
21
+ URI uri = new URI(value.toString().trim())
22
+ if (!(uri.scheme in ['http', 'https']) || !uri.host) return null
23
+ String authority = uri.host + (uri.port < 0 ? '' : ":${uri.port}")
24
+ // 保留 Jenkins 任务路径的百分号编码,去掉认证、查询和片段。
25
+ return "${uri.scheme}://${authority}${uri.rawPath ?: '/'}".replace('(', '%28').replace(')', '%29')
26
+ } catch (Exception ignored) {
27
+ return null
28
+ }
29
+ }
30
+
31
+ static String consoleUrl(Object buildUrl, Object jenkinsUrl) {
32
+ String build = safeUrl(buildUrl)
33
+ if (!build) return null
34
+ String root = safeUrl(jenkinsUrl)
35
+ if (root) {
36
+ URI original = new URI(build)
37
+ // Jenkins 公共入口可能带 context path,任务路径从 /job/ 开始。
38
+ String path = original.rawPath
39
+ int jobStart = path.indexOf('/job/')
40
+ if (jobStart >= 0) path = path.substring(jobStart)
41
+ build = root.replaceAll('/+$', '') + path
42
+ }
43
+ return build.replaceAll('/+$', '') + '/console'
44
+ }
45
+
46
+ static String components(Object value) {
47
+ List values = value instanceof Collection ? value as List : text(value).split(/[,,]/) as List
48
+ Map labels = [web: '前端(web)', frontend: '前端(web)', admin: '前端(admin)',
49
+ api: '后端(api)', backend: '后端(api)', celery_worker: '后端(celery_worker)']
50
+ return values.collect { labels[it.toString().trim()] ?: text(it) }.join(', ')
51
+ }
52
+
53
+ static String fitUtf8(String value, int budget) {
54
+ if (value.getBytes('UTF-8').length <= budget) return value
55
+ String prefix = value
56
+ while ((prefix + '…').getBytes('UTF-8').length > budget) {
57
+ prefix = prefix.substring(0, prefix.offsetByCodePoints(prefix.length(), -1))
58
+ }
59
+ return prefix + '…'
60
+ }
61
+
62
+ static String render(Map result) {
63
+ String author = markdown(result.commitAuthor)
64
+ if (result.commitSource) author += "(${markdown(result.commitSource)})"
65
+ List lines = [
66
+ "项目:${markdown(result.project)}", "环境:${markdown(result.environment)}",
67
+ "组件:${markdown(components(result.components))}", "状态:${markdown(result.status)}",
68
+ "源码版本:${markdown(result.sourceVersion)}", "镜像版本:${markdown(result.imageVersion)}",
69
+ "Git提交人:${author}", "Git提交说明:${markdown(result.commitMessage)}",
70
+ "构建号:${markdown(result.buildNumber)}",
71
+ "触发人:${markdown(result.actor)}", "发布说明:${markdown(result.note ?: '无')}"
72
+ ]
73
+ if (result.time) lines.add("更新时间:${markdown(result.time)}")
74
+ (result.extras ?: [:]).each { label, value -> lines.add("${markdown(label)}:${markdown(value)}") }
75
+ String log = safeUrl(result.logUrl)
76
+ String footer = "\n日志:${log ? '[点击查看](' + log + ')' : '未解析'}"
77
+ (result.links ?: [:]).each { label, value ->
78
+ String url = safeUrl(value)
79
+ if (url) footer += "\n${markdown(label)}:[点击查看](${url})"
80
+ }
81
+ footer += '\n<@all>'
82
+ // 企业微信 Markdown 上限 4096 字节,截短正文时保留本次日志入口及提醒。
83
+ if (footer.getBytes('UTF-8').length > 2048) throw new IllegalArgumentException('通知链接过长')
84
+ return fitUtf8(lines.join('\n'), 4096 - footer.getBytes('UTF-8').length) + footer
85
+ }
86
+ }
@@ -0,0 +1,83 @@
1
+ import com.infly.jenkins.ReleaseNotification
2
+ import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException
3
+ import org.jenkinsci.plugins.workflow.steps.TimeoutStepExecution
4
+
5
+ def call(Map options = [:]) {
6
+ if (options.enabled == false) return false
7
+ String id = UUID.randomUUID().toString()
8
+ String payloadFile = ".infly-notify-${id}.json"
9
+ String responseFile = ".infly-notify-${id}-response.json"
10
+ FlowInterruptedException pendingInterruption = null
11
+ try {
12
+ boolean delivered = false
13
+ timeout(time: 30, unit: 'SECONDS') {
14
+ if (!options.credentialsId) throw new IllegalArgumentException('缺少通知凭据 ID')
15
+ Map result = new LinkedHashMap(options)
16
+ result.actor = options.actor ?: triggerActor()
17
+ result.buildNumber = options.buildNumber ?: "${env.JOB_NAME ?: 'Jenkins'} #${env.BUILD_NUMBER ?: '?'}"
18
+ result.time = options.time ?: new Date().format('yyyy-MM-dd HH:mm:ss', TimeZone.getTimeZone('Asia/Shanghai'))
19
+ result.logUrl = options.logUrl ?: ReleaseNotification.consoleUrl(env.BUILD_URL, options.jenkinsUrl)
20
+ String content = ReleaseNotification.render(result)
21
+ writeFile file: payloadFile, encoding: 'UTF-8', text: groovy.json.JsonOutput.toJson([
22
+ msgtype: 'markdown', markdown: [content: content]
23
+ ])
24
+ withCredentials([string(credentialsId: options.credentialsId.toString(), variable: 'INFLY_NOTIFY_WEBHOOK_URL')]) {
25
+ int code = sh(returnStatus: true, script: """
26
+ set +x
27
+ curl --fail --silent --connect-timeout 5 --max-time 15 \\
28
+ -H 'Content-Type: application/json' --data-binary @${payloadFile} \\
29
+ --output ${responseFile} "\$INFLY_NOTIFY_WEBHOOK_URL"
30
+ """)
31
+ if (code == 0) {
32
+ // 先完成 Pipeline 步骤,再创建解析器,避免 CPS 保存不可序列化的解析器实例。
33
+ String responseText = readFile(file: responseFile, encoding: 'UTF-8')
34
+ def response = new groovy.json.JsonSlurperClassic().parseText(responseText)
35
+ delivered = response instanceof Map && response.errcode == 0
36
+ }
37
+ }
38
+ }
39
+ if (!delivered) echo '企业微信通知失败,发布结果保持不变'
40
+ return delivered
41
+ } catch (FlowInterruptedException interruption) {
42
+ // 标准 timeout 仅在越过自身边界后清除 actual 标记;外层超时和人工取消继续上抛。
43
+ if (!isNotificationTimeout(interruption)) {
44
+ pendingInterruption = interruption
45
+ throw interruption
46
+ }
47
+ echo '企业微信通知超过 30 秒,发布结果保持不变'
48
+ return false
49
+ } catch (Exception ignored) {
50
+ // 异常及响应可能携带 Webhook,日志仅报告结果。
51
+ echo '企业微信通知未发送成功,发布结果保持不变'
52
+ return false
53
+ } finally {
54
+ try {
55
+ timeout(time: 5, unit: 'SECONDS') {
56
+ sh(returnStatus: true, script: "rm -f -- ${payloadFile} ${responseFile}")
57
+ }
58
+ } catch (FlowInterruptedException interruption) {
59
+ // 清理不能替换原始中断;正常清理期间收到的人工取消或外层超时仍须生效。
60
+ if (!isNotificationTimeout(interruption) && pendingInterruption == null) throw interruption
61
+ echo '通知临时文件清理已停止,请检查本次工作目录'
62
+ } catch (Exception ignored) {
63
+ // 检出失败时可能没有 workspace,不能让清理覆盖原始结果。
64
+ echo '通知临时文件清理未完成,请检查本次工作目录'
65
+ }
66
+ }
67
+ }
68
+
69
+ boolean isNotificationTimeout(FlowInterruptedException interruption) {
70
+ return !interruption.isActualInterruption() && !interruption.causes.isEmpty() &&
71
+ interruption.causes.every { it instanceof TimeoutStepExecution.ExceededTimeout }
72
+ }
73
+
74
+ def triggerActor() {
75
+ try {
76
+ def causes = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')
77
+ return causes ? (causes[0].userId ?: causes[0].userName ?: 'Jenkins') : 'Jenkins'
78
+ } catch (FlowInterruptedException interruption) {
79
+ throw interruption
80
+ } catch (Exception ignored) {
81
+ return 'Jenkins'
82
+ }
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infly/libs",
3
- "version": "2.5.0",
3
+ "version": "2.7.0",
4
4
  "description": "不受前端框架限制的独立工具库",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -14,6 +14,9 @@
14
14
  "adapters/vue2/",
15
15
  "adapters/webpack/",
16
16
  "build/",
17
+ "jenkins/vars/",
18
+ "jenkins/src/",
19
+ "jenkins/README.md",
17
20
  "module/",
18
21
  "script/git-automation/",
19
22
  "script/index.js",
@@ -1,15 +1,8 @@
1
+ const { logTerminal } = require("../../cli/terminal-style");
1
2
  const path = require('path');
2
3
  const { checkAndUpdatePackages } = require('./index');
3
4
 
4
5
  // 设置基本的日志颜色
5
- global.logColor = {
6
- success: '\x1b[32m', // 绿色
7
- error: '\x1b[31m', // 红色
8
- warning: '\x1b[33m', // 黄色
9
- info: '\x1b[36m', // 青色
10
- reset: '\x1b[0m' // 重置
11
- };
12
-
13
6
  /**
14
7
  * 主函数:检查 packages 并处理
15
8
  */
@@ -17,7 +10,7 @@ async function main() {
17
10
  // packages 目录路径(相对于当前脚本的位置)
18
11
  const packagesDir = path.resolve(__dirname, '../../../../packages');
19
12
 
20
- console.log(global.logColor.info, `\n🔍 开始检查 packages 目录: ${packagesDir}\n`);
13
+ logTerminal("info", `\n开始检查 packages 目录: ${packagesDir}\n`);
21
14
 
22
15
  try {
23
16
  // 执行完整的检查和更新流程
@@ -25,13 +18,13 @@ async function main() {
25
18
  // 如果没有问题会自动切换到 master 分支并拉取最新代码
26
19
  await checkAndUpdatePackages(packagesDir, 'master');
27
20
 
28
- console.log(global.logColor.success, `\n✨ packages 检查和更新完成,可以继续执行后续操作!\n`);
21
+ logTerminal("success", `\npackages 检查和更新完成,可以继续执行后续操作!\n`);
29
22
 
30
23
  // 在这里可以继续执行你的其他逻辑
31
24
  // 比如构建、发布等操作
32
25
 
33
26
  } catch (error) {
34
- console.error(global.logColor.error, `\n💥 执行失败: ${error.message}\n`);
27
+ logTerminal("error", `\n执行失败: ${error.message}\n`);
35
28
  process.exit(1);
36
29
  }
37
30
  }
@@ -39,7 +32,7 @@ async function main() {
39
32
  // 如果直接运行此文件,则执行主函数
40
33
  if (require.main === module) {
41
34
  main().catch(error => {
42
- console.error(global.logColor.error, `\n💥 执行失败: ${error.message}\n`);
35
+ logTerminal("error", `\n执行失败: ${error.message}\n`);
43
36
  process.exit(1);
44
37
  });
45
38
  }