@infly/libs 2.1.0 → 2.1.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.
@@ -1,136 +1,136 @@
1
- function shouldSkipWebhook() {
2
- const args = process.argv || [];
3
- const hasNoWebhookArg = args.some((arg = "") =>
4
- ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg)
5
- );
6
-
7
- const env = process.env || {};
8
- const envValues = [
9
- env.npm_config_nowebhook,
10
- env.npm_config_noWebhook,
11
- env.NO_WEBHOOK,
12
- env.DISABLE_WEBHOOK
13
- ];
14
- const hasNoWebhookEnv = envValues.some((value) => {
15
- const normalized = String(value || "").toLowerCase();
16
- return ["1", "true", "yes", "on"].includes(normalized);
17
- });
18
-
19
- return hasNoWebhookArg || hasNoWebhookEnv;
20
- }
21
-
22
- function getWebhookMessage() {
23
- const args = process.argv || [];
24
- const env = process.env || {};
25
- const messageEnv =
26
- env.npm_config_m ||
27
- env.npm_config_message ||
28
- env.WEBHOOK_MESSAGE ||
29
- env.BUILD_MESSAGE ||
30
- "";
31
-
32
- if (messageEnv) {
33
- return String(messageEnv).trim();
34
- }
35
-
36
- for (let index = 0; index < args.length; index += 1) {
37
- const arg = args[index] || "";
38
-
39
- if (arg === "-m" || arg === "--message") {
40
- return String(args[index + 1] || "").trim();
41
- }
42
-
43
- if (arg.startsWith("-m=")) {
44
- return arg.slice(3).trim();
45
- }
46
-
47
- if (arg.startsWith("--message=")) {
48
- return arg.slice(10).trim();
49
- }
50
- }
51
-
52
- return "";
53
- }
54
-
55
- function postVersionFileAndMsg(publishText, extraParams = {}) {
56
- const {
57
- projectName,
58
- newFileName,
59
- gitInfo,
60
- webhookUrl = "", // 启用企业微信推送
61
- webhookAtUser = [],
62
- webhookExtraText = "",
63
- gitAutoPushRepos,
64
- gitAutoPushReposBranchMap,
65
- repos,
66
- deployUrl = ""
67
- } = extraParams || {};
68
- const { branch, commitMsg, author } = gitInfo || {};
69
- const webhookMessage = getWebhookMessage();
70
- const GITPATH = `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`;
71
- const UPLOADURL = `https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=&type=file`;
72
- /* const data = {
73
- msgtype: "markdown",
74
- markdown: {
75
- content: `${publishText}\n构建文件:[点击下载](${GITPATH})`,
76
- },
77
- };
78
- if (Array.isArray(webhookAtUser) && webhookAtUser.length > 0) {
79
- webhookAtUser.forEach((item, index) => {
80
- data.markdown.content = `${data.markdown.content}\n<@${item}>`;
81
- });
82
- } */
83
- let content = publishText;
84
- if (gitAutoPushReposBranchMap) {
85
- content = [
86
- publishText,
87
- `构建文件:已推送对应仓库【${repos}】- 分支【${gitAutoPushReposBranchMap[branch]}】`,
88
- `构建人:${author}`,
89
- deployUrl ? `部署系统:${deployUrl}` : ""
90
- ].filter(Boolean).join("\n");
91
- } else {
92
- content = `${publishText}\n构建文件下载地址:${GITPATH}\n${webhookExtraText}\n`;
93
- }
94
-
95
- if (webhookMessage) {
96
- content = `${content}\n${webhookMessage}`;
97
- }
98
-
99
- // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
100
- content = (content || "").replace(/%s/g, "");
101
-
102
- const data = {
103
- msgtype: "text",
104
- text: {
105
- content,
106
- mentioned_mobile_list: Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[branch] // 支持按分支配置不同的提醒人
107
- }
108
- };
109
-
110
- if (shouldSkipWebhook()) {
111
- console.log(global.logColor?.info || "%s", "🔕 已跳过企业微信机器人推送(nowebhook)");
112
- return;
113
- }
114
-
115
- try {
116
- const axios = require("axios");
117
-
118
- if (axios) {
119
- axios
120
- .post(webhookUrl, data, {
121
- headers: {
122
- "Content-Type": "application/json"
123
- }
124
- })
125
- .catch((e) => {
126
- console.error("请求出错:", e);
127
- });
128
- }
129
- } catch (error) {
130
- console.error("axios is not available, please install it.");
131
- }
132
- }
133
-
134
- module.exports = {
135
- postVersionFileAndMsg
136
- };
1
+ function shouldSkipWebhook() {
2
+ const args = process.argv || [];
3
+ const hasNoWebhookArg = args.some((arg = "") =>
4
+ ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg)
5
+ );
6
+
7
+ const env = process.env || {};
8
+ const envValues = [
9
+ env.npm_config_nowebhook,
10
+ env.npm_config_noWebhook,
11
+ env.NO_WEBHOOK,
12
+ env.DISABLE_WEBHOOK
13
+ ];
14
+ const hasNoWebhookEnv = envValues.some((value) => {
15
+ const normalized = String(value || "").toLowerCase();
16
+ return ["1", "true", "yes", "on"].includes(normalized);
17
+ });
18
+
19
+ return hasNoWebhookArg || hasNoWebhookEnv;
20
+ }
21
+
22
+ function getWebhookMessage() {
23
+ const args = process.argv || [];
24
+ const env = process.env || {};
25
+ const messageEnv =
26
+ env.npm_config_m ||
27
+ env.npm_config_message ||
28
+ env.WEBHOOK_MESSAGE ||
29
+ env.BUILD_MESSAGE ||
30
+ "";
31
+
32
+ if (messageEnv) {
33
+ return String(messageEnv).trim();
34
+ }
35
+
36
+ for (let index = 0; index < args.length; index += 1) {
37
+ const arg = args[index] || "";
38
+
39
+ if (arg === "-m" || arg === "--message") {
40
+ return String(args[index + 1] || "").trim();
41
+ }
42
+
43
+ if (arg.startsWith("-m=")) {
44
+ return arg.slice(3).trim();
45
+ }
46
+
47
+ if (arg.startsWith("--message=")) {
48
+ return arg.slice(10).trim();
49
+ }
50
+ }
51
+
52
+ return "";
53
+ }
54
+
55
+ function postVersionFileAndMsg(publishText, extraParams = {}) {
56
+ const {
57
+ projectName,
58
+ newFileName,
59
+ gitInfo,
60
+ webhookUrl = "", // 启用企业微信推送
61
+ webhookAtUser = [],
62
+ webhookExtraText = "",
63
+ gitAutoPushRepos,
64
+ gitAutoPushReposBranchMap,
65
+ repos,
66
+ deployUrl = ""
67
+ } = extraParams || {};
68
+ const { branch, commitMsg, author } = gitInfo || {};
69
+ const webhookMessage = getWebhookMessage();
70
+ const GITPATH = `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`;
71
+ const UPLOADURL = `https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=&type=file`;
72
+ /* const data = {
73
+ msgtype: "markdown",
74
+ markdown: {
75
+ content: `${publishText}\n构建文件:[点击下载](${GITPATH})`,
76
+ },
77
+ };
78
+ if (Array.isArray(webhookAtUser) && webhookAtUser.length > 0) {
79
+ webhookAtUser.forEach((item, index) => {
80
+ data.markdown.content = `${data.markdown.content}\n<@${item}>`;
81
+ });
82
+ } */
83
+ let content = publishText;
84
+ if (gitAutoPushReposBranchMap) {
85
+ content = [
86
+ publishText,
87
+ `构建文件:已推送对应仓库【${repos}】- 分支【${gitAutoPushReposBranchMap[branch]}】`,
88
+ `构建人:${author}`,
89
+ deployUrl ? `部署系统:${deployUrl}` : ""
90
+ ].filter(Boolean).join("\n");
91
+ } else {
92
+ content = `${publishText}\n构建文件下载地址:${GITPATH}\n${webhookExtraText}\n`;
93
+ }
94
+
95
+ if (webhookMessage) {
96
+ content = `${content}\n${webhookMessage}`;
97
+ }
98
+
99
+ // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
100
+ content = (content || "").replace(/%s/g, "");
101
+
102
+ const data = {
103
+ msgtype: "text",
104
+ text: {
105
+ content,
106
+ mentioned_mobile_list: Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[branch] // 支持按分支配置不同的提醒人
107
+ }
108
+ };
109
+
110
+ if (shouldSkipWebhook()) {
111
+ console.log(global.logColor?.info || "%s", "🔕 已跳过企业微信机器人推送(nowebhook)");
112
+ return;
113
+ }
114
+
115
+ try {
116
+ const axios = require("axios");
117
+
118
+ if (axios) {
119
+ axios
120
+ .post(webhookUrl, data, {
121
+ headers: {
122
+ "Content-Type": "application/json"
123
+ }
124
+ })
125
+ .catch((e) => {
126
+ console.error("请求出错:", e);
127
+ });
128
+ }
129
+ } catch (error) {
130
+ console.error("axios is not available, please install it.");
131
+ }
132
+ }
133
+
134
+ module.exports = {
135
+ postVersionFileAndMsg
136
+ };
@@ -1,74 +1,74 @@
1
- const fs = require("node:fs");
2
- const path = require("node:path");
3
-
4
- const {
5
- EXIT_SELECTION,
6
- selectOption: defaultSelectOption,
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+
4
+ const {
5
+ EXIT_SELECTION,
6
+ selectOption: defaultSelectOption,
7
7
  } = require("../../cli/select-option");
8
- const { composeRelease: defaultComposeRelease } = require("./compose-release");
9
-
10
- function loadTargetConfig(configPath) {
11
- const resolvedPath = path.resolve(configPath);
12
- delete require.cache[require.resolve(resolvedPath)];
13
- return {
14
- config: require(resolvedPath),
15
- configDir: path.dirname(resolvedPath),
16
- };
17
- }
18
-
19
- function loadPackageTargetConfig(cwd = process.cwd()) {
20
- const packagePath = path.resolve(cwd, "package.json");
21
- if (!fs.existsSync(packagePath)) {
22
- throw new Error(`Package config not found: ${packagePath}`);
23
- }
24
- delete require.cache[require.resolve(packagePath)];
25
- const packageJson = require(packagePath);
26
- return {
27
- config: packageJson.infly?.docker,
28
- configDir: path.dirname(packagePath),
29
- };
30
- }
31
-
32
- async function runComposeCommand(options = {}, dependencies = {}) {
33
- const composeRelease = dependencies.composeRelease || defaultComposeRelease;
34
- const usesDirectConfig = !options.config
35
- && !options.configObject
36
- && (options.projectDir || options.file);
37
- if (usesDirectConfig) return composeRelease(options);
38
-
39
- const loaded = options.config
40
- ? loadTargetConfig(options.config)
41
- : options.configObject
42
- ? { config: options.configObject, configDir: options.configDir || process.cwd() }
43
- : loadPackageTargetConfig(options.cwd || process.cwd());
44
- const targets = loaded.config?.targets;
45
- if (!targets || Object.keys(targets).length === 0) {
46
- throw new Error("Docker target config must define at least one target.");
47
- }
48
-
49
- const selectOption = dependencies.selectOption || defaultSelectOption;
50
- const log = dependencies.log || console.log;
51
- const targetName = options.target || await selectOption(
52
- "请选择 Docker 发布目标",
53
- Object.entries(targets).map(([value, target]) => ({
54
- value,
55
- label: target.label || value,
56
- })),
57
- );
58
- if (targetName === EXIT_SELECTION) {
59
- log("已退出,未执行任何操作。");
60
- return { cancelled: true };
61
- }
62
- const target = targets[targetName];
63
- if (!target) throw new Error(`Unknown Docker target: ${targetName}`);
64
-
65
- return composeRelease({
66
- projectDir: loaded.configDir,
67
- file: target.file,
68
- bump: options.bump || "patch",
69
- push: Boolean(options.push),
70
- dryRun: Boolean(options.dryRun),
71
- });
72
- }
73
-
74
- module.exports = { loadPackageTargetConfig, loadTargetConfig, runComposeCommand };
8
+ const { composeRelease: defaultComposeRelease } = require("./compose-release");
9
+
10
+ function loadTargetConfig(configPath) {
11
+ const resolvedPath = path.resolve(configPath);
12
+ delete require.cache[require.resolve(resolvedPath)];
13
+ return {
14
+ config: require(resolvedPath),
15
+ configDir: path.dirname(resolvedPath),
16
+ };
17
+ }
18
+
19
+ function loadPackageTargetConfig(cwd = process.cwd()) {
20
+ const packagePath = path.resolve(cwd, "package.json");
21
+ if (!fs.existsSync(packagePath)) {
22
+ throw new Error(`Package config not found: ${packagePath}`);
23
+ }
24
+ delete require.cache[require.resolve(packagePath)];
25
+ const packageJson = require(packagePath);
26
+ return {
27
+ config: packageJson.infly?.docker,
28
+ configDir: path.dirname(packagePath),
29
+ };
30
+ }
31
+
32
+ async function runComposeCommand(options = {}, dependencies = {}) {
33
+ const composeRelease = dependencies.composeRelease || defaultComposeRelease;
34
+ const usesDirectConfig = !options.config
35
+ && !options.configObject
36
+ && (options.projectDir || options.file);
37
+ if (usesDirectConfig) return composeRelease(options);
38
+
39
+ const loaded = options.config
40
+ ? loadTargetConfig(options.config)
41
+ : options.configObject
42
+ ? { config: options.configObject, configDir: options.configDir || process.cwd() }
43
+ : loadPackageTargetConfig(options.cwd || process.cwd());
44
+ const targets = loaded.config?.targets;
45
+ if (!targets || Object.keys(targets).length === 0) {
46
+ throw new Error("Docker target config must define at least one target.");
47
+ }
48
+
49
+ const selectOption = dependencies.selectOption || defaultSelectOption;
50
+ const log = dependencies.log || console.log;
51
+ const targetName = options.target || await selectOption(
52
+ "请选择 Docker 发布目标",
53
+ Object.entries(targets).map(([value, target]) => ({
54
+ value,
55
+ label: target.label || value,
56
+ })),
57
+ );
58
+ if (targetName === EXIT_SELECTION) {
59
+ log("已退出,未执行任何操作。");
60
+ return { cancelled: true };
61
+ }
62
+ const target = targets[targetName];
63
+ if (!target) throw new Error(`Unknown Docker target: ${targetName}`);
64
+
65
+ return composeRelease({
66
+ projectDir: loaded.configDir,
67
+ file: target.file,
68
+ bump: options.bump || "patch",
69
+ push: Boolean(options.push),
70
+ dryRun: Boolean(options.dryRun),
71
+ });
72
+ }
73
+
74
+ module.exports = { loadPackageTargetConfig, loadTargetConfig, runComposeCommand };
@@ -1,98 +1,98 @@
1
- const { execFileSync } = require("node:child_process");
2
- const fs = require("node:fs");
3
- const path = require("node:path");
4
-
1
+ const { execFileSync } = require("node:child_process");
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+
5
5
  function bumpComposeImageVersion(content, bump = "patch") {
6
6
  if (!["none", "patch"].includes(bump)) {
7
7
  throw new Error(`Unsupported version bump: ${bump}. Supported values: none, patch.`);
8
- }
9
-
10
- const imageRegex = /^(\s*image:\s*)([^\s#]+):(\d+)\.(\d+)\.(\d+)(\s*(?:#.*)?)$/gm;
11
- const matches = [...content.matchAll(imageRegex)];
12
-
13
- if (matches.length !== 1) {
14
- throw new Error(`Compose file must contain exactly one versioned image; found ${matches.length}.`);
15
- }
16
-
8
+ }
9
+
10
+ const imageRegex = /^(\s*image:\s*)([^\s#]+):(\d+)\.(\d+)\.(\d+)(\s*(?:#.*)?)$/gm;
11
+ const matches = [...content.matchAll(imageRegex)];
12
+
13
+ if (matches.length !== 1) {
14
+ throw new Error(`Compose file must contain exactly one versioned image; found ${matches.length}.`);
15
+ }
16
+
17
17
  const [, prefix, image, major, minor, patchVersion, suffix] = matches[0];
18
18
  const from = `${image}:${major}.${minor}.${patchVersion}`;
19
19
  const to = bump === "none"
20
20
  ? from
21
21
  : `${image}:${major}.${minor}.${Number(patchVersion) + 1}`;
22
22
  const replacement = `${prefix}${to}${suffix}`;
23
-
24
- return {
25
- content: content.replace(imageRegex, replacement),
26
- from,
27
- to,
28
- };
29
- }
30
-
31
- function resolveComposePath(projectDir, file) {
32
- if (!projectDir) throw new Error("--project-dir is required.");
33
- if (!file) throw new Error("--file is required.");
34
-
35
- const resolvedProjectDir = path.resolve(projectDir);
36
- const composePath = path.resolve(resolvedProjectDir, file);
37
- const relative = path.relative(resolvedProjectDir, composePath);
38
-
39
- if (relative.startsWith("..") || path.isAbsolute(relative)) {
40
- throw new Error("Compose file must be inside project-dir.");
41
- }
42
- if (!fs.existsSync(composePath)) {
43
- throw new Error(`Compose file not found: ${composePath}`);
44
- }
45
-
46
- return { projectDir: resolvedProjectDir, composePath };
47
- }
48
-
49
- function defaultRunDocker(args, options) {
50
- execFileSync("docker", args, { cwd: options.cwd, stdio: "inherit" });
51
- }
52
-
53
- function composeRelease(options = {}, dependencies = {}) {
54
- const {
55
- projectDir,
56
- file,
57
- bump = "patch",
58
- push = false,
59
- dryRun = false,
60
- } = options;
61
- const runDocker = dependencies.runDocker || defaultRunDocker;
62
- const resolved = resolveComposePath(projectDir, file);
63
- const original = fs.readFileSync(resolved.composePath, "utf8");
64
- const updated = bumpComposeImageVersion(original, bump);
65
- const baseArgs = ["compose", "-f", resolved.composePath];
66
-
23
+
24
+ return {
25
+ content: content.replace(imageRegex, replacement),
26
+ from,
27
+ to,
28
+ };
29
+ }
30
+
31
+ function resolveComposePath(projectDir, file) {
32
+ if (!projectDir) throw new Error("--project-dir is required.");
33
+ if (!file) throw new Error("--file is required.");
34
+
35
+ const resolvedProjectDir = path.resolve(projectDir);
36
+ const composePath = path.resolve(resolvedProjectDir, file);
37
+ const relative = path.relative(resolvedProjectDir, composePath);
38
+
39
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
40
+ throw new Error("Compose file must be inside project-dir.");
41
+ }
42
+ if (!fs.existsSync(composePath)) {
43
+ throw new Error(`Compose file not found: ${composePath}`);
44
+ }
45
+
46
+ return { projectDir: resolvedProjectDir, composePath };
47
+ }
48
+
49
+ function defaultRunDocker(args, options) {
50
+ execFileSync("docker", args, { cwd: options.cwd, stdio: "inherit" });
51
+ }
52
+
53
+ function composeRelease(options = {}, dependencies = {}) {
54
+ const {
55
+ projectDir,
56
+ file,
57
+ bump = "patch",
58
+ push = false,
59
+ dryRun = false,
60
+ } = options;
61
+ const runDocker = dependencies.runDocker || defaultRunDocker;
62
+ const resolved = resolveComposePath(projectDir, file);
63
+ const original = fs.readFileSync(resolved.composePath, "utf8");
64
+ const updated = bumpComposeImageVersion(original, bump);
65
+ const baseArgs = ["compose", "-f", resolved.composePath];
66
+
67
67
  if (bump === "none") {
68
68
  console.log(`Version fixed: ${updated.from}`);
69
69
  } else {
70
70
  console.log(`Version update: ${updated.from} -> ${updated.to}`);
71
71
  }
72
-
73
- if (dryRun) {
74
- console.log(`[dry-run] docker ${[...baseArgs, "config"].join(" ")}`);
75
- console.log(`[dry-run] docker ${[...baseArgs, "build"].join(" ")}`);
76
- if (push) console.log(`[dry-run] docker ${[...baseArgs, "push"].join(" ")}`);
77
- return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
78
- }
79
-
72
+
73
+ if (dryRun) {
74
+ console.log(`[dry-run] docker ${[...baseArgs, "config"].join(" ")}`);
75
+ console.log(`[dry-run] docker ${[...baseArgs, "build"].join(" ")}`);
76
+ if (push) console.log(`[dry-run] docker ${[...baseArgs, "push"].join(" ")}`);
77
+ return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
78
+ }
79
+
80
80
  const versionChanged = updated.content !== original;
81
81
  if (versionChanged) fs.writeFileSync(resolved.composePath, updated.content, "utf8");
82
82
  try {
83
- runDocker([...baseArgs, "config"], { cwd: resolved.projectDir });
84
- runDocker([...baseArgs, "build"], { cwd: resolved.projectDir });
85
- if (push) runDocker([...baseArgs, "push"], { cwd: resolved.projectDir });
83
+ runDocker([...baseArgs, "config"], { cwd: resolved.projectDir });
84
+ runDocker([...baseArgs, "build"], { cwd: resolved.projectDir });
85
+ if (push) runDocker([...baseArgs, "push"], { cwd: resolved.projectDir });
86
86
  } catch (error) {
87
87
  if (versionChanged) fs.writeFileSync(resolved.composePath, original, "utf8");
88
- throw error;
89
- }
90
-
91
- return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
92
- }
93
-
94
- module.exports = {
95
- bumpComposeImageVersion,
96
- composeRelease,
97
- resolveComposePath,
98
- };
88
+ throw error;
89
+ }
90
+
91
+ return { ...updated, projectDir: resolved.projectDir, composePath: resolved.composePath };
92
+ }
93
+
94
+ module.exports = {
95
+ bumpComposeImageVersion,
96
+ composeRelease,
97
+ resolveComposePath,
98
+ };
@@ -48,8 +48,8 @@ if ! grep -Eqi 'manifest unknown|no such manifest|manifest[^[:cntrl:]]*not found
48
48
  exit 1
49
49
  fi
50
50
 
51
- # 本地构建只写 qc 标签;Jenkins 人工确认后才允许创建不可变正式标签。
52
- # 使用 pull/tag/push 避免部署节点依赖 Buildx,同时不在 Jenkins 执行 Dockerfile 构建。
51
+ # 本地构建只推送当前构建节点平台的 qc 镜像;Jenkins 门禁通过后才允许创建不可变正式标签。
52
+ # 单平台镜像已完整拉取到本地,可直接重新标记并推送,无需在 Jenkins 节点安装 Buildx。
53
53
  docker tag "$source_image" "$final_image"
54
54
  docker push "$final_image"
55
55
  docker pull "$final_image"