dsh-git-push 2.10.4 → 2.10.5
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 +4 -0
- package/lib/app/audit-api.js +2 -0
- package/lib/app/repo-ownership.js +65 -0
- package/lib/app/tool-call.js +4 -0
- package/lib/audit/audit-file.js +15 -1
- package/lib/audit/orchestrate.js +1 -0
- package/lib/audit/ownership.js +46 -0
- package/lib/cli/commands-audit.mjs +3 -0
- package/lib/self/index.js +1 -1
- package/package.json +1 -1
- package/scripts/bump-version.mjs +163 -0
package/README.md
CHANGED
|
@@ -265,6 +265,7 @@ dsh-git-push/
|
|
|
265
265
|
│ │ ├── http-handlers.js — HTTP 路由分发(薄 router:前置校验 + switch 各端点调 handlers/ 模块)
|
|
266
266
|
│ │ ├── index.js — 插件入口再导出(宿主 main 指向)
|
|
267
267
|
│ │ ├── inject-text.js — 注入文本(工具用法提示 FUNCTION_USAGE_HINT)
|
|
268
|
+
│ │ ├── repo-ownership.js — (待注释)
|
|
268
269
|
│ │ ├── scan-root.js — 默认扫描根解析(配置优先→DSH 家根自动识别)
|
|
269
270
|
│ │ ├── schema.js — 配置 schema(宿主导出缺失时兜底)
|
|
270
271
|
│ │ ├── settings-bridge.js — 设置读写桥(host scope 共享;绕开 client isLoopback=memory 落盘陷阱)
|
|
@@ -315,6 +316,7 @@ dsh-git-push/
|
|
|
315
316
|
│ │ ├── ignore-blind.js — 审计静默失明检测(本地 git 排除配置把整仓判成忽略时告警)
|
|
316
317
|
│ │ ├── index.js — 审计层统一出口(auditFull/auditChanged)
|
|
317
318
|
│ │ ├── orchestrate.js — 审计编排(收集→检查→汇总)
|
|
319
|
+
│ │ ├── ownership.js — (待注释)
|
|
318
320
|
│ │ ├── public.js — (待注释)
|
|
319
321
|
│ │ ├── repo-level.js — 仓库级语义规则
|
|
320
322
|
│ │ ├── report-yaml.js — (待注释)
|
|
@@ -471,6 +473,7 @@ dsh-git-push/
|
|
|
471
473
|
│ ├── audit-runtime-check.mjs — 三层审计 L3 运行时检测脚本
|
|
472
474
|
│ ├── browser-page-probe.mjs — (待注释)
|
|
473
475
|
│ ├── build-client.mjs — 客户端分片拼接(PART_ORDER + --check 门禁 + 形态铁律自检)
|
|
476
|
+
│ ├── bump-version.mjs — (待注释)
|
|
474
477
|
│ ├── check.mjs — 语法检查脚本(npm run check)
|
|
475
478
|
│ ├── clean-date-comments.py — (待注释)
|
|
476
479
|
│ ├── cpu-sample.mjs — (待注释)
|
|
@@ -622,6 +625,7 @@ dsh-git-push/
|
|
|
622
625
|
│ ├── test-picker-layout.mjs — (待注释)
|
|
623
626
|
│ ├── test-platform-scan.mjs — (待注释)
|
|
624
627
|
│ ├── test-plugin.mjs — 插件接线测试(入口导出/工具清单/双副本同步)
|
|
628
|
+
│ ├── test-privacy-ownership.mjs — (待注释)
|
|
625
629
|
│ ├── test-private-gate.mjs — (待注释)
|
|
626
630
|
│ ├── test-project-type-filter.mjs — 项目类型规则适配测试(非 dsh 项目不加载 dsh 槽位/0.x 版本规则、timeout 限 js 系、folder 尊重 gitignore——Pawchive 误报消除驱动)
|
|
627
631
|
│ ├── test-push-diagnose.mjs — (待注释)
|
package/lib/app/audit-api.js
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
import { buildRuleSlotMap } from '../audit/slot.js';
|
|
14
14
|
import { isBlockerFinding } from '../audit/index.js';
|
|
15
15
|
import { MAX_MSG_PREVIEW } from './constants.js';
|
|
16
|
+
import { probeRepoOwnership } from './repo-ownership.js';
|
|
16
17
|
|
|
17
18
|
/** 支持的聚合维度(非法值回落 rule)。 */
|
|
18
19
|
export const GROUP_BY_KEYS = ['rule', 'file', 'severity', 'slot'];
|
|
@@ -102,6 +103,7 @@ export async function runAuditApi(repo, params = {}, cfg = {}) {
|
|
|
102
103
|
const { scoreQuality } = await import('../score/index.js');
|
|
103
104
|
const scope = params.scope === 'diff' ? 'diff' : 'full';
|
|
104
105
|
const auditOpts = {
|
|
106
|
+
ownership: probeRepoOwnership(repo), // 隐私规则只对自有仓库生效(审计层只消费该字符串)
|
|
105
107
|
scope,
|
|
106
108
|
rulesetDir: params.rulesetDir || '',
|
|
107
109
|
maxScanFiles: params.maxScanFiles ?? cfg.maxScanFiles ?? 0,
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 装配层 · 仓库归属探测(供审计的隐私规则判断「是不是自己的仓库」)
|
|
3
|
+
*
|
|
4
|
+
* 为什么放在这里而不是 `lib/audit/`:
|
|
5
|
+
* 判定归属需要「本机 GitHub 账号」+「仓库 remote」,两者都在 `lib/git/**`;而边界门禁
|
|
6
|
+
* (test-audit-git-boundary.mjs)禁止 `lib/audit/**` 依赖 git 层——审计要能脱离宿主独立使用。
|
|
7
|
+
* 故探测放在装配层,结果以**字符串**注入审计(依赖倒置);纯判定逻辑在
|
|
8
|
+
* `lib/audit/ownership.js`(零依赖、可单测)。
|
|
9
|
+
*
|
|
10
|
+
* 取数口径(都只读本地,不跑网络):
|
|
11
|
+
* · 本机 login:账号状态快照(token/ssh 的 login 字段,由账号检查写入,见 account-status.js);
|
|
12
|
+
* · 仓库 owner:`git remote -v` 的 fetch URL 解析(parseGithubUrl)。
|
|
13
|
+
* 判不出(无快照 / 无 GitHub remote)一律返回 'unknown' ⇒ 上游按「照旧生效」处理。
|
|
14
|
+
*
|
|
15
|
+
* 已知局限:组织仓库的 owner 是组织名而非个人 login ⇒ 判为 'foreign'(隐私规则关闭)。
|
|
16
|
+
* 方向是保守误伤(少报),不是漏报自家隐私;如需覆盖组织仓库,可在此扩展自有组织名单。
|
|
17
|
+
*/
|
|
18
|
+
import { listRemotes, parseGithubUrl } from '../git/remote-resolve.js';
|
|
19
|
+
import { readAccountStatus } from '../git/account-status.js';
|
|
20
|
+
import { classifyOwnership } from '../audit/ownership.js';
|
|
21
|
+
|
|
22
|
+
/** 同一仓库只探一次(remote 与账号快照都是磁盘读,逐文件审计时重复开销明显)。 */
|
|
23
|
+
const CACHE = new Map();
|
|
24
|
+
|
|
25
|
+
/** 本机 GitHub 登录名(小写;取不到返回空串)。 */
|
|
26
|
+
export function localLogin() {
|
|
27
|
+
try {
|
|
28
|
+
const st = readAccountStatus({});
|
|
29
|
+
const login = String(st?.token?.login || '') || String(st?.ssh?.login || '');
|
|
30
|
+
return login.trim().toLowerCase();
|
|
31
|
+
} catch {
|
|
32
|
+
return '';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 仓库 GitHub owner(小写;无 GitHub remote 返回空串)。 */
|
|
37
|
+
export function remoteOwner(repoPath) {
|
|
38
|
+
try {
|
|
39
|
+
const map = listRemotes(repoPath || '') || {};
|
|
40
|
+
for (const name of Object.keys(map)) {
|
|
41
|
+
const url = (map[name] && (map[name].fetch || map[name].push)) || '';
|
|
42
|
+
const parsed = parseGithubUrl(String(url || ''));
|
|
43
|
+
if (parsed && parsed.owner) return String(parsed.owner).trim().toLowerCase();
|
|
44
|
+
}
|
|
45
|
+
} catch { /* 非 git 目录 / 无 remote → 空串 */ }
|
|
46
|
+
return '';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 探测仓库归属(带进程内缓存)。
|
|
51
|
+
* @param {string} repoPath 仓库根目录
|
|
52
|
+
* @returns {'own'|'foreign'|'unknown'}
|
|
53
|
+
*/
|
|
54
|
+
export function probeRepoOwnership(repoPath = '') {
|
|
55
|
+
const key = String(repoPath || '');
|
|
56
|
+
if (CACHE.has(key)) return CACHE.get(key);
|
|
57
|
+
const verdict = classifyOwnership(localLogin(), remoteOwner(key));
|
|
58
|
+
CACHE.set(key, verdict);
|
|
59
|
+
return verdict;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 清空缓存(测试用 / 账号切换后)。 */
|
|
63
|
+
export function resetRepoOwnershipCache() {
|
|
64
|
+
CACHE.clear();
|
|
65
|
+
}
|
package/lib/app/tool-call.js
CHANGED
|
@@ -35,6 +35,7 @@ import { buildAuditApiGuide } from './inject-text.js';
|
|
|
35
35
|
import { exemptStatsOf, GROUP_BY_KEYS } from './audit-api.js';
|
|
36
36
|
import { setLastSlotHitStats } from './slot-stats.js';
|
|
37
37
|
import { getDefaultScanRoot } from './scan-root.js';
|
|
38
|
+
import { probeRepoOwnership } from './repo-ownership.js';
|
|
38
39
|
|
|
39
40
|
/**
|
|
40
41
|
* 工具调用分发(薄适配:参数 → 总入口函数)。
|
|
@@ -448,6 +449,9 @@ function buildAuditOpts(args, cfg, scope) {
|
|
|
448
449
|
includeIgnored: args.includeIgnored === true,
|
|
449
450
|
// 分析覆盖率信息项(默认开;coverage:false 关闭——大仓库省一次读取+解析)
|
|
450
451
|
coverage: args.coverage !== false,
|
|
452
|
+
// 仓库归属:隐私/凭据类规则只对自有仓库生效(他人仓库等同关闭),见 lib/audit/ownership.js。
|
|
453
|
+
// 探测在装配层(依赖 git 层),审计层只消费这个字符串(边界门禁:lib/audit 不得依赖 lib/git)。
|
|
454
|
+
ownership: probeRepoOwnership(args.repo),
|
|
451
455
|
};
|
|
452
456
|
}
|
|
453
457
|
|
package/lib/audit/audit-file.js
CHANGED
|
@@ -2,6 +2,7 @@ import { runChecks } from './checks.js';
|
|
|
2
2
|
import { exemptForFinding } from '../exempt/index.js';
|
|
3
3
|
import { hasExternalCallTimeout, hasMkdirInSameFunction, hasForeignWriteTarget } from './file-context.js';
|
|
4
4
|
import { CODE_EXTS } from './finding.js';
|
|
5
|
+
import { privacyRulesEnabled, isPrivacyRule } from './ownership.js';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* 单文件审计:读文件 → 跑检查 → 豁免过滤(注册表驱动,7 标记全消费)。
|
|
@@ -132,7 +133,20 @@ export function auditFile({ file, relPath, text, grouped }, opts = {}) {
|
|
|
132
133
|
const isTestFile = /(^|[/\\])(test|tests|__tests__|spec)[/\\]|\.(test|spec)\.(js|mjs|cjs|ts)$/i.test(String(relPath || file));
|
|
133
134
|
const maintainabilityScoped = !isCode || isTestFile;
|
|
134
135
|
const scopedGrouped = maintainabilityScoped ? { ...grouped, 'repeated-string': undefined, 'min-occurrences': undefined } : grouped;
|
|
135
|
-
|
|
136
|
+
// 隐私/凭据类规则只对**自有仓库**生效:克隆来的他人仓库里有什么邮箱/密钥与本次提交无关,
|
|
137
|
+
// 报出来是纯噪声(实测:某第三方 Unity 项目 3 条 blocker 全是 LICENSE 里的作者邮箱)。
|
|
138
|
+
// 判不出归属('unknown')时照旧生效——保守方向:宁可多报,不可漏掉自家隐私。
|
|
139
|
+
const privacyOn = privacyRulesEnabled(opts?.ownership);
|
|
140
|
+
const finalGrouped = privacyOn ? scopedGrouped : (() => {
|
|
141
|
+
const stripped = {};
|
|
142
|
+
for (const [kind, rules] of Object.entries(scopedGrouped || {})) {
|
|
143
|
+
if (!Array.isArray(rules)) { stripped[kind] = rules; continue; }
|
|
144
|
+
const keep = rules.filter((r) => !isPrivacyRule(r?.id));
|
|
145
|
+
if (keep.length) stripped[kind] = keep;
|
|
146
|
+
}
|
|
147
|
+
return stripped;
|
|
148
|
+
})();
|
|
149
|
+
let findings = runChecks({ file, relPath, text, grouped: finalGrouped }, { level: opts?.level, repoHasJsYamlImport: opts?.repoHasJsYamlImport, repoLevelRules: opts?.repoLevelRules, repoPath: opts?.repoPath, treeConfirm: opts?.treeConfirm });
|
|
136
150
|
const isRuleDefFile = /(^|[/\\])audit-rules-[a-z0-9-]+\.ya?ml$/i.test(String(relPath || file));
|
|
137
151
|
const fileLines = String(text || '').split('\n');
|
|
138
152
|
// 语义级豁免:纯 regex 规则看不到的上下文在此兜底——
|
package/lib/audit/orchestrate.js
CHANGED
|
@@ -224,6 +224,7 @@ async function auditFiles(repoPath, files, opts = {}) {
|
|
|
224
224
|
level: opts.auditLevel, repoHasJsYamlImport, repoPath,
|
|
225
225
|
repoLevelRules: skipRepoLevel ? repoLevelRules : null,
|
|
226
226
|
treeConfirm,
|
|
227
|
+
ownership: opts.ownership, // 仓库归属('own'|'foreign'|'unknown'):由装配层探测注入,审计层不读 git
|
|
227
228
|
}));
|
|
228
229
|
}
|
|
229
230
|
// 跨文件重复代码检测(maintainability/no-duplicate-code,该抽公共函数)。
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 审计层 · 隐私规则的生效范围(按仓库归属)
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要(2026-10-28 用户确立的口径):
|
|
5
|
+
* 隐私/凭据类规则(secret-email、credfile-*、credref-* …)的**目的**是防止**自己的仓库**
|
|
6
|
+
* 把隐私推到远端。克隆来的第三方公开仓库里有什么邮箱/密钥,与你无关:报出来是纯粹噪声,
|
|
7
|
+
* 而且常常成片出现(实测:克隆一个 Unity 项目直接 3 条 blocker,全是第三方 LICENSE 里的
|
|
8
|
+
* 作者邮箱——版权文件含作者邮箱是法律要求,根本不是隐私泄漏)。
|
|
9
|
+
* 故:**隐私类规则只在「自己的仓库」生效;别人的 git 仓库等同关闭。**
|
|
10
|
+
*
|
|
11
|
+
* 为什么这里只放纯函数(架构约束):
|
|
12
|
+
* `lib/audit/**` 不得依赖 `lib/git/**`(边界门禁 test-audit-git-boundary.mjs:审计按独立包
|
|
13
|
+
* 设计,要能脱离宿主使用)。而「取本机账号 + 读 remote」必然依赖 git 层 ⇒ 探测放在**装配层**
|
|
14
|
+
* `lib/app/repo-ownership.js`,结果以**字符串**经 opts 注入进来(依赖倒置)。
|
|
15
|
+
* 本模块因此零 import、零副作用,可在任何环境下单测。
|
|
16
|
+
*
|
|
17
|
+
* 判据语义:'own'=自有(生效)|'foreign'=他人(关闭)|'unknown'=判不出(**照旧生效**——
|
|
18
|
+
* 保守方向:宁可多报,不可漏掉自家隐私)。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 纯函数:由「本机 login」与「仓库 owner」判归属。
|
|
23
|
+
* @param {string} login 本机 GitHub 登录名(空串 = 未知)
|
|
24
|
+
* @param {string} owner 仓库 remote 解析出的 owner(空串 = 未知)
|
|
25
|
+
* @returns {'own'|'foreign'|'unknown'}
|
|
26
|
+
*/
|
|
27
|
+
export function classifyOwnership(login = '', owner = '') {
|
|
28
|
+
const me = String(login || '').trim().toLowerCase();
|
|
29
|
+
const them = String(owner || '').trim().toLowerCase();
|
|
30
|
+
if (!me || !them) return 'unknown';
|
|
31
|
+
return them === me ? 'own' : 'foreign';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 隐私/凭据类规则是否应在该仓库生效。
|
|
36
|
+
* @param {'own'|'foreign'|'unknown'} [ownership] 归属(缺省/undefined 按 unknown 处理 ⇒ 生效)
|
|
37
|
+
* @returns {boolean} true = 生效;false = 他人仓库,关闭
|
|
38
|
+
*/
|
|
39
|
+
export function privacyRulesEnabled(ownership) {
|
|
40
|
+
return ownership !== 'foreign';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 规则 id 是否属隐私/凭据类(这类规则受归属限制)。 */
|
|
44
|
+
export function isPrivacyRule(ruleId) {
|
|
45
|
+
return /^(secret-|credfile-|credref-)/.test(String(ruleId || ''));
|
|
46
|
+
}
|
|
@@ -15,6 +15,7 @@ import { readSettings, applySettingsToCfg } from '../app/settings-bridge.js';
|
|
|
15
15
|
import { defaultConfig } from '../client/index.js';
|
|
16
16
|
import { access } from 'node:fs/promises';
|
|
17
17
|
import { join } from 'node:path';
|
|
18
|
+
import { probeRepoOwnership } from '../app/repo-ownership.js';
|
|
18
19
|
|
|
19
20
|
/** 审计 full 扫描 findings 打印条数上限(防刷屏)。 */
|
|
20
21
|
const AUDIT_PRINT_LIMIT = 20;
|
|
@@ -78,6 +79,7 @@ async function runHistoryAuditCmd(root, flags) {
|
|
|
78
79
|
const cfg = cliPluginConfig();
|
|
79
80
|
const { runHistoryAudit } = await import('../audit/history.js');
|
|
80
81
|
const opts = pluginEqualAuditOpts(cfg, flags, { scope: 'full' });
|
|
82
|
+
opts.ownership = probeRepoOwnership(root); // 与插件工具同参:隐私规则只对自有仓库生效
|
|
81
83
|
const weights = pluginEqualWeights(cfg, flags);
|
|
82
84
|
const r = await runHistoryAudit(root || '.', {
|
|
83
85
|
since: flags.since, until: flags.until, outDir: flags.out,
|
|
@@ -96,6 +98,7 @@ async function runStandardAudit(root, flags) {
|
|
|
96
98
|
const cfg = cliPluginConfig();
|
|
97
99
|
const full = flags.full === true || !(await pathExists(join(root || '.', '.git')));
|
|
98
100
|
const opts = pluginEqualAuditOpts(cfg, flags, { scope: full ? 'full' : 'diff' });
|
|
101
|
+
opts.ownership = probeRepoOwnership(root); // 与插件工具同参:隐私规则只对自有仓库生效
|
|
99
102
|
const weights = pluginEqualWeights(cfg, flags);
|
|
100
103
|
const auditResult = full ? await auditFull(root, opts) : await auditWithScope(root, opts);
|
|
101
104
|
const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files });
|
package/lib/self/index.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
export const VERSION = '2.10.
|
|
12
|
+
export const VERSION = '2.10.5'; // 2.10.5:隐私/凭据类规则只对自有仓库生效(他人仓库等同关闭):克隆的第三方仓库里第三方 LICENSE/ReadMe 的作者邮箱不再成片报 blocker(实测某 Unity 项目 3 条 blocker 全由此而来);判不出归属时照旧生效(保守)。归属探测放装配层 lib/app/repo-ownership.js(依赖 git 层),审计层 lib/audit/ownership.js 只留纯函数并消费注入的归属字符串,守住『lib/audit 不依赖 lib/git』边界;CLI 与插件工具同参注入,保证两边结果一致。新增 scripts/bump-version.mjs:一键升版(默认 dry-run、--apply 才写盘),把散在三处的版本号收口,并自动重生成派生文档。另含 2.10.4 的 CIFS 克隆修复。。历史:2.10.4:修掉「克隆到 CIFS/SMB 挂载失败」——根因是 git init 要把 core.filemode 写进 .git/config,而写 config 走 config.lock→chmod→rename,挂载带 nounix 时 chmod 恒 EPERM ⇒ git 直接 fatal(留下未初始化的空 .git,整体克隆失败)。新增 lib/git/init-compat.js:真去 chmod 一个临时文件探测能力,不支持时手工搭最小 .git 结构(HEAD + config[filemode=false] + 空 objects/refs/info;remote 段一并手写,因 git remote add 同样要写 config),绕开 git 的 config 写入流程;实测降级后 add/commit/log/status/remote 全部正常。三处 init 调用点(clone.js / clone-history-mode.js / clone-replay-io.js)统一走该兼容层,deps 可注入 chmodOk 便于测试。新增 test/test-init-compat.mjs(6 例,含「降级结构必须是真仓库」与自证)。实测:katboi01/UmaViewer(157MB)经插件成功克隆到 CIFS 挂载,HEAD 与远端一致、脏文件 0。。2.10.3:忽略链路端到端回归。
|
|
13
13
|
// 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
|
|
14
14
|
// 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
|
|
15
15
|
// 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
|
package/package.json
CHANGED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* dsh-git-push — 一键版本升版(bump-version)
|
|
4
|
+
*
|
|
5
|
+
* 为什么要有这个脚本:版本号散在三处手工同步,每次发版都要手改
|
|
6
|
+
* ① `package.json` 的 version
|
|
7
|
+
* ② `lib/self/index.js` 的 `export const VERSION = '<v>'; // <v>:说明。历史:…`
|
|
8
|
+
* ③ `docs/releases.json` 新增一条 `<v>: "说明"`
|
|
9
|
+
* 少改一处就会被 doc-version / version-drift 门禁判为漂移,而这两处还各带长文本
|
|
10
|
+
* (VERSION 行还挂着历史链),手改既慢又容易写坏引号、破坏 JSON。
|
|
11
|
+
* 第 4 处(README 版本表 / CHANGELOG)已由 doc-version.mjs 从上面两处生成,无需手改。
|
|
12
|
+
*
|
|
13
|
+
* 用法:
|
|
14
|
+
* node scripts/bump-version.mjs --message "本次做了什么" # 预览(默认 dry-run)
|
|
15
|
+
* node scripts/bump-version.mjs --message "…" --apply # 真写盘
|
|
16
|
+
* node scripts/bump-version.mjs --to 2.11.0 --message "…" --apply # 指定版本(默认 patch +1)
|
|
17
|
+
* node scripts/bump-version.mjs --message-file /tmp/msg.txt --apply
|
|
18
|
+
*
|
|
19
|
+
* 约定:
|
|
20
|
+
* · **默认 dry-run**——只打印将要改动的三处(旧值 → 新值),不落盘;确认无误再加 --apply。
|
|
21
|
+
* (与 npm_publish / install-plugin 同口径:有副作用的动作先看预览再执行)
|
|
22
|
+
* · `--message` 必填:发版说明不能凭空生成,属于「人写内容」,脚本只负责把它同步到三处。
|
|
23
|
+
* · VERSION 行的历史链保留最近 2 个版本摘要,避免注释无限变长(沿用既有风格)。
|
|
24
|
+
* · 写完自动重生成版本文档(doc-version apply / doc-func apply / doc-tree sync+apply),
|
|
25
|
+
* 因为版本号一变,CHANGELOG 与函数索引必须跟着走,否则门禁立刻报漂移。
|
|
26
|
+
*/
|
|
27
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
28
|
+
import { join, dirname } from 'node:path';
|
|
29
|
+
import { fileURLToPath } from 'node:url';
|
|
30
|
+
import { execFileSync } from 'node:child_process';
|
|
31
|
+
|
|
32
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
33
|
+
const PKG = join(ROOT, 'package.json');
|
|
34
|
+
const SELF = join(ROOT, 'lib', 'self', 'index.js');
|
|
35
|
+
const RELEASES = join(ROOT, 'docs', 'releases.json');
|
|
36
|
+
|
|
37
|
+
/** 解析命令行参数(只认 --flag value 与布尔 --apply)。 */
|
|
38
|
+
function parseArgs(argv) {
|
|
39
|
+
const out = { apply: false, to: '', message: '', messageFile: '' };
|
|
40
|
+
for (let i = 0; i < argv.length; i++) {
|
|
41
|
+
const a = argv[i];
|
|
42
|
+
if (a === '--apply') { out.apply = true; continue; }
|
|
43
|
+
if (a === '--message' || a === '-m') { out.message = argv[++i] || ''; continue; }
|
|
44
|
+
if (a === '--message-file') { out.messageFile = argv[++i] || ''; continue; }
|
|
45
|
+
if (a === '--to') { out.to = argv[++i] || ''; continue; }
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const fail = (msg) => { console.error('✗ ' + msg); process.exit(1); };
|
|
51
|
+
|
|
52
|
+
/** 语义化版本比较:a < b 返回负。只支持 x.y.z。 */
|
|
53
|
+
function cmpVer(a, b) {
|
|
54
|
+
const pa = String(a).split('.').map(Number);
|
|
55
|
+
const pb = String(b).split('.').map(Number);
|
|
56
|
+
for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** patch +1:默认每次提交升第三位(version-discipline 的既有口径)。 */
|
|
61
|
+
function bumpPatch(v) {
|
|
62
|
+
const [x, y, z] = String(v).split('.').map(Number);
|
|
63
|
+
return `${x}.${y}.${(z || 0) + 1}`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function readJson(p) {
|
|
67
|
+
try { return JSON.parse(readFileSync(p, 'utf8')); } catch (e) { fail(`${p} 解析失败:${e.message}`); }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 拼新的 VERSION 行。
|
|
72
|
+
* 旧注释形如:`2.10.4:本次说明。历史:2.10.3:更早说明。` → 把「本次说明」降级进历史链,
|
|
73
|
+
* 只保留最近 2 条,避免每版都把整串历史再抄一遍(实测 2.9.x 之后该行已接近不可读)。
|
|
74
|
+
*/
|
|
75
|
+
function buildVersionLine(oldLine, newVer, oldVer, message) {
|
|
76
|
+
const m = /export const VERSION = '([^']+)';\s*\/\/(.*)$/.exec(oldLine);
|
|
77
|
+
const oldComment = m ? m[2].trim() : '';
|
|
78
|
+
// 旧版本的「本次说明」= 历史链之前的那一段
|
|
79
|
+
const histIdx = oldComment.indexOf('历史:');
|
|
80
|
+
const oldMain = (histIdx >= 0 ? oldComment.slice(0, histIdx) : oldComment).replace(/^[\d.]+\s*[::]\s*/, '').trim();
|
|
81
|
+
const oldHist = histIdx >= 0 ? oldComment.slice(histIdx + '历史:'.length).trim() : '';
|
|
82
|
+
// 历史链:新压入的旧版摘要 + 原有最近 1 条
|
|
83
|
+
const prev = oldMain ? [`${oldVer}:${oldMain}`] : [];
|
|
84
|
+
const kept = oldHist ? oldHist.split(/。\s*(?=[\d.]+:)/).slice(0, 1).map((s) => s.replace(/。$/, '')) : [];
|
|
85
|
+
const chain = [...prev, ...kept].join('。');
|
|
86
|
+
const comment = `${newVer}:${message}。` + (chain ? `历史:${chain}。` : '');
|
|
87
|
+
return `export const VERSION = '${newVer}'; // ${comment}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const args = parseArgs(process.argv.slice(2));
|
|
91
|
+
const pkg = readJson(PKG);
|
|
92
|
+
const cur = String(pkg.version || '');
|
|
93
|
+
const target = args.to || bumpPatch(cur);
|
|
94
|
+
let message = args.message;
|
|
95
|
+
if (args.messageFile) {
|
|
96
|
+
try { message = readFileSync(args.messageFile, 'utf8').trim(); } catch (e) { fail(`--message-file 读取失败:${e.message}`); }
|
|
97
|
+
}
|
|
98
|
+
if (!/^\d+\.\d+\.\d+$/.test(target)) fail(`版本号必须为 x.y.z:${target}`);
|
|
99
|
+
if (cmpVer(target, cur) <= 0) fail(`目标版本 ${target} 必须大于当前 ${cur}`);
|
|
100
|
+
if (!message) fail('缺少 --message(发版说明需人写;或从 --message-file 读取)');
|
|
101
|
+
|
|
102
|
+
const releases = readJson(RELEASES);
|
|
103
|
+
if (releases[target]) fail(`docs/releases.json 已存在 ${target} 条目(不要重复升版)`);
|
|
104
|
+
|
|
105
|
+
const selfSrc = readFileSync(SELF, 'utf8');
|
|
106
|
+
const selfLines = selfSrc.split('\n');
|
|
107
|
+
const vi = selfLines.findIndex((l) => /^export const VERSION = '/.test(l));
|
|
108
|
+
if (vi < 0) fail('lib/self/index.js 未找到 VERSION 行');
|
|
109
|
+
const oldLine = selfLines[vi];
|
|
110
|
+
const newLine = buildVersionLine(oldLine, target, cur, message);
|
|
111
|
+
|
|
112
|
+
// ── 预览(默认 dry-run)
|
|
113
|
+
console.log(`升版:${cur} → ${target}${args.apply ? '(--apply 真写盘)' : '(dry-run,未写盘)'}`);
|
|
114
|
+
console.log('\n① package.json');
|
|
115
|
+
console.log(` - "version": "${cur}"`);
|
|
116
|
+
console.log(` + "version": "${target}"`);
|
|
117
|
+
console.log('\n② lib/self/index.js(VERSION 行)');
|
|
118
|
+
console.log(` - ${oldLine.slice(0, 90)}…`);
|
|
119
|
+
console.log(` + ${newLine.slice(0, 90)}…`);
|
|
120
|
+
console.log('\n③ docs/releases.json');
|
|
121
|
+
console.log(` + "${target}": "${message.slice(0, 70)}${message.length > 70 ? '…' : ''}"`);
|
|
122
|
+
console.log('\n④ 随后自动重生成:docs/CHANGELOG.md(doc-version)、docs/FUNCTIONS.md(doc-func)、tree-doc.json(doc-tree)');
|
|
123
|
+
|
|
124
|
+
if (!args.apply) {
|
|
125
|
+
console.log('\n确认无误后追加 --apply 才会写盘。');
|
|
126
|
+
process.exit(0);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ── 写盘
|
|
130
|
+
// 注意:本仓库在 CIFS 挂载上,write/edit 工具会因 chmod 报 EPERM;脚本用 fs 直接写
|
|
131
|
+
// 普通文件(不触发 chmod),这正是把它脚本化的额外收益。
|
|
132
|
+
const newPkgText = readFileSync(PKG, 'utf8').replace(
|
|
133
|
+
/("version"\s*:\s*")[^"]+(")/,
|
|
134
|
+
`$1${target}$2`,
|
|
135
|
+
);
|
|
136
|
+
if (newPkgText === readFileSync(PKG, 'utf8')) fail('package.json 的 version 未替换成功(正则未命中)');
|
|
137
|
+
writeFileSync(PKG, newPkgText);
|
|
138
|
+
|
|
139
|
+
selfLines[vi] = newLine;
|
|
140
|
+
writeFileSync(SELF, selfLines.join('\n'));
|
|
141
|
+
|
|
142
|
+
const merged = { ...releases };
|
|
143
|
+
merged[target] = message;
|
|
144
|
+
// 按语义化版本排序,保持文件可读(原文件即按版本升序)
|
|
145
|
+
const sorted = {};
|
|
146
|
+
for (const k of Object.keys(merged).sort(cmpVer)) sorted[k] = merged[k];
|
|
147
|
+
writeFileSync(RELEASES, JSON.stringify(sorted, null, 2) + '\n');
|
|
148
|
+
|
|
149
|
+
console.log('\n✔ 三处已写入,重生成派生文档…');
|
|
150
|
+
for (const cmd of [
|
|
151
|
+
['scripts/doc-version.mjs', ['apply']],
|
|
152
|
+
['scripts/doc-func.mjs', ['apply']],
|
|
153
|
+
['scripts/doc-tree.mjs', ['sync']],
|
|
154
|
+
['scripts/doc-tree.mjs', ['apply']],
|
|
155
|
+
]) {
|
|
156
|
+
try {
|
|
157
|
+
execFileSync(process.execPath, [join(ROOT, cmd[0]), ...cmd[1]], { cwd: ROOT, stdio: 'pipe', encoding: 'utf8' });
|
|
158
|
+
console.log(` ✔ ${cmd[0]} ${cmd[1].join(' ')}`);
|
|
159
|
+
} catch (e) {
|
|
160
|
+
console.error(` ✗ ${cmd[0]} 失败:${String(e?.stdout || e?.stderr || e).split('\n')[0]}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
console.log(`\n完成:${cur} → ${target}。请跑 node scripts/doc-version.mjs check 与全量回归确认门禁绿。`);
|