@infly/libs 2.1.9 → 2.2.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,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,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
+ };
@@ -25,7 +25,7 @@ const path = require("path");
25
25
  const DEFAULT_REGISTRY = "ccr.ccs.tencentyun.com";
26
26
  const DEFAULT_NAMESPACE = "points";
27
27
 
28
- function formatCicdLink(value) {
28
+ function formatCicdLink(value, deployParams) {
29
29
  if (value === undefined) {
30
30
  return "";
31
31
  }
@@ -52,10 +52,34 @@ function formatCicdLink(value) {
52
52
  throw new Error("--cicd-url 不能包含用户名或密码凭据");
53
53
  }
54
54
 
55
+ // 单组件推送成功后预填“平台/镜像版本”参数,新平台首次部署无需从历史选项里挑选;仅对 /build 构建入口追加。
56
+ if (deployParams !== undefined) {
57
+ const { platform, platformLabel, tag, date } = deployParams;
58
+ if (typeof platform !== "string" || !/^[a-z0-9]+$/.test(platform)
59
+ || typeof tag !== "string" || !/^[0-9a-f]{12}$/.test(tag)
60
+ || typeof date !== "string" || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(date)) {
61
+ throw new Error("发布系统深链参数必须是合法平台、12 位提交版本和 yyyy-MM-dd HH:mm 时间");
62
+ }
63
+ if (platformLabel !== undefined && (typeof platformLabel !== "string" || !platformLabel.trim()
64
+ || /[\u0000-\u001f\u007f]/.test(platformLabel))) {
65
+ throw new Error("发布系统深链平台名称必须是非空且不含控制字符的字符串");
66
+ }
67
+ if (parsedUrl.pathname.endsWith("/build")) {
68
+ // Jenkins 原生 choice 的显示文本就是提交值;传入标签时须与“中文名称 / 编码”选项完全一致。
69
+ const platformChoice = platformLabel === undefined ? platform : `${platformLabel.trim()} / ${platform}`;
70
+ const suffix = `&${encodeURIComponent("平台")}=${encodeURIComponent(platformChoice)}`
71
+ + `&${encodeURIComponent("镜像版本")}=${encodeURIComponent(`${platform} / ${tag} / ${date}`)}`;
72
+ parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}${suffix}` : `?${suffix.slice(1)}`;
73
+ }
74
+ }
75
+
55
76
  // 显示中文地址,同时把标准化 URL 放进 OSC 8 点击目标,避免依赖终端的文本自动识别。
77
+ // decodeURI 不展开保留字符(如 /、&、= 的转义),深链分隔符手动还原,保证文本可读可复制。
78
+ const displayHref = decodeURI(parsedUrl.href)
79
+ .replace(/%2F/gi, "/").replace(/%26/gi, "&").replace(/%3D/gi, "=").replace(/%3A/gi, ":");
56
80
  const hyperlinkStart = `\x1b]8;;${parsedUrl.href}\x1b\\`;
57
81
  const hyperlinkEnd = "\x1b]8;;\x1b\\";
58
- return `发布系统:\n${hyperlinkStart}\x1b[34m${decodeURI(parsedUrl.href)}\x1b[0m${hyperlinkEnd}`;
82
+ return `发布系统:\n${hyperlinkStart}\x1b[34m${displayHref}\x1b[0m${hyperlinkEnd}`;
59
83
  }
60
84
 
61
85
  function detectMode({ standalone = false } = {}) {
@@ -7,6 +7,16 @@ const { composeRelease } = require("./compose-release");
7
7
  const { formatCicdLink } = require("./docker-build-push");
8
8
  const { resolveDockerConfig } = require("./target-config");
9
9
 
10
+ // Jenkins 构建页“镜像版本”与 Webhook 通知均按北京时间展示。
11
+ function beijingDateTime(now = new Date()) {
12
+ const parts = new Intl.DateTimeFormat("en-CA", {
13
+ timeZone: "Asia/Shanghai", year: "numeric", month: "2-digit", day: "2-digit",
14
+ hour: "2-digit", minute: "2-digit", hourCycle: "h23",
15
+ }).formatToParts(now);
16
+ const values = Object.fromEntries(parts.filter((part) => part.type !== "literal").map((part) => [part.type, part.value]));
17
+ return `${values.year}-${values.month}-${values.day} ${values.hour}:${values.minute}`;
18
+ }
19
+
10
20
  async function checkDocker(run, projectDir, buildx = true, dependencies = {}, autoStart = true) {
11
21
  const quiet = { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] };
12
22
  try {
@@ -253,7 +263,7 @@ async function runTargetRelease(options = {}, dependencies = {}) {
253
263
  // 输出同时面向本地核对与 Jenkins 下拉部署,避免再手工复制提交参数。
254
264
  if (results.length) {
255
265
  const pushNote = options.push
256
- ? "已推送不可变提交标签和 latest 最新构建标签,可直接在 Jenkins 选择部署"
266
+ ? "已推送不可变提交标签和 latest 最新推送标签,可直接在 Jenkins 选择部署"
257
267
  : "仅本地生成,未推送镜像";
258
268
  log("");
259
269
  log("\x1b[0;34m==========================================");
@@ -262,11 +272,18 @@ async function runTargetRelease(options = {}, dependencies = {}) {
262
272
  log(`可用标签(${pushNote}):`);
263
273
  for (const r of results) {
264
274
  log(` ${r.component}=${r.image} (不可变提交版本)`);
265
- log(` ${r.component}_latest=${r.latestImage} (最新构建镜像)`);
275
+ log(` ${r.component}_latest=${r.latestImage} (最新推送镜像,即所选平台 registry 的 latest)`);
266
276
  }
267
277
  if (cicdLink) {
268
278
  log("");
269
- log(cicdLink);
279
+ // 单组件推送成功后把平台与 12 位提交预填进 Jenkins 参数,新平台首次部署无需从历史下拉选项挑选;
280
+ // 多组件对应对应多个任务时保持原链接,非 /build 地址由 formatCicdLink 原样返回。
281
+ const deployLink = options.push && results.length === 1 && /^[a-z0-9]+$/.test(target)
282
+ ? formatCicdLink(options.cicdUrl, { platform: target, platformLabel: profile.label,
283
+ tag: results[0].commit.slice(0, 12),
284
+ date: beijingDateTime((dependencies.now || (() => new Date()))()) })
285
+ : cicdLink;
286
+ log(deployLink);
270
287
  }
271
288
  }
272
289
  return { target, results };
@@ -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
+ };