dsh-git-push 2.20.19 → 3.1.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.
- package/README.md +76 -47
- package/cli-tool.mjs +2 -4
- package/cli.mjs +11 -4
- package/lib/app/apply.js +15 -13
- package/lib/app/command-registry.js +26 -19
- package/lib/app/handlers/http-constants.js +8 -0
- package/lib/app/handlers/meta.js +2 -2
- package/lib/app/handlers/preprocess.js +104 -0
- package/lib/app/handlers/repo-actions.js +2 -3
- package/lib/app/handlers/repos.js +137 -10
- package/lib/app/handlers/settings.js +34 -15
- package/lib/app/http-handlers.js +13 -42
- package/lib/app/index.js +3 -2
- package/lib/app/inject-text.js +6 -21
- package/lib/app/preprocess-client.js +136 -0
- package/lib/app/repo-ownership.js +1 -1
- package/lib/app/schema.js +20 -10
- package/lib/app/settings-bridge.js +60 -8
- package/lib/app/severity.js +14 -0
- package/lib/app/slash-commands.js +5 -164
- package/lib/app/tool-call.js +96 -163
- package/lib/cli/commands-preprocess.mjs +74 -0
- package/lib/cli/commands-tool.mjs +3 -2
- package/lib/cli/commands-vcs.mjs +39 -5
- package/lib/cli/shared.mjs +36 -10
- package/lib/client/index.js +11 -16
- package/lib/client-parts/git/account.js +21 -12
- package/lib/client-parts/git/actions.js +23 -77
- package/lib/client-parts/git/apply.js +8 -2
- package/lib/client-parts/git/browser.js +1 -1
- package/lib/client-parts/git/const.js +33 -1
- package/lib/client-parts/git/controller.js +175 -176
- package/lib/client-parts/git/icons.js +1 -1
- package/lib/client-parts/git/loader.js +1 -1
- package/lib/client-parts/git/npm.js +56 -37
- package/lib/client-parts/git/page.js +53 -1
- package/lib/client-parts/git/repo.js +8 -1
- package/lib/client-parts/git/settings.js +13 -1
- package/lib/client-parts/git/state.js +237 -0
- package/lib/client-parts/git/utils.js +1 -1
- package/lib/client.js +631 -312
- package/lib/commit-push/pre-commit-engine.js +629 -30
- package/lib/commit-push.js +127 -67
- package/lib/context/index.js +7 -5
- package/lib/core/config.js +1 -27
- package/lib/core/exec.js +2 -11
- package/lib/{exempt/index.js → git/exempt-markers.js} +8 -1
- package/lib/git/identity-rewrite.js +1 -1
- package/lib/git/ignore.js +1 -1
- package/lib/git/index.js +1 -1
- package/lib/git/push.js +2 -17
- package/lib/git/repo-index.js +8 -3
- package/lib/git/repos.js +2 -2
- package/lib/git/sensitive.js +1 -1
- package/lib/npm/install.js +1 -1
- package/lib/npm/publish.js +20 -5
- package/lib/npm/registry.js +2 -2
- package/lib/plugin/auto-push.js +5 -8
- package/lib/preprocess/providers.js +195 -0
- package/lib/self/index.js +1 -1
- package/lib/skip-dirs.js +14 -55
- package/package.json +31 -42
- package/skills/dev/dsh-git-push.md +9 -9
- package/skills/guide/guide-commit-push.md +11 -13
- package/skills/workflow/README.md +0 -1
- package/skills/workflow/task-completion-report.md +2 -2
- package/.auditignore +0 -30
- package/.gitignore +0 -43
- package/cli-audit.mjs +0 -141
- package/lib/BUGFIX-NOTES-2026-09-14.md +0 -278
- package/lib/app/audit-api.js +0 -173
- package/lib/app/handlers/audit.js +0 -150
- package/lib/app/host-doc-checks.js +0 -25
- package/lib/app/schema-audit.js +0 -42
- package/lib/app/scope-check.js +0 -69
- package/lib/ast/brace.js +0 -120
- package/lib/ast/callgraph.js +0 -135
- package/lib/ast/code-lines.js +0 -175
- package/lib/ast/consts.js +0 -12
- package/lib/ast/control-flow.js +0 -470
- package/lib/ast/credential.js +0 -315
- package/lib/ast/dataflow.js +0 -391
- package/lib/ast/dup-code.js +0 -165
- package/lib/ast/fs-hotspots.js +0 -154
- package/lib/ast/index.js +0 -38
- package/lib/ast/io-risk-const.js +0 -95
- package/lib/ast/io-risk-fn.js +0 -208
- package/lib/ast/io-risk-loop.js +0 -308
- package/lib/ast/io-risk.js +0 -314
- package/lib/ast/lang.js +0 -156
- package/lib/ast/line-count.js +0 -52
- package/lib/ast/magic-number.js +0 -272
- package/lib/ast/naming.js +0 -292
- package/lib/ast/perf.js +0 -488
- package/lib/ast/scope-collisions.js +0 -228
- package/lib/ast/scope.js +0 -241
- package/lib/ast/shell.js +0 -131
- package/lib/ast/size.js +0 -448
- package/lib/ast/symbol-index.js +0 -399
- package/lib/ast/tokenizer.js +0 -421
- package/lib/ast/treesitter.js +0 -413
- package/lib/audit/analysis-coverage.js +0 -98
- package/lib/audit/audit-file.js +0 -205
- package/lib/audit/auditignore-rules.js +0 -148
- package/lib/audit/checks.js +0 -17
- package/lib/audit/client-entry.js +0 -93
- package/lib/audit/collector.js +0 -610
- package/lib/audit/ext-runner.js +0 -80
- package/lib/audit/file-context.js +0 -391
- package/lib/audit/finding.js +0 -101
- package/lib/audit/gitignore-match.js +0 -113
- package/lib/audit/glob.js +0 -63
- package/lib/audit/history-report.js +0 -100
- package/lib/audit/history.js +0 -126
- package/lib/audit/ignore-blind.js +0 -102
- package/lib/audit/index.js +0 -33
- package/lib/audit/orchestrate.js +0 -672
- package/lib/audit/public.js +0 -24
- package/lib/audit/repo-level.js +0 -30
- package/lib/audit/report-yaml.js +0 -90
- package/lib/audit/scope-policy.js +0 -110
- package/lib/audit/slot.js +0 -66
- package/lib/audit-rules/audit-rules-comment.yml +0 -199
- package/lib/audit-rules/audit-rules-cpp.yml +0 -114
- package/lib/audit-rules/audit-rules-csharp.yml +0 -82
- package/lib/audit-rules/audit-rules-docs.yml +0 -32
- package/lib/audit-rules/audit-rules-dsh.yml +0 -177
- package/lib/audit-rules/audit-rules-filehealth.yml +0 -42
- package/lib/audit-rules/audit-rules-folder.yml +0 -99
- package/lib/audit-rules/audit-rules-frontend.yml +0 -335
- package/lib/audit-rules/audit-rules-go.yml +0 -103
- package/lib/audit-rules/audit-rules-i18n.yml +0 -45
- package/lib/audit-rules/audit-rules-java.yml +0 -105
- package/lib/audit-rules/audit-rules-nodejs.yml +0 -662
- package/lib/audit-rules/audit-rules-npm.yml +0 -187
- package/lib/audit-rules/audit-rules-paths.yml +0 -98
- package/lib/audit-rules/audit-rules-performance.yml +0 -245
- package/lib/audit-rules/audit-rules-php.yml +0 -101
- package/lib/audit-rules/audit-rules-private.yml +0 -24
- package/lib/audit-rules/audit-rules-python.yml +0 -106
- package/lib/audit-rules/audit-rules-robustness.yml +0 -31
- package/lib/audit-rules/audit-rules-rust.yml +0 -109
- package/lib/audit-rules/audit-rules-structure.yml +0 -158
- package/lib/audit-rules/audit-rules-swift.yml +0 -99
- package/lib/audit-rules/audit-rules-template.yml +0 -108
- package/lib/audit-ui-sdk/contract.js +0 -117
- package/lib/audit-ui-sdk/index.js +0 -17
- package/lib/checks/button-bind.js +0 -347
- package/lib/checks/common.js +0 -170
- package/lib/checks/credential-file.js +0 -43
- package/lib/checks/dataflow.js +0 -40
- package/lib/checks/dispatch.js +0 -117
- package/lib/checks/dup-code.js +0 -69
- package/lib/checks/dup-const.js +0 -232
- package/lib/checks/file-health.js +0 -150
- package/lib/checks/filter.js +0 -137
- package/lib/checks/folder.js +0 -173
- package/lib/checks/fs-scanner.js +0 -57
- package/lib/checks/hardcoded-path.js +0 -98
- package/lib/checks/index.js +0 -49
- package/lib/checks/io.js +0 -66
- package/lib/checks/magic-number.js +0 -42
- package/lib/checks/npm-json.js +0 -273
- package/lib/checks/private.js +0 -64
- package/lib/checks/regex.js +0 -298
- package/lib/checks/scope-collision.js +0 -68
- package/lib/checks/semantic.js +0 -134
- package/lib/checks/structural.js +0 -281
- package/lib/cli/commands-audit.mjs +0 -142
- package/lib/cli/commands-doc.mjs +0 -127
- package/lib/client-parts/audit/audit.js +0 -301
- package/lib/exempt/tool.js +0 -198
- package/lib/git/module-splitter.js +0 -47
- package/lib/link-check/index.js +0 -187
- package/lib/lint-adapter/detect.js +0 -161
- package/lib/lint-adapter/index.js +0 -50
- package/lib/lint-adapter/runner.js +0 -133
- package/lib/preprocess/audit.js +0 -98
- package/lib/preprocess/index.js +0 -78
- package/lib/rule/compilers/credential.js +0 -62
- package/lib/rule/compilers/dataflow.js +0 -38
- package/lib/rule/compilers/file-health.js +0 -75
- package/lib/rule/compilers/frontend.js +0 -86
- package/lib/rule/compilers/func.js +0 -35
- package/lib/rule/compilers/helpers.js +0 -71
- package/lib/rule/compilers/index.js +0 -29
- package/lib/rule/compilers/link-semantic.js +0 -45
- package/lib/rule/compilers/list-kinds.js +0 -12
- package/lib/rule/compilers/numeric-kinds.js +0 -73
- package/lib/rule/compilers/regex.js +0 -78
- package/lib/rule/compilers/structure.js +0 -107
- package/lib/rule/compilers.js +0 -17
- package/lib/rule/homoglyph.js +0 -45
- package/lib/rule/loader.js +0 -274
- package/lib/rule/registry.js +0 -122
- package/lib/rule/scope.js +0 -67
- package/lib/score/docs-score.js +0 -166
- package/lib/score/index.js +0 -234
- package/lib/user-requirements.json +0 -15
- package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
- package/scripts/audit-ext/_example-readme-present.mjs +0 -34
- package/scripts/audit-ext/dsh-inject-declarations.mjs +0 -209
- package/scripts/audit-ext/variable-min-length.mjs +0 -102
- package/scripts/audit-gate.mjs +0 -235
- package/scripts/audit-runner.mjs +0 -35
- package/scripts/audit-runtime-check.mjs +0 -129
- package/scripts/browser-page-probe.mjs +0 -271
- package/scripts/build-client.mjs +0 -131
- package/scripts/bump-version.mjs +0 -178
- package/scripts/check-js-scope.mjs +0 -87
- package/scripts/check.mjs +0 -203
- package/scripts/clean-date-comments.py +0 -102
- package/scripts/cpu-sample.mjs +0 -188
- package/scripts/doc-drift.mjs +0 -200
- package/scripts/doc-func.mjs +0 -212
- package/scripts/doc-tree.mjs +0 -458
- package/scripts/doc-version.mjs +0 -149
- package/scripts/hot-path-probe-cjs.cjs +0 -71
- package/scripts/hot-path-probe-fs-shim.mjs +0 -28
- package/scripts/hot-path-probe-fsp-shim.mjs +0 -31
- package/scripts/hot-path-probe.mjs +0 -153
- package/scripts/local-registry.mjs +0 -37
- package/scripts/module-splitter.py +0 -800
- package/scripts/picker-repro.mjs +0 -115
- package/scripts/platform-scan.mjs +0 -168
- package/scripts/probe-recheck.mjs +0 -47
- package/scripts/rename-locator.mjs +0 -97
- package/scripts/rule-switch.mjs +0 -97
- package/scripts/rules-solo-audit.mjs +0 -173
- package/scripts/scan-file-io.mjs +0 -717
- package/scripts/scan-fs-hotspots.mjs +0 -107
- package/scripts/scan-version.mjs +0 -125
- package/scripts/symbol-index.mjs +0 -85
- package/scripts/verify-prestep.mjs +0 -100
- package/scripts/version-source.mjs +0 -173
- package/skills/dev/audit-rule-authoring.md +0 -58
- package/skills/guide/guide-audit.md +0 -270
- /package/lib/{audit → app}/ownership.js +0 -0
- /package/lib/{audit-defaults.js → git/defaults.js} +0 -0
package/scripts/picker-repro.mjs
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
// dsh-skip-quality: 本文件只生成**静态自检页**(用真实 CSS 拼一个最小复现,供人目测布局),
|
|
2
|
-
// 其中的按钮是布局样本、不承担交互,未绑事件属预期(规则判定无误,属「判对但不需要」)。
|
|
3
|
-
/**
|
|
4
|
-
* 目录选择器布局自检页生成器(无依赖、离线)。
|
|
5
|
-
*
|
|
6
|
-
* 为什么需要:选择器弹窗的「条目多时被压扁」是**纯布局缺陷**——CSS 文本看着没问题
|
|
7
|
-
* (`max-height` + `overflow-y:auto` 都在),只有真实渲染才暴露。实测 73 条目录在
|
|
8
|
-
* 1080px 视口下,行高从应有的 27px 被压到 10px、容器根本不滚动,而任何
|
|
9
|
-
* 「断言 CSS 里有某条声明」的单元测试都会通过。
|
|
10
|
-
*
|
|
11
|
-
* 本脚本用**真实 CSS**(直接从 lib/client-parts/const.js 抽取 .dshgp_* 规则)拼一个
|
|
12
|
-
* 最小复现页:只有 mask/dialog/path/up/list/foot 六层与 N 个目录行。
|
|
13
|
-
* 在浏览器里打开即可目测;配合一段测量脚本可拿到行高/可滚动性等硬指标。
|
|
14
|
-
*
|
|
15
|
-
* 用法:
|
|
16
|
-
* node scripts/picker-repro.mjs # 生成 /tmp/dshgp-picker-repro.html(默认 73 条)
|
|
17
|
-
* node scripts/picker-repro.mjs --count 300 # 指定条目数
|
|
18
|
-
* node scripts/picker-repro.mjs --out <路径>
|
|
19
|
-
* node scripts/picker-repro.mjs --serve # 生成后用本机 http 起服务并打印地址
|
|
20
|
-
*
|
|
21
|
-
* 判读标准(在浏览器控制台跑 MEASURE_SNIPPET):
|
|
22
|
-
* rowHeight 应 ≈ 26-28px(12px 字 + 上下 5px padding + 行高)
|
|
23
|
-
* listScrollable true(条目超容器时必须能滚,而不是压扁)
|
|
24
|
-
* footerInViewport true(「选择当前目录」必须留在视口内)
|
|
25
|
-
*/
|
|
26
|
-
import { readFileSync, writeFileSync } from 'node:fs';
|
|
27
|
-
import { join, dirname } from 'node:path';
|
|
28
|
-
import { fileURLToPath } from 'node:url';
|
|
29
|
-
import { createServer } from 'node:http';
|
|
30
|
-
|
|
31
|
-
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
32
|
-
const CONST_FILE = join(ROOT, 'lib', 'client-parts', 'const.js');
|
|
33
|
-
const DEFAULT_OUT = '/tmp/dshgp-picker-repro.html';
|
|
34
|
-
const DEFAULT_COUNT = 73;
|
|
35
|
-
|
|
36
|
-
/** 从 const.js 抽取全部 .dshgp_* 规则原文(保证自检页与真实样式同源)。 */
|
|
37
|
-
export function extractCss(src = readFileSync(CONST_FILE, 'utf8')) {
|
|
38
|
-
return [...src.matchAll(/'\.(dshgp_[a-z0-9_]+)\{([^}]*)\}'/g)]
|
|
39
|
-
.map((m) => `.${m[1]}{${m[2]}}`)
|
|
40
|
-
.join('\n');
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** 生成复现页 HTML。 */
|
|
44
|
-
export function buildReproHtml({ count = DEFAULT_COUNT, css = extractCss() } = {}) {
|
|
45
|
-
const rows = Array.from({ length: count }, (_, i) => {
|
|
46
|
-
const name = `项目目录-${String(i + 1).padStart(2, '0')}-很长的中文目录名用于测试挤压`;
|
|
47
|
-
return `<div class="dshgp_browsedir" data-path="/x/${name}">📁 ${name}</div>`;
|
|
48
|
-
}).join('');
|
|
49
|
-
// 暗色变量只是为了目测接近真实主题,不参与布局判定
|
|
50
|
-
const vars = ':root{--dsw-alias-border-l4:#444;--dsw-alias-border-l2:#333;'
|
|
51
|
-
+ '--dsw-alias-bg-layer-3:#1b1b2a;--dsw-alias-bg-layer-2:#222;--dsw-alias-bg-base:#111;'
|
|
52
|
-
+ '--dsw-alias-label-primary:#eee;--dsw-alias-label-secondary:#aaa;'
|
|
53
|
-
+ '--dsw-alias-label-tertiary:#888;--dsw-alias-brand-primary:#7c5cff}';
|
|
54
|
-
return '<!doctype html><meta charset="utf-8"><title>picker repro</title>'
|
|
55
|
-
+ `<style>${vars}${css}</style>`
|
|
56
|
-
+ '<body style="margin:0;height:100vh;background:#0d0d14">'
|
|
57
|
-
+ '<div class="dshgp_browsemask"><div class="dshgp_browsedialog">'
|
|
58
|
-
+ '<div class="dshgp_browsehead"><span class="dshgp_browsetitle">选择目录</span>'
|
|
59
|
-
+ '<button type="button" class="dshgp_browseclose">✕</button></div>'
|
|
60
|
-
+ '<div class="dshgp_browsepath">/volume1/VirtualDSM/DeepSeekHarness/工作区</div>'
|
|
61
|
-
+ '<div class="dshgp_browseup">⬆ 上级目录</div>'
|
|
62
|
-
+ `<div class="dshgp_browselist" id="list">${rows}</div>`
|
|
63
|
-
+ '<div class="dshgp_browsefoot"><button type="button" class="dshgp_keybtn">选择当前目录</button></div>'
|
|
64
|
-
+ '</div></div></body>';
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** 浏览器控制台测量脚本(返回硬指标 JSON)。 */
|
|
68
|
-
export const MEASURE_SNIPPET = `(() => {
|
|
69
|
-
const list = document.getElementById('list');
|
|
70
|
-
const rows = [...list.children];
|
|
71
|
-
const lb = list.getBoundingClientRect();
|
|
72
|
-
const f = rows[0].getBoundingClientRect();
|
|
73
|
-
const foot = document.querySelector('.dshgp_browsefoot').getBoundingClientRect();
|
|
74
|
-
return {
|
|
75
|
-
rows: rows.length,
|
|
76
|
-
rowHeight: Math.round(f.height * 10) / 10,
|
|
77
|
-
rowFlexShrink: getComputedStyle(rows[0]).flexShrink,
|
|
78
|
-
listClientH: list.clientHeight,
|
|
79
|
-
listScrollH: list.scrollHeight,
|
|
80
|
-
listScrollable: list.scrollHeight > list.clientHeight,
|
|
81
|
-
visibleRows: Math.round(lb.height / f.height),
|
|
82
|
-
footerInViewport: foot.bottom <= innerHeight,
|
|
83
|
-
};
|
|
84
|
-
})()`;
|
|
85
|
-
|
|
86
|
-
function argOf(name, def) {
|
|
87
|
-
const i = process.argv.indexOf(name);
|
|
88
|
-
return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : def;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function main() {
|
|
92
|
-
const count = Number(argOf('--count', String(DEFAULT_COUNT))) || DEFAULT_COUNT;
|
|
93
|
-
const out = argOf('--out', DEFAULT_OUT);
|
|
94
|
-
const html = buildReproHtml({ count });
|
|
95
|
-
writeFileSync(out, html, 'utf8');
|
|
96
|
-
console.log(`✅ 已生成复现页:${out}(${count} 条目录,${html.length} 字节)`);
|
|
97
|
-
console.log('');
|
|
98
|
-
console.log('浏览器打开后,控制台粘贴以下脚本取硬指标:');
|
|
99
|
-
console.log(MEASURE_SNIPPET);
|
|
100
|
-
console.log('');
|
|
101
|
-
console.log('判读:rowHeight≈26-28px · listScrollable=true · footerInViewport=true');
|
|
102
|
-
if (!process.argv.includes('--serve')) return 0;
|
|
103
|
-
const port = Number(argOf('--port', '31399'));
|
|
104
|
-
const server = createServer((req, res) => {
|
|
105
|
-
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
|
|
106
|
-
res.end(html);
|
|
107
|
-
});
|
|
108
|
-
server.listen(port, '127.0.0.1', () => console.log(`\n服务已启动:http://127.0.0.1:${port}/(Ctrl+C 结束)`));
|
|
109
|
-
return null; // 挂起,等待手动结束
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
|
113
|
-
const code = main();
|
|
114
|
-
if (code !== null) process.exitCode = code;
|
|
115
|
-
}
|
|
@@ -1,168 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 跨平台可移植性扫描器(独立工具,可对**任意仓库**跑)
|
|
3
|
-
*
|
|
4
|
-
* 定位:找出「只在 Linux/macOS 能跑」与「只在 Windows 能跑」的代码,并区分
|
|
5
|
-
* **代码**(会真炸)与**注释**(只是说明,降级为提示);同时统计已做平台分支的位置。
|
|
6
|
-
*
|
|
7
|
-
* 用法:
|
|
8
|
-
* node scripts/platform-scan.mjs <目标目录> [--json] [--strict] [--top N] [--ext .js,.mjs,.ts]
|
|
9
|
-
* --json 机器可读输出(file/line/rule/category/severity/snippet)
|
|
10
|
-
* --strict 发现「代码里的平台专属写法」时以退出码 1 结束(可用于 CI 门禁)
|
|
11
|
-
* --top N 文本输出里每类最多列几个文件(默认 8)
|
|
12
|
-
*
|
|
13
|
-
* 判据来源:把实测踩过的坑固化成规则 —— 例如 `process.env.PATH.split(':')`(Windows 用 ';',
|
|
14
|
-
* 会永远找不到可执行文件,却报成「找不到 git」这种看起来像环境问题的误导结论)、
|
|
15
|
-
* 硬编码 `/tmp`、`sh -c`、`C:\Windows` 断言、`cmd /c` 等。
|
|
16
|
-
*
|
|
17
|
-
* 说明:正则判据是「线索」不是「判决」——例如夹具字符串里的 `/tmp` 也会命中(本工具按
|
|
18
|
-
* 注释/代码分层给出提示,最终由人判断)。跨平台**正确**的写法(`os.tmpdir()`、`path.join`、
|
|
19
|
-
* `path.delimiter`、`process.platform` 分支)不会被判为问题,只计入「已平台分支」。
|
|
20
|
-
*/
|
|
21
|
-
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
22
|
-
import { dirname, extname, join, relative, resolve } from 'node:path';
|
|
23
|
-
import { fileURLToPath } from 'node:url';
|
|
24
|
-
|
|
25
|
-
import { tokenize } from '../lib/ast/tokenizer.js';
|
|
26
|
-
|
|
27
|
-
const SKIP_DIRS = new Set(['.git', 'node_modules', '.trash', '.codegraph', 'dist', 'build', '__pycache__', '.test-cache', '.archify']);
|
|
28
|
-
/** 报告里每条命中回显的最大字符数(避免超长行把报告撑爆)。 */
|
|
29
|
-
const SNIPPET_MAX = 120;
|
|
30
|
-
const DEFAULT_EXTS = ['.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.sh', '.ps1', '.bat', '.cmd', '.py'];
|
|
31
|
-
|
|
32
|
-
/** 规则表:id / 类别 / 严重级 / 判据 / 为什么。 */
|
|
33
|
-
const RULES = [
|
|
34
|
-
// ── 只在 POSIX(Linux/macOS)成立 ──
|
|
35
|
-
{ id: 'posix-tmp', category: 'posix-only', severity: 'warning', re: /['"`]\/tmp\//, why: "硬编码 /tmp:Windows 无此路径(应 os.tmpdir())" },
|
|
36
|
-
{ id: 'posix-devnull', category: 'posix-only', severity: 'warning', re: /['"`]\/dev\/null/, why: '硬编码 /dev/null:Windows 用 NUL' },
|
|
37
|
-
{ id: 'posix-shell', category: 'posix-only', severity: 'warning', re: /(\/bin\/(sh|bash)|\bsh\s+-c\b|\bbash\s+-c\b|#!\/bin\/(sh|bash)|(exec(File)?Sync|spawn(Sync)?)\(\s*['"](sh|bash|zsh|fish)['"])/, why: '依赖 POSIX shell:Windows 无 sh/bash(应走 execFile 数组参数)' },
|
|
38
|
-
{ id: 'posix-cmd', category: 'posix-only', severity: 'warning', re: /(exec(File)?Sync|spawn(Sync)?)\(\s*['"](chmod|chown|readlink|sed|awk|grep|which|stat|kill|df|du|uname)['"]/, why: '调用 POSIX 专有命令' },
|
|
39
|
-
{ id: 'path-split-colon', category: 'posix-only', severity: 'warning', re: /PATH[^\n]*\.split\(\s*['"]:['"]\s*\)|\.split\(\s*['"]:['"]\s*\)[^\n]*PATH/, why: "PATH 用 ':' 切分:Windows 是 ';'(应 path.delimiter)" },
|
|
40
|
-
{ id: 'posix-abs', category: 'posix-only', severity: 'notice', re: /['"`]\/(usr|etc|var|opt|bin|sbin|proc|sys)\//, why: '硬编码 POSIX 系统路径(Windows 无对应位置)' },
|
|
41
|
-
{ id: 'posix-symlink', category: 'posix-only', severity: 'notice', re: /\b(symlinkSync|symlink)\s*\(/, why: '符号链接:Windows 需特权/开发者模式(应提供降级)' },
|
|
42
|
-
{ id: 'posix-sudo', category: 'posix-only', severity: 'notice', re: /\bsudo\s+/, why: 'sudo:Windows 无此命令' },
|
|
43
|
-
{ id: 'posix-tilde-ssh', category: 'posix-only', severity: 'notice', re: /['"`]~\/\.ssh\//, why: '~/.ssh 字面量:Windows 家目录形式不同(应 os.homedir())' },
|
|
44
|
-
// ── 只在 Windows 成立 ──
|
|
45
|
-
{ id: 'win-drive', category: 'windows-only', severity: 'warning', re: /['"`][A-Za-z]:[\\/]/, why: '硬编码盘符路径:Linux/macOS 不存在(应 path.parse/os.homedir)' },
|
|
46
|
-
{ id: 'win-cmd', category: 'windows-only', severity: 'warning', re: /(cmd(\.exe)?\s+\/c\b|powershell(\.exe)?\b|\bstart\s+['"]{2}|(exec(File)?Sync|spawn(Sync)?)\(\s*['"](cmd|cmd\.exe|powershell|powershell\.exe)['"])/, why: '调用 Windows 专有 shell(cmd/powershell)' },
|
|
47
|
-
{ id: 'win-exe', category: 'windows-only', severity: 'notice', re: /['"][^'"\n]*\.(exe|bat|cmd)['"]/, why: '硬编码 .exe/.bat/.cmd:POSIX 上无扩展名(应探测候选名)' },
|
|
48
|
-
{ id: 'win-where', category: 'windows-only', severity: 'notice', re: /\b(where|tasklist|wmic|reg\s+query)\b\s+/, why: 'Windows 专有命令(POSIX 对应 which/ps)' },
|
|
49
|
-
{ id: 'win-env', category: 'windows-only', severity: 'notice', re: /%[A-Z_]+%/, why: '%VAR% 环境变量写法:仅 Windows cmd 展开' },
|
|
50
|
-
{ id: 'win-path32', category: 'windows-only', severity: 'notice', re: /path\.win32\b/, why: '显式使用 Windows 路径语义(若未做平台分支则在 POSIX 上错误)' },
|
|
51
|
-
// ── 已做平台分支(正确做法,仅统计) ──
|
|
52
|
-
{ id: 'platform-gated', category: 'gated', severity: 'info', re: /process\.platform\s*[!=]==?\s*['"](win32|linux|darwin)['"]|os\.platform\(\)|os\.tmpdir\(\)|path\.delimiter|path\.(join|resolve|sep)\b/, why: '已使用跨平台写法/平台分支' },
|
|
53
|
-
];
|
|
54
|
-
|
|
55
|
-
/** 递归收集待扫描文件(相对路径)。 */
|
|
56
|
-
function collectFiles(root, exts, dir = root, out = []) {
|
|
57
|
-
let entries = [];
|
|
58
|
-
try { entries = readdirSync(dir); } catch { return out; }
|
|
59
|
-
for (const name of entries) {
|
|
60
|
-
if (SKIP_DIRS.has(name)) continue;
|
|
61
|
-
const full = join(dir, name);
|
|
62
|
-
let st = null;
|
|
63
|
-
try { st = statSync(full); } catch { continue; }
|
|
64
|
-
if (st.isDirectory()) collectFiles(root, exts, full, out);
|
|
65
|
-
else if (exts.includes(extname(name))) out.push(relative(root, full).replace(/\\/g, '/'));
|
|
66
|
-
}
|
|
67
|
-
return out;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** 该行是否位于注释里(用 tokenizer 判定,避免把注释当代码)。 */
|
|
71
|
-
function commentLineSet(text) {
|
|
72
|
-
const set = new Set();
|
|
73
|
-
try {
|
|
74
|
-
for (const t of tokenize(text)) {
|
|
75
|
-
if (t.type === 'comment') for (let l = t.line; l <= t.line + (String(t.value).split('\n').length - 1); l++) set.add(l);
|
|
76
|
-
}
|
|
77
|
-
} catch { /* tokenize 失败就当没有注释信息 */ }
|
|
78
|
-
return set;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* 扫描一个仓库。
|
|
83
|
-
* @param {string} root 目标目录
|
|
84
|
-
* @param {{exts?:string[]}} [opts]
|
|
85
|
-
* @returns {{findings:Array, summary:object}}
|
|
86
|
-
*/
|
|
87
|
-
export function scanPlatformCode(root, { exts = DEFAULT_EXTS } = {}) {
|
|
88
|
-
const files = collectFiles(root, exts);
|
|
89
|
-
const findings = [];
|
|
90
|
-
for (const rel of files) {
|
|
91
|
-
let text = '';
|
|
92
|
-
try { text = readFileSync(join(root, rel), 'utf8'); } catch { continue; }
|
|
93
|
-
const comments = commentLineSet(text);
|
|
94
|
-
const lines = text.split('\n');
|
|
95
|
-
for (let i = 0; i < lines.length; i++) {
|
|
96
|
-
const line = lines[i];
|
|
97
|
-
if (line.length > 400) continue; // 压缩产物行:跳过(噪声)
|
|
98
|
-
for (const rule of RULES) {
|
|
99
|
-
if (!rule.re.test(line)) continue;
|
|
100
|
-
// 注释里的命中降级为 info(说明性文字,不是可执行代码)
|
|
101
|
-
const inComment = comments.has(i + 1);
|
|
102
|
-
const severity = rule.category === 'gated' ? 'info' : (inComment ? 'info' : rule.severity);
|
|
103
|
-
findings.push({
|
|
104
|
-
file: rel, line: i + 1, rule: rule.id, category: rule.category, severity,
|
|
105
|
-
inComment, why: rule.why, snippet: line.trim().slice(0, SNIPPET_MAX),
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
const byCategory = {};
|
|
111
|
-
for (const f of findings) byCategory[f.category] = (byCategory[f.category] || 0) + 1;
|
|
112
|
-
const actionable = findings.filter((f) => f.category !== 'gated' && !f.inComment && f.severity !== 'info');
|
|
113
|
-
const filesAffected = [...new Set(actionable.map((f) => f.file))];
|
|
114
|
-
return { root, files: files.length, findings, summary: { total: findings.length, byCategory, actionable: actionable.length, filesAffected: filesAffected.length } };
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/** 解析命令行参数。 */
|
|
118
|
-
function parseArgs(argv) {
|
|
119
|
-
const args = { exts: DEFAULT_EXTS, json: false, strict: false, top: 8 };
|
|
120
|
-
const positional = [];
|
|
121
|
-
for (let i = 0; i < argv.length; i++) {
|
|
122
|
-
const a = argv[i];
|
|
123
|
-
if (a === '--json') args.json = true;
|
|
124
|
-
else if (a === '--strict') args.strict = true;
|
|
125
|
-
else if (a === '--top') args.top = Number(argv[++i] || 8);
|
|
126
|
-
else if (a === '--ext') args.exts = String(argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
127
|
-
else if (a.startsWith('--')) throw new Error(`未知参数: ${a}`);
|
|
128
|
-
else positional.push(a);
|
|
129
|
-
}
|
|
130
|
-
args.root = positional[0];
|
|
131
|
-
return args;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/** 文本输出(按类别分组 + 每类文件 top)。 */
|
|
135
|
-
function printReport(result, top) {
|
|
136
|
-
const { summary, findings } = result;
|
|
137
|
-
console.log(`目标: ${result.root}(扫描 ${result.files} 个文件)`);
|
|
138
|
-
console.log(`命中 ${summary.total} 条|其中「代码里的平台专属写法」${summary.actionable} 条,涉及 ${summary.filesAffected} 个文件`);
|
|
139
|
-
console.log(`分类: ${JSON.stringify(summary.byCategory)}`);
|
|
140
|
-
for (const [cat, title] of [['posix-only', '只在 POSIX(Linux/macOS)成立'], ['windows-only', '只在 Windows 成立'], ['gated', '已做平台分支/跨平台写法(正面)']]) {
|
|
141
|
-
const rows = findings.filter((f) => f.category === cat);
|
|
142
|
-
if (!rows.length) continue;
|
|
143
|
-
console.log(`\n── ${title}:${rows.length} 条`);
|
|
144
|
-
const byFile = new Map();
|
|
145
|
-
for (const r of rows) byFile.set(r.file, (byFile.get(r.file) || 0) + 1);
|
|
146
|
-
for (const [file, n] of [...byFile.entries()].sort((a, b) => b[1] - a[1]).slice(0, top)) {
|
|
147
|
-
console.log(` ${file}(${n} 条)`);
|
|
148
|
-
for (const r of rows.filter((x) => x.file === file).slice(0, 3)) {
|
|
149
|
-
console.log(` :${r.line} [${r.rule}]${r.inComment ? '(注释)' : ''} ${r.snippet}`);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// ── CLI 入口 ──
|
|
156
|
-
// 注意:必须用 fileURLToPath(路径含中文/空格时 new URL().pathname 会变成 %XX 编码,比较恒不相等)
|
|
157
|
-
const isMain = process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));
|
|
158
|
-
if (isMain) {
|
|
159
|
-
const args = parseArgs(process.argv.slice(2));
|
|
160
|
-
if (!args.root) {
|
|
161
|
-
console.error('用法: node scripts/platform-scan.mjs <目标目录> [--json] [--strict] [--top N] [--ext .js,.mjs]');
|
|
162
|
-
process.exit(2);
|
|
163
|
-
}
|
|
164
|
-
const result = scanPlatformCode(resolve(args.root), { exts: args.exts });
|
|
165
|
-
if (args.json) console.log(JSON.stringify(result, null, 2));
|
|
166
|
-
else printReport(result, args.top);
|
|
167
|
-
process.exit(args.strict && result.summary.actionable > 0 ? 1 : 0);
|
|
168
|
-
}
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 探针:「重新检测」按钮链路实测(联网,需服务已启动)。
|
|
3
|
-
* 运行:node test/probe-recheck-live.mjs
|
|
4
|
-
*/
|
|
5
|
-
const BASE = process.env.DSH_PROBE_BASE || 'http://127.0.0.1:8090';
|
|
6
|
-
const ORIGIN = 'http://127.0.0.1:30801';
|
|
7
|
-
// 超时兜底:/account-check 内部要联网校验 token 与 SSH,服务端异常或网络悬挂时
|
|
8
|
-
// 无超时的 fetch 会**永久挂起**,探针既不报错也不退出(只能 Ctrl+C),
|
|
9
|
-
// 排查时看不到任何有用信息。60s 与 lib/git/api.js 的网络出口默认值一致。
|
|
10
|
-
const TIMEOUT_MS = 60_000;
|
|
11
|
-
const ACCOUNT_CHECK_PATH = '/api/git-push/account-check'; // 账号状态检测端点
|
|
12
|
-
const post = (p, b) => fetch(BASE + p, {
|
|
13
|
-
method: 'POST',
|
|
14
|
-
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
|
|
15
|
-
body: JSON.stringify(b),
|
|
16
|
-
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
17
|
-
}).then(r => r.json());
|
|
18
|
-
const get = (p) => fetch(BASE + p, {
|
|
19
|
-
headers: { Origin: ORIGIN },
|
|
20
|
-
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
21
|
-
}).then(r => r.json());
|
|
22
|
-
|
|
23
|
-
console.log('══ 「重新检测」按钮链路实测 ══\n');
|
|
24
|
-
|
|
25
|
-
console.log('① 按钮行为 POST /account-check(与 client.js recheckAccount 一致)');
|
|
26
|
-
const resp = await post(ACCOUNT_CHECK_PATH, { checkSsh: true, confirm: false });
|
|
27
|
-
const ts = resp.tokenStatus || {}, ss = resp.sshStatus || {};
|
|
28
|
-
const tv = ts.valid ? '✅ 有效' : (ts.timeout ? '⏳ 超时未测成(不是失效)' : '❌ 无效');
|
|
29
|
-
const sv = ss.valid ? '✅ 有效' : (ss.timeout ? '⏳ 超时未测成' : '❌ 无效');
|
|
30
|
-
console.log(' Token:', tv, ts.login ? `(${ts.login})` : '');
|
|
31
|
-
console.log(' SSH :', sv, ss.login ? `(${ss.login})` : '');
|
|
32
|
-
|
|
33
|
-
console.log('\n② 写回后读回(页面渲染依据)');
|
|
34
|
-
const s = await get('/api/git-push/account-status');
|
|
35
|
-
console.log(' ' + (s.block || '').split('\n').join('\n '));
|
|
36
|
-
console.log('\n 字段: tokenTimeout=' + s.tokenStatus?.timeout, '| sshTimeout=' + s.sshStatus?.timeout);
|
|
37
|
-
|
|
38
|
-
console.log('\n③ 防抖验证:连发两次(第二次应被前端忽略,后端仍应稳定)');
|
|
39
|
-
const [r1, r2] = await Promise.all([
|
|
40
|
-
post(ACCOUNT_CHECK_PATH, { checkSsh: false, confirm: false }),
|
|
41
|
-
post(ACCOUNT_CHECK_PATH, { checkSsh: false, confirm: false }),
|
|
42
|
-
]);
|
|
43
|
-
console.log(' 两次返回 tokenStatus.valid:', r1.tokenStatus?.valid, '/', r2.tokenStatus?.valid);
|
|
44
|
-
console.log(' (前端有 accountLoading 防抖,真实点击不会连发)');
|
|
45
|
-
|
|
46
|
-
console.log('\n══ 结论 ══');
|
|
47
|
-
console.log(ts.valid || ss.valid ? '✅ 按钮有效:在线校验成功并写回状态' : '⏳ 本次未测成(网络超时),状态已如实标注 timeout=true');
|
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* 变量重命名位置定位(按作用域聚合——对单字母变量人工重命名有帮助)
|
|
4
|
-
*
|
|
5
|
-
* 核心(对齐「按绑定聚合非按名字」方法论,零依赖 token 级近似):
|
|
6
|
-
* - 同名但不同作用域的变量语义不同,必须分开重命名——
|
|
7
|
-
* 本工具按 (作用域, 变量名) 聚合:声明点 + 该函数作用域内全部引用行
|
|
8
|
-
* - 作用域 = 函数区间(复用 lib/ast/scope.js collectFnLineRanges——近似 Babel scope.uid)
|
|
9
|
-
* - 遮蔽场景:内层函数区间与外层分开(不同函数 = 不同作用域组)
|
|
10
|
-
*
|
|
11
|
-
* 用法:
|
|
12
|
-
* node scripts/rename-locator.mjs <file> [--name x] [--all-len] [--json]
|
|
13
|
-
* --name x 只输出变量名 x 的分组(默认输出所有 <2 字符短变量)
|
|
14
|
-
* --all-len 输出所有长度变量(默认只 <2 单字符)
|
|
15
|
-
* --json JSON 输出(供脚本消费)
|
|
16
|
-
*
|
|
17
|
-
* 输出示例:
|
|
18
|
-
* x @ processUser:声明 L2 · 引用 L3 (一次改完这个函数内全部 x)
|
|
19
|
-
* x @ calculate:声明 L6 · 引用 L7 (另一个 x,独立一组)
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import { readFileSync } from 'node:fs';
|
|
23
|
-
import { basename } from 'node:path';
|
|
24
|
-
import { tokenize } from '../lib/ast/tokenizer.js';
|
|
25
|
-
import { collectFnLineRanges } from '../lib/ast/scope.js';
|
|
26
|
-
|
|
27
|
-
/** 所在函数名(行号 → 函数名;模块顶层 '(module)')。 */
|
|
28
|
-
function fnNameAtLine(src, line) {
|
|
29
|
-
const m = String(src).split('\n')[line - 1]?.match(/function\s+([A-Za-z_$][\w$]*)/);
|
|
30
|
-
return m ? m[1] : '(anonymous)';
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* 按作用域聚合短变量引用位置。
|
|
35
|
-
* @param {string} src 文件全文
|
|
36
|
-
* @param {object} [opts] { name?: string, minLen?: number(默认 2——<2 即单字符) }
|
|
37
|
-
* @returns {Array<{name:string, scopeName:string, declLine:number, refs:number[], count:number}>}
|
|
38
|
-
*/
|
|
39
|
-
export function locateVariables(src = '', opts = {}) {
|
|
40
|
-
const tokens = tokenize(src);
|
|
41
|
-
const fnRanges = collectFnLineRanges(src);
|
|
42
|
-
const scopeOf = (line) => {
|
|
43
|
-
for (const [s, e] of fnRanges) if (line >= s && line <= e) return fnNameAtLine(src, s);
|
|
44
|
-
return '(module)';
|
|
45
|
-
};
|
|
46
|
-
const minLen = opts.minLen ?? 2;
|
|
47
|
-
const groups = [];
|
|
48
|
-
const seen = new Set();
|
|
49
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
50
|
-
const t = tokens[i];
|
|
51
|
-
if (t.type !== 'ident' || !['const', 'let', 'var'].includes(t.value)) continue;
|
|
52
|
-
const nx = tokens[i + 1];
|
|
53
|
-
if (!(nx && nx.type === 'ident')) continue;
|
|
54
|
-
if (opts.name) {
|
|
55
|
-
if (nx.value !== opts.name) continue;
|
|
56
|
-
} else if (minLen > 0 && nx.value.length >= minLen) continue;
|
|
57
|
-
const scopeName = scopeOf(nx.line);
|
|
58
|
-
const key = `${nx.value}@${scopeName}`;
|
|
59
|
-
if (seen.has(key)) continue;
|
|
60
|
-
seen.add(key);
|
|
61
|
-
// 该作用域区间(函数范围或模块顶层)
|
|
62
|
-
const sRange = fnRanges.find(([s, e]) => nx.line >= s && nx.line <= e);
|
|
63
|
-
const refs = [];
|
|
64
|
-
for (let j = 0; j < tokens.length; j++) {
|
|
65
|
-
const tj = tokens[j];
|
|
66
|
-
if (tj.type !== 'ident' || tj.value !== nx.value) continue;
|
|
67
|
-
// 跳过声明关键字后的声明位(tokens[j-1] 是 const/let/var)
|
|
68
|
-
if (tokens[j - 1] && ['const', 'let', 'var'].includes(tokens[j - 1].value)) continue;
|
|
69
|
-
const inScope = sRange
|
|
70
|
-
? (tj.line >= sRange[0] && tj.line <= sRange[1])
|
|
71
|
-
: !fnRanges.some(([s, e]) => tj.line >= s && tj.line <= e);
|
|
72
|
-
if (inScope) refs.push(tj.line);
|
|
73
|
-
}
|
|
74
|
-
groups.push({ name: nx.value, scopeName, declLine: nx.line, refs: [...new Set(refs)].sort((a, b) => a - b), count: 1 + new Set(refs).size });
|
|
75
|
-
}
|
|
76
|
-
return groups.sort((a, b) => a.declLine - b.declLine);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function main() {
|
|
80
|
-
const argv = process.argv.slice(2);
|
|
81
|
-
const file = argv.find((a) => !a.startsWith('--'));
|
|
82
|
-
if (!file) { console.error('用法: node scripts/rename-locator.mjs <file> [--name x] [--all-len] [--json]'); process.exitCode = 1; return; }
|
|
83
|
-
const ni = argv.indexOf('--name'); const name = ni >= 0 ? argv[ni + 1] : undefined;
|
|
84
|
-
const allLen = argv.includes('--all-len');
|
|
85
|
-
const json = argv.includes('--json');
|
|
86
|
-
let src;
|
|
87
|
-
try { src = readFileSync(file, 'utf8'); } catch (e) { console.error(`读文件失败: ${e.message}`); process.exitCode = 1; return; }
|
|
88
|
-
const groups = locateVariables(src, name ? { name } : { minLen: allLen ? 0 : 2 });
|
|
89
|
-
if (json) { console.log(JSON.stringify({ file, groups }, null, 2)); return; }
|
|
90
|
-
if (!groups.length) { console.log(`${file}: 无${name ? `变量 ${name}` : '单字符短变量'}(按函数作用域分组)`); return; }
|
|
91
|
-
console.log(`${file} 变量重命名位置(按作用域分组——同名不同函数各自独立):`);
|
|
92
|
-
for (const g of groups) {
|
|
93
|
-
console.log(` ${g.name} @ ${g.scopeName}:声明 L${g.declLine} · 引用 ${g.refs.map((r) => `L${r}`).join(' ') || '(无)'}`);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
if (basename(process.argv[1] || '') === 'rename-locator.mjs') main(); // 入口判断:basename 精确(endsWith 会误匹配 test-rename-locator.mjs)
|
package/scripts/rule-switch.mjs
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 手动启停「安装版本」规则槽位。
|
|
3
|
-
*
|
|
4
|
-
* 与侧边栏 UI 的规则包启停完全同一套实现(lib/rule/loader.js setSlotDisabled:
|
|
5
|
-
* 修改规则 yml 顶层 `disabled: true` / 删除该行),只是以命令行方式直接调用,
|
|
6
|
-
* 不依赖 GUI。规则装载每次审计实时读 yml —— 改完**立即生效、无需重启实例**。
|
|
7
|
-
*
|
|
8
|
-
* 默认操作目标 = 部署安装副本(<DSH>/.dsh-home/.dsh/profiles/web/node_modules/dsh-git-push/
|
|
9
|
-
* lib/audit-rules),即 GUI 实际加载的规则;--target 可指向任意规则目录
|
|
10
|
-
* (如工作区 lib/audit-rules 用 --workspace)。强制槽位 nodejs/private 不可禁用
|
|
11
|
-
* (安全红线,setSlotDisabled 拦截,与 UI 行为一致)。
|
|
12
|
-
*
|
|
13
|
-
* 用法:
|
|
14
|
-
* node scripts/rule-switch.mjs list [--workspace|--target <规则目录>]
|
|
15
|
-
* node scripts/rule-switch.mjs status <slot> [--target <规则目录>]
|
|
16
|
-
* node scripts/rule-switch.mjs disable <slot> [--target <规则目录>]
|
|
17
|
-
* node scripts/rule-switch.mjs enable <slot> [--target <规则目录>]
|
|
18
|
-
*
|
|
19
|
-
* 示例:
|
|
20
|
-
* node scripts/rule-switch.mjs list # 列出安装版本全部槽位状态
|
|
21
|
-
* node scripts/rule-switch.mjs disable comment # 禁用安装版本的 comment 槽位
|
|
22
|
-
* node scripts/rule-switch.mjs enable comment # 重新启用
|
|
23
|
-
*/
|
|
24
|
-
import { readFileSync, readdirSync } from 'node:fs';
|
|
25
|
-
import { dirname, join, resolve } from 'node:path';
|
|
26
|
-
import { fileURLToPath } from 'node:url';
|
|
27
|
-
|
|
28
|
-
import { setSlotDisabled } from '../lib/rule/loader.js';
|
|
29
|
-
|
|
30
|
-
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
31
|
-
const PLUGIN_ROOT = resolve(HERE, '..');
|
|
32
|
-
// 工作区模式推导 DSH 根:<DSH>/.dsh-home/工作区/<项目> → 上溯三级
|
|
33
|
-
const DSH_ROOT = resolve(PLUGIN_ROOT, '..', '..', '..');
|
|
34
|
-
const DEPLOYED_RULES = join(DSH_ROOT, '.dsh-home', '.dsh', 'profiles', 'web', 'node_modules', 'dsh-git-push', 'lib', 'audit-rules');
|
|
35
|
-
|
|
36
|
-
/** 解析规则目录:--target 优先,--workspace 指工作区,缺省部署安装副本。 */
|
|
37
|
-
function resolveRulesDir(argv) {
|
|
38
|
-
const ti = argv.indexOf('--target');
|
|
39
|
-
if (ti >= 0 && argv[ti + 1]) return resolve(process.cwd(), argv[ti + 1]);
|
|
40
|
-
if (argv.includes('--workspace')) return join(PLUGIN_ROOT, 'lib', 'audit-rules');
|
|
41
|
-
return DEPLOYED_RULES;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/** 扫描目录内全部 audit-rules-<slot>.yml 槽位及状态。 */
|
|
45
|
-
function listSlots(dir) {
|
|
46
|
-
const slots = [];
|
|
47
|
-
for (const f of readdirSync(dir)) {
|
|
48
|
-
const match = f.match(/^audit-rules-(.+)\.yml$/);
|
|
49
|
-
if (!match) continue;
|
|
50
|
-
const text = readFileSync(join(dir, f), 'utf8');
|
|
51
|
-
const disabled = /^disabled:\s*true\s*$/m.test(text);
|
|
52
|
-
slots.push({ slot: match[1], file: f, disabled });
|
|
53
|
-
}
|
|
54
|
-
return slots.sort((a, b) => a.slot.localeCompare(b.slot));
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function main(argv = process.argv.slice(2)) {
|
|
58
|
-
const cmd = argv[0] || 'list';
|
|
59
|
-
const dir = resolveRulesDir(argv);
|
|
60
|
-
console.log(`规则目录:${dir}`);
|
|
61
|
-
if (!readdirSync(dir).some((f) => f.startsWith('audit-rules-') && f.endsWith('.yml'))) { // dsh-skip-residue(规则目录条目少,一次性判定)
|
|
62
|
-
console.error(`❌ 目录无规则文件(audit-rules-*.yml):${dir}`);
|
|
63
|
-
process.exit(1);
|
|
64
|
-
}
|
|
65
|
-
if (cmd === 'list') {
|
|
66
|
-
const slots = listSlots(dir);
|
|
67
|
-
for (const { slot, disabled } of slots) {
|
|
68
|
-
console.log(` ${disabled ? '✖ 禁用' : '✔ 启用'} ${slot}`);
|
|
69
|
-
}
|
|
70
|
-
console.log(`共 ${slots.length} 个槽位(改完立即生效,无需重启;强制槽位 nodejs/private 不可禁用)`);
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
if (cmd === 'status') {
|
|
74
|
-
const slot = argv[1];
|
|
75
|
-
if (!slot) { console.error('用法: status <槽位>'); process.exit(1); }
|
|
76
|
-
const found = listSlots(dir).find((s) => s.slot === slot);
|
|
77
|
-
if (!found) { console.error(`❌ 槽位不存在: ${slot}`); process.exit(1); }
|
|
78
|
-
console.log(` ${found.disabled ? '✖ 禁用' : '✔ 启用'} ${slot}`);
|
|
79
|
-
return;
|
|
80
|
-
}
|
|
81
|
-
if (cmd === 'disable' || cmd === 'enable') {
|
|
82
|
-
const slot = argv[1];
|
|
83
|
-
if (!slot) { console.error(`用法: ${cmd} <槽位>`); process.exit(1); }
|
|
84
|
-
const wantDisabled = cmd === 'disable';
|
|
85
|
-
const outcome = setSlotDisabled(slot, wantDisabled, { dir });
|
|
86
|
-
if (!outcome.ok) {
|
|
87
|
-
console.error(`❌ ${outcome.error}`);
|
|
88
|
-
process.exit(1);
|
|
89
|
-
}
|
|
90
|
-
console.log(`✅ ${slot} 已${wantDisabled ? '禁用' : '启用'}(写入 ${dir}/audit-rules-${slot}.yml 顶层 disabled,审计实时生效、无需重启)`);
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
console.error(`未知命令: ${cmd}(支持 list / status <槽位> / disable <槽位> / enable <槽位>)`);
|
|
94
|
-
process.exit(1);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
main();
|