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/lib/checks/structural.js
DELETED
|
@@ -1,281 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 检查层 · 结构类规则
|
|
3
|
-
*
|
|
4
|
-
* 职责:函数长度、复杂度、嵌套深度、文件行数、重复字符串、同步 fs、空 catch。
|
|
5
|
-
* 本层为薄包装:判定逻辑在 lib/ast/*,此处只把结果转成 finding。
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { makeFinding } from '../audit/index.js';
|
|
9
|
-
import { checkSyncFs, checkEmptyCatchAst, checkFuncLinesAst, checkFuncDensityAst, checkNameLengthAst, checkComplexityAst, checkNestingDepthAst, checkFileLines, checkRepeatedStringsAst, checkCommentDensityAst, maxFunctionLength } from '../ast/index.js';
|
|
10
|
-
import { classifyFunctionPath, analyzeFunctionalScope } from '../ast/scope.js';
|
|
11
|
-
|
|
12
|
-
/* ───────── 结构检查默认阈值 ───────── */
|
|
13
|
-
// FUNC_LINES_DEFAULT 改为从 lib/audit-defaults.js 取单一来源(此前与 lib/rule/compilers/func.js
|
|
14
|
-
// 各写一份 50,两处必须永远相等,漏改一处就静默不一致——自审 duplicate-constant 报的真重复)
|
|
15
|
-
import { FUNC_LINES_DEFAULT } from '../audit-defaults.js';
|
|
16
|
-
const MAX_LINES_DEFAULT = 500; // 规则未配 threshold 时的文件行数默认阈值
|
|
17
|
-
import { resolveScopeAction } from '../rule/scope.js';
|
|
18
|
-
import { capSeverity, HINT_QUALITY } from './common.js';
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
/** 检查 func-lines:单函数超长(AST 精确行数 + 语句密度互补,单行海量语句也检出)。 */
|
|
22
|
-
export function checkFuncLines({ file, text, rules }) {
|
|
23
|
-
const findings = [];
|
|
24
|
-
const rule = rules?.[0];
|
|
25
|
-
if (!rule) return findings;
|
|
26
|
-
const threshold = rule.threshold || FUNC_LINES_DEFAULT;
|
|
27
|
-
const blockThreshold = rule.blockThreshold || threshold * 2;
|
|
28
|
-
// AST 版:括号平衡精确统计函数体行数(修行数启发式假阴性)
|
|
29
|
-
const astHits = checkFuncLinesAst(text, { warn: threshold, block: blockThreshold });
|
|
30
|
-
const fnScope = rule.scopeRules?.length ? analyzeFunctionalScope(text) : new Map(); // P4:闭包双重作用域(public 不豁免)
|
|
31
|
-
for (const hit of astHits) {
|
|
32
|
-
// 作用域豁免(P1):规则声明 scope_rules 且函数为启动路径(apply/init/main 等)→ exempt;P4:public(被 return/挂 this/exports 暴露)按模块级不豁免
|
|
33
|
-
if (rule.scopeRules?.length && fnScope.get(hit.name) !== 'public' && resolveScopeAction(rule.scopeRules, { path: classifyFunctionPath(hit.name), functionName: hit.name }) === 'exempt') continue;
|
|
34
|
-
findings.push(makeFinding({
|
|
35
|
-
file, line: hit.line, rule: rule.id, kind: 'func-lines',
|
|
36
|
-
severity: hit.level === 'blocker' || rule.level === 'blocker' ? 'blocker' : 'warning',
|
|
37
|
-
// 长度按非注释部分(hit.codeLen);与总行数不同时才附注释行说明
|
|
38
|
-
message: (hit.commentLines > 0
|
|
39
|
-
? `单函数 ${hit.codeLen} 行代码(总 ${hit.len} 行,其中注释 ${hit.commentLines} 行,阈值 ${threshold})——应拆分`
|
|
40
|
-
: `单函数 ${hit.codeLen} 行(阈值 ${threshold})——应拆分`),
|
|
41
|
-
dimensions: rule.dimensions,
|
|
42
|
-
exemptHint: 'dsh-skip-func-length(文件头=全文件 / 函数定义行=单函数)',
|
|
43
|
-
scoreImpact: hit.level === 'blocker' ? 2 : 1,
|
|
44
|
-
}));
|
|
45
|
-
}
|
|
46
|
-
// 语句密度补充(架构收敛):**判定全部在 AST 层**(checkFuncDensityAst),
|
|
47
|
-
// 本层只把结果转成 finding,不再自己找函数起点、自己数花括号、自己判行数。
|
|
48
|
-
// 历史违规:此处曾是第二套独立实现(正则找起点 + 手数括号 + 自判行数),与 AST 版各判各的,
|
|
49
|
-
// 既重复报同一函数,又因未剥离字面量把含 `\{` 正则的函数算成 242 行 blocker。
|
|
50
|
-
// 跳过条件:已被行数判定报出的函数(reportedByLines)不再按密度重复报。
|
|
51
|
-
const reportedByLines = new Set(astHits.map((h) => h.line));
|
|
52
|
-
const densityHits = checkFuncDensityAst(text, {
|
|
53
|
-
threshold, blockThreshold, skipLines: reportedByLines,
|
|
54
|
-
});
|
|
55
|
-
for (const d of densityHits) {
|
|
56
|
-
findings.push(makeFinding({
|
|
57
|
-
file, line: d.line, rule: rule.id, kind: 'func-lines',
|
|
58
|
-
severity: d.level === 'blocker' || rule.level === 'blocker' ? 'blocker' : 'warning',
|
|
59
|
-
message: `单函数 ${d.stmtCount} 语句挤在 ${d.bodyLines} 行(平均 ${d.density.toFixed(1)} 条/行,阈值 ${threshold} 条)——单行海量语句应拆分`,
|
|
60
|
-
dimensions: rule.dimensions,
|
|
61
|
-
exemptHint: 'dsh-skip-func-length(文件头=全文件 / 函数定义行=单函数)',
|
|
62
|
-
scoreImpact: d.level === 'blocker' ? 2 : 1,
|
|
63
|
-
}));
|
|
64
|
-
}
|
|
65
|
-
return findings;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** 检查 sync-fs:async 路径中的 fs 同步调用(AST 级,修 named import 假阴性)。 */
|
|
69
|
-
export function checkSyncFsInFile({ file, text }) {
|
|
70
|
-
const findings = [];
|
|
71
|
-
for (const hit of checkSyncFs(text)) {
|
|
72
|
-
findings.push(makeFinding({
|
|
73
|
-
file, line: hit.line, rule: 'quality/sync-fs', kind: 'sync-fs',
|
|
74
|
-
severity: 'warning',
|
|
75
|
-
message: `async 路径中的同步 fs 调用 ${hit.call}(${hit.via})——阻塞事件循环,应换异步版`,
|
|
76
|
-
dimensions: ['性能'],
|
|
77
|
-
exemptHint: HINT_QUALITY,
|
|
78
|
-
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
79
|
-
}));
|
|
80
|
-
}
|
|
81
|
-
return findings;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/** 检查空 catch(AST 级括号平衡:多行空块/仅注释块均命中)。 */
|
|
85
|
-
export function checkEmptyCatch({ file, text }) {
|
|
86
|
-
const findings = [];
|
|
87
|
-
for (const hit of checkEmptyCatchAst(text)) {
|
|
88
|
-
findings.push(makeFinding({
|
|
89
|
-
file, line: hit.line, rule: 'quality/empty-catch', kind: 'empty-catch',
|
|
90
|
-
severity: 'warning',
|
|
91
|
-
message: '空 catch 静默吞错——应加 log 或注释原因',
|
|
92
|
-
dimensions: ['健壮性', '可观测性'],
|
|
93
|
-
exemptHint: HINT_QUALITY,
|
|
94
|
-
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
95
|
-
}));
|
|
96
|
-
}
|
|
97
|
-
return findings;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** 检查命名长度(min-length)。 */
|
|
101
|
-
export function checkMinLength({ file, text, rules }) {
|
|
102
|
-
const findings = [];
|
|
103
|
-
const rule = (rules || [])[0];
|
|
104
|
-
// 空规则短路(修复):filterRulesByExt 裁剪后 min-length 可能是**空数组**
|
|
105
|
-
// (truthy)——如 JS 文件只剩 exts=[java,kt]/[py] 的 java/python 规则时数组被裁空,
|
|
106
|
-
// 但 dispatch 的 `if (grouped['min-length'])` 对空数组仍真 → 本检查器拿空 rules 照跑
|
|
107
|
-
// (threshold 默认 2)→ 对当前文件报「裸 min-length 短名」(rule.id 空 → fallback),
|
|
108
|
-
// Pawchive test/tools 实测 27 条全为此根因。与 checkComplexity/checkMaxLines 同短路。
|
|
109
|
-
if (!rule) return findings;
|
|
110
|
-
const threshold = rule?.threshold || 2;
|
|
111
|
-
for (const hit of checkNameLengthAst(text, { min: threshold })) {
|
|
112
|
-
findings.push(makeFinding({
|
|
113
|
-
file, line: hit.line, rule: rule?.id || 'min-length', kind: 'min-length',
|
|
114
|
-
severity: 'warning',
|
|
115
|
-
message: `${hit.type === 'function' ? '函数' : '变量'}名「${hit.name}」过短(< ${threshold})——应可读命名`,
|
|
116
|
-
dimensions: rule?.dimensions || ['可读性'],
|
|
117
|
-
exemptHint: HINT_QUALITY,
|
|
118
|
-
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
119
|
-
}));
|
|
120
|
-
}
|
|
121
|
-
return findings;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** 检查圈复杂度(max-complexity)。 */
|
|
125
|
-
export function checkComplexity({ file, text, rules }) {
|
|
126
|
-
const findings = [];
|
|
127
|
-
const rule = (rules || [])[0];
|
|
128
|
-
if (!rule) return findings; // 规则被 exts/exclude_paths 过滤为空时短路(防 rule.severity 崩溃)
|
|
129
|
-
const threshold = rule?.threshold || 10;
|
|
130
|
-
// blocker 阈值:yml 可配 block_complexity(如 50),缺省 = threshold*2
|
|
131
|
-
const blockThreshold = rule?.block || threshold * 2;
|
|
132
|
-
const fnScope2 = rule.scopeRules?.length ? analyzeFunctionalScope(text) : new Map(); // P4
|
|
133
|
-
for (const hit of checkComplexityAst(text, { warn: threshold, block: blockThreshold })) {
|
|
134
|
-
// 作用域豁免(P1):启动路径函数豁免圈复杂度;P4:public 不豁免
|
|
135
|
-
if (rule.scopeRules?.length && fnScope2.get(hit.name) !== 'public' && resolveScopeAction(rule.scopeRules, { path: classifyFunctionPath(hit.name), functionName: hit.name }) === 'exempt') continue;
|
|
136
|
-
// 分档提示(按复杂度区间):11~20 中等 / 21~50 高风险应拆分 / 50+ 极难维护(拦)
|
|
137
|
-
const grade = hit.complexity > blockThreshold
|
|
138
|
-
? '极难维护(几乎不可测)'
|
|
139
|
-
: (hit.complexity > 20 ? '高风险' : '中等(开始难测)');
|
|
140
|
-
findings.push(makeFinding({
|
|
141
|
-
file, line: hit.line, rule: rule?.id || 'max-complexity', kind: 'max-complexity',
|
|
142
|
-
severity: capSeverity(rule.severity, hit.level),
|
|
143
|
-
message: `函数 ${hit.name} 圈复杂度 ${hit.complexity}(阈值 ${threshold},${grade})`
|
|
144
|
-
+ (hit.level === 'blocker' ? '——极难维护,应拆分(拦提交)' : '——应拆分'),
|
|
145
|
-
dimensions: rule?.dimensions || ['可维护性'],
|
|
146
|
-
exemptHint: HINT_QUALITY,
|
|
147
|
-
scoreImpact: hit.level === 'blocker' ? 2 : 1,
|
|
148
|
-
}));
|
|
149
|
-
}
|
|
150
|
-
return findings;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
/** 检查嵌套深度(max-depth)。 */
|
|
154
|
-
export function checkDepth({ file, text, rules }) {
|
|
155
|
-
const findings = [];
|
|
156
|
-
const rule = (rules || [])[0];
|
|
157
|
-
if (!rule) return findings; // 规则被 exts/exclude_paths 过滤为空时短路(防 rule.severity 崩溃)
|
|
158
|
-
const threshold = rule?.threshold || 4;
|
|
159
|
-
for (const hit of checkNestingDepthAst(text, { warn: threshold, block: threshold + 2 })) {
|
|
160
|
-
findings.push(makeFinding({
|
|
161
|
-
file, line: hit.line, rule: rule?.id || 'max-depth', kind: 'max-depth',
|
|
162
|
-
severity: capSeverity(rule.severity, hit.level),
|
|
163
|
-
message: `嵌套深度 ${hit.depth}(阈值 ${threshold})——应提取早返回`,
|
|
164
|
-
dimensions: rule?.dimensions || ['可读性'],
|
|
165
|
-
exemptHint: HINT_QUALITY,
|
|
166
|
-
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
167
|
-
}));
|
|
168
|
-
}
|
|
169
|
-
return findings;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/** 检查文件行数(max-lines)。fileScope 由调度层按仓库事实推导(见 lib/checks/dispatch.js 的 resolveFileScope)。 */
|
|
173
|
-
export function checkMaxLines({ file, text, rules, fileScope = '' }) {
|
|
174
|
-
const rule = (rules || [])[0];
|
|
175
|
-
if (!rule) return []; // 规则被 exts/exclude_paths 过滤为空时短路(防 rule.severity 崩溃)
|
|
176
|
-
const threshold = rule?.threshold || MAX_LINES_DEFAULT;
|
|
177
|
-
const { lines, codeLines, commentLines, level } = checkFileLines(text, { warn: threshold, block: threshold * 2 });
|
|
178
|
-
if (!level) return [];
|
|
179
|
-
// 作用域优先(**声明驱动**):规则 yml 的 scope_rules 命中本文件作用域时按 action 处理。
|
|
180
|
-
// exempt → 跳过(不出现在报告);downgrade → 降为提示(仍报、不扣分)。
|
|
181
|
-
const action = resolveScopeAction(rule.scopeRules, { fileScope });
|
|
182
|
-
if (action === 'exempt') return [];
|
|
183
|
-
// 平台约束优先:DSH 客户端单文件(不可拆分)→ 降级为提示(仍报、不扣分)
|
|
184
|
-
if (action === 'downgrade') {
|
|
185
|
-
return [makeFinding({
|
|
186
|
-
file, line: 1, rule: rule?.id || 'max-lines', kind: 'max-lines',
|
|
187
|
-
severity: 'info',
|
|
188
|
-
message: `文件 ${codeLines} 行代码(总 ${lines} 行,其中注释 ${commentLines} 行,阈值 ${threshold})——`
|
|
189
|
-
+ 'DSH 要求客户端为**单文件**(dsh.client / exports["./client"] 指向同一文件),不可按模块拆分,故降级为提示',
|
|
190
|
-
dimensions: rule?.dimensions || ['可维护性'],
|
|
191
|
-
exemptHint: 'dsh-skip-size(文件头,文件级属性)',
|
|
192
|
-
scoreImpact: 0,
|
|
193
|
-
})];
|
|
194
|
-
}
|
|
195
|
-
// 聚合型 vs 臃肿型(用户设计):先罚函数再考虑文件——函数是执行单元、
|
|
196
|
-
// 文件是组织单元。文件超行数但最大函数 ≤ 50 行(聚合型:函数都合规,文件大只是
|
|
197
|
-
// 函数多/数据多)→ 降级 info(提示不扣分);文件超行数且存在 > 50 行函数(臃肿型:
|
|
198
|
-
// 文件大是因为藏着大函数)→ 保持 warning/blocker(先拆函数再拆文件)。
|
|
199
|
-
const maxFuncLen = maxFunctionLength(text);
|
|
200
|
-
const FUNC_COMPLIANT_LIMIT = 50;
|
|
201
|
-
// 聚合型需「有函数且都合规」:无函数的纯脚本/数据文件(顶层语句堆叠)没有「函数多」
|
|
202
|
-
// 作证据,不豁免(保持 warning——脚本型大文件同样是拆模块债务)。
|
|
203
|
-
if (maxFuncLen > 0 && maxFuncLen <= FUNC_COMPLIANT_LIMIT) {
|
|
204
|
-
return [makeFinding({
|
|
205
|
-
file, line: 1, rule: rule?.id || 'max-lines', kind: 'max-lines',
|
|
206
|
-
severity: 'info',
|
|
207
|
-
message: `文件 ${codeLines} 行代码(总 ${lines} 行,其中注释 ${commentLines} 行,阈值 ${threshold})——`
|
|
208
|
-
+ `最大函数仅 ${maxFuncLen} 行,函数都合规,属聚合型(函数多而非函数长),文件边界只是导航成本,可接受`,
|
|
209
|
-
dimensions: rule?.dimensions || ['可维护性'],
|
|
210
|
-
exemptHint: 'dsh-skip-size(文件头,文件级属性)',
|
|
211
|
-
scoreImpact: 0,
|
|
212
|
-
})];
|
|
213
|
-
}
|
|
214
|
-
// 分两种「非聚合型」情形,文案必须各说各的事实:
|
|
215
|
-
// · 有超大函数 → 臃肿型(先拆函数)
|
|
216
|
-
// · 一个函数都没有(顶层语句堆叠的脚本/数据文件)→ 不能说「藏着超大函数」
|
|
217
|
-
// (此前统一套「最大函数 0 行(臃肿型:文件大因藏着超大函数)」——0 行显然不是超大函数,
|
|
218
|
-
// 文案自相矛盾;外部项目实测反馈即指向这句)
|
|
219
|
-
const headline = maxFuncLen > 0
|
|
220
|
-
? `最大函数 ${maxFuncLen} 行(臃肿型:文件大是因藏着超大函数),应先拆函数再考虑拆文件`
|
|
221
|
-
: '文件内未识别到函数(顶层语句堆叠的脚本/数据形态),应拆分为模块';
|
|
222
|
-
return [makeFinding({
|
|
223
|
-
file, line: 1, rule: rule?.id || 'max-lines', kind: 'max-lines',
|
|
224
|
-
severity: capSeverity(rule.severity, level),
|
|
225
|
-
// 判定按非注释部分(codeLines);总行数/注释行数一并展示便于判断拆分空间
|
|
226
|
-
message: `文件 ${codeLines} 行代码(总 ${lines} 行,其中注释 ${commentLines} 行,阈值 ${threshold})——${headline}`,
|
|
227
|
-
dimensions: rule?.dimensions || ['可维护性'],
|
|
228
|
-
exemptHint: 'dsh-skip-size(文件头,文件级属性)',
|
|
229
|
-
scoreImpact: level === 'blocker' ? 2 : 1,
|
|
230
|
-
})];
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
/** 检查注释冗余密度(comment-density,,评审规则①)。
|
|
234
|
-
* 变量即注释——语义明确的代码里变量名已表达内容,额外的行注释不加深理解;
|
|
235
|
-
* 应只保留隐性约束/复杂设计/外部契约/非显然决策的**块注释**,减少行注释。
|
|
236
|
-
* 判定:行注释行数 ÷ 有效代码行数 > 阈值(规则 threshold 或默认 0.4)→ 提示。
|
|
237
|
-
* 块注释(斜杠星号、JSDoc、docstring)不计入(设计说明保留);只 warning 不拦截。
|
|
238
|
-
*/
|
|
239
|
-
export function checkCommentDensity({ file, text, rules }) {
|
|
240
|
-
const rule = (rules || [])[0];
|
|
241
|
-
if (!rule) return [];
|
|
242
|
-
const threshold = rule?.threshold != null ? rule.threshold : 0.4;
|
|
243
|
-
const hits = checkCommentDensityAst(text, { warn: threshold });
|
|
244
|
-
if (!hits.length) return [];
|
|
245
|
-
const h = hits[0];
|
|
246
|
-
return [makeFinding({
|
|
247
|
-
file, line: 1, rule: rule?.id || 'comment-density', kind: 'comment-density',
|
|
248
|
-
severity: capSeverity(rule.severity, 'warning'),
|
|
249
|
-
message: `行注释 ${h.commentLines} 行 ÷ 代码 ${h.codeLines} 行 = ${(h.ratio * 100).toFixed(0)}%(阈值 ${Math.round(threshold * 100)}%)——语义明确的代码变量即注释,行注释过多可能复述代码;只保留解释「为什么」的块注释`,
|
|
250
|
-
dimensions: rule?.dimensions || ['可读性'],
|
|
251
|
-
exemptHint: 'dsh-skip-quality(文件头=整文件)',
|
|
252
|
-
scoreImpact: 1,
|
|
253
|
-
})];
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/** 检查重复硬编码串/数值(repeated-string / min-occurrences,两 kind 合并去重,)。 */
|
|
257
|
-
export function checkRepeated({ file, text, rules }) {
|
|
258
|
-
const findings = [];
|
|
259
|
-
// 多个规则(repeated-string + min-occurrences)合并传入时:
|
|
260
|
-
// · 阈值取最小(任一规则达到即报,不放过)
|
|
261
|
-
// · ignore 集合并
|
|
262
|
-
// · 同一文本只报一条(取第一条命中规则的 id)——修「同一文本被两个 kind 双报」
|
|
263
|
-
const thresholds = (rules || []).map((r) => Number(r.threshold) || 3);
|
|
264
|
-
const threshold = thresholds.length ? Math.min(...thresholds) : 3;
|
|
265
|
-
const ignore = [...new Set((rules || []).flatMap((r) => r.ignoreValues || []))];
|
|
266
|
-
const seen = new Set();
|
|
267
|
-
for (const hit of checkRepeatedStringsAst(text, { min: threshold, ignore })) {
|
|
268
|
-
if (seen.has(hit.value)) continue; // 同文本只报一次
|
|
269
|
-
seen.add(hit.value);
|
|
270
|
-
const rule = (rules || []).find((r) => Number(r.threshold || 3) <= hit.count) || (rules || [])[0];
|
|
271
|
-
findings.push(makeFinding({
|
|
272
|
-
file, line: hit.line, rule: rule?.id || 'repeated-string', kind: rule?.kind || 'repeated-string',
|
|
273
|
-
severity: 'warning',
|
|
274
|
-
message: `硬编码文本「${hit.value}」重复 ${hit.count} 次(阈值 ${threshold})——应配置化`,
|
|
275
|
-
dimensions: rule?.dimensions || ['可维护性'],
|
|
276
|
-
exemptHint: HINT_QUALITY,
|
|
277
|
-
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
278
|
-
}));
|
|
279
|
-
}
|
|
280
|
-
return findings;
|
|
281
|
-
}
|
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* CLI 命令 · 审计域(audit/scan + 插件配置对齐工具)(从 cli.mjs 抽出)
|
|
3
|
-
*
|
|
4
|
-
* 为什么拆出来:cli.mjs 578 行代码超单文件阈值(400),审计命令族 + 配置对齐工具
|
|
5
|
-
* (cliPluginConfig / pluginEqualAuditOpts / pluginEqualWeights / pathExists)是
|
|
6
|
-
* 「与插件 code_audit 结果一致」的独立能力域,被 cmdAudit/cmdScan/cmdCommit 共享。
|
|
7
|
-
*
|
|
8
|
-
* 保持薄引用:审计逻辑在 lib/audit/*(与插件 code_audit 同源)。
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import { cliPluginConfig } from './shared.mjs';
|
|
12
|
-
import { auditWithScope, auditFull } from '../audit/index.js';
|
|
13
|
-
import { formatAnalysisCoverageLine } from '../audit/analysis-coverage.js';
|
|
14
|
-
import { scoreQuality } from '../score/index.js';
|
|
15
|
-
import { access } from 'node:fs/promises';
|
|
16
|
-
import { join } from 'node:path';
|
|
17
|
-
import { probeRepoOwnership } from '../app/repo-ownership.js';
|
|
18
|
-
|
|
19
|
-
/** 审计 full 扫描 findings 打印条数上限(防刷屏)。 */
|
|
20
|
-
const AUDIT_PRINT_LIMIT = 20;
|
|
21
|
-
|
|
22
|
-
// cliPluginConfig 已挪到 lib/cli/shared.mjs(三入口共用;git 侧读配置不必 import 审计实现)。
|
|
23
|
-
// 这里保留同名导出,外部按老路径 import 不受影响。
|
|
24
|
-
export { cliPluginConfig };
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* 构造与插件 code_audit **完全相同**的审计参数(保证 CLI 与插件结果一致)。
|
|
28
|
-
* 对齐点:auditLevel、maxScanFiles、规则包顺序 slots、禁用槽位 disabledSlots、
|
|
29
|
-
* includeIgnored、rulesetDir、权重(weightOverrides)。CLI 显式传参优先于配置。
|
|
30
|
-
*/
|
|
31
|
-
export function pluginEqualAuditOpts(cfg, flags, { scope = 'diff' } = {}) {
|
|
32
|
-
const rulesetDir = flags.ruleset || '';
|
|
33
|
-
return {
|
|
34
|
-
scope,
|
|
35
|
-
rulesetDir,
|
|
36
|
-
maxScanFiles: cfg.maxScanFiles,
|
|
37
|
-
slots: cfg.auditRuleOrder && cfg.auditRuleOrder.length ? cfg.auditRuleOrder : undefined,
|
|
38
|
-
disabledSlots: Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [],
|
|
39
|
-
includeIgnored: flags.includeIgnored === true,
|
|
40
|
-
// 分析覆盖率信息项(与插件 code_audit 同口径,由审计编排层计算;见 lib/audit/orchestrate.js)
|
|
41
|
-
coverage: flags.coverage !== false,
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** CLI 审计权重:显式 --weights > 插件配置 weightOverrides > 默认权重表(与 code_audit 同序)。 */
|
|
46
|
-
export function pluginEqualWeights(cfg, flags) {
|
|
47
|
-
const src = flags.weights || (typeof cfg.weightOverrides === 'string' ? cfg.weightOverrides : '');
|
|
48
|
-
if (!src) return {};
|
|
49
|
-
try { return JSON.parse(src); } catch { return {}; }
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** 路径是否存在(异步,避免在 async 命令里做同步 I/O)。 */
|
|
53
|
-
async function pathExists(p) {
|
|
54
|
-
try { await access(p); return true; } catch { return false; }
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** 子命令:audit — 审计目录(**与插件 code_audit 结果一致**)。 */
|
|
58
|
-
export async function cmdAudit(root, flags) {
|
|
59
|
-
// 拆分:history 模式与 standard 模式各自独立函数(圈复杂度 18→各 <10)
|
|
60
|
-
if (flags.history === true) return runHistoryAuditCmd(root, flags);
|
|
61
|
-
return runStandardAudit(root, flags);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** history 模式:历史提交审计(逐提交快照全量审计 + 落盘报告)。 */
|
|
65
|
-
async function runHistoryAuditCmd(root, flags) {
|
|
66
|
-
const cfg = cliPluginConfig();
|
|
67
|
-
const { runHistoryAudit } = await import('../audit/history.js');
|
|
68
|
-
const opts = pluginEqualAuditOpts(cfg, flags, { scope: 'full' });
|
|
69
|
-
opts.ownership = probeRepoOwnership(root); // 与插件工具同参:隐私规则只对自有仓库生效
|
|
70
|
-
const weights = pluginEqualWeights(cfg, flags);
|
|
71
|
-
const r = await runHistoryAudit(root || '.', {
|
|
72
|
-
since: flags.since, until: flags.until, outDir: flags.out,
|
|
73
|
-
auditOpts: opts, weights,
|
|
74
|
-
onCommit: (p) => { if (!flags.json) console.log(` [${p.index}/${p.total}] ${p.short} ${p.ok ? '✓' : '✗ ' + (p.error || '')}`); },
|
|
75
|
-
});
|
|
76
|
-
if (!r.ok) { console.error(`❌ ${r.error || '历史审计失败'}`); return 1; }
|
|
77
|
-
if (flags.json) { console.log(JSON.stringify(r, null, 2)); return 0; }
|
|
78
|
-
console.log(`历史审计完成:${r.total} 个提交(处理 ${r.processed},失败 ${r.failed}${r.aborted ? ',已中断' : ''})`);
|
|
79
|
-
console.log(`报告目录:${r.reportDir}`);
|
|
80
|
-
return 0;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/** standard 模式:full/diff 审计 + 评分 + 结果输出。 */
|
|
84
|
-
async function runStandardAudit(root, flags) {
|
|
85
|
-
const cfg = cliPluginConfig();
|
|
86
|
-
const full = flags.full === true || !(await pathExists(join(root || '.', '.git')));
|
|
87
|
-
const opts = pluginEqualAuditOpts(cfg, flags, { scope: full ? 'full' : 'diff' });
|
|
88
|
-
opts.ownership = probeRepoOwnership(root); // 与插件工具同参:隐私规则只对自有仓库生效
|
|
89
|
-
const weights = pluginEqualWeights(cfg, flags);
|
|
90
|
-
const auditResult = full ? await auditFull(root, opts) : await auditWithScope(root, opts);
|
|
91
|
-
const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts, dimRuleCounts: auditResult.dimRuleCounts });
|
|
92
|
-
if (flags.json) {
|
|
93
|
-
console.log(JSON.stringify({ ok: true, repo: root, scope: auditResult.scope, summary: auditResult.summary, quality, findings: auditResult.findings, files: auditResult.files, analysisCoverage: auditResult.analysisCoverage || null, yaml: auditResult.yaml }, null, 2));
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
printAuditResult(root, auditResult, opts, weights, quality);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** standard 审计结果的可读输出(文案集中一处)。 */
|
|
100
|
-
function printAuditResult(root, auditResult, opts, weights, quality) {
|
|
101
|
-
console.log(`审计 ${root}(scope=${auditResult.scope}${opts.rulesetDir ? ', ruleset=' + opts.rulesetDir : ''}${opts.includeIgnored ? ', include-ignored' : ''})`);
|
|
102
|
-
console.log(` summary: ${JSON.stringify(auditResult.summary)}`);
|
|
103
|
-
if (quality.emptyResult) {
|
|
104
|
-
console.log(` quality: ${quality.emptyReason}(files=${auditResult.files})`);
|
|
105
|
-
} else {
|
|
106
|
-
console.log(` quality: ${quality.score}/100(${quality.level})`);
|
|
107
|
-
}
|
|
108
|
-
if (Object.keys(weights).length) console.log(` 权重覆盖(来自插件配置 weightOverrides): ${JSON.stringify(weights)}`);
|
|
109
|
-
// 文档加分制(0 分起、上限 10)——结构信号 + 交叉验证,不进问题计数
|
|
110
|
-
const ds = auditResult.docsScore;
|
|
111
|
-
if (ds && Array.isArray(ds.items)) {
|
|
112
|
-
const total = ds.items.filter((i) => i.hit).reduce((a, i) => a + (Number(i.score) || 0), 0);
|
|
113
|
-
console.log(` 文档加分:命中 ${ds.hits?.length ?? 0}/${ds.items.length}(+${total.toFixed(1)}/10)`);
|
|
114
|
-
if (Array.isArray(ds.review) && ds.review.length) console.log(` 建议人工复核:${ds.review.join(';')}`);
|
|
115
|
-
}
|
|
116
|
-
// 分析覆盖率(信息项,不进评分)——与插件 code_audit 同一口径,让「到底解析到多少」可见
|
|
117
|
-
if (auditResult.analysisCoverage) console.log(` ${formatAnalysisCoverageLine(auditResult.analysisCoverage)}`);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/** 子命令:scan — 全量扫描目录(**与插件 code_audit 结果一致**)。
|
|
121
|
-
* 修复:此前 CLI 只传 scope+depth,完全不带插件配置(auditLevel / maxScanFiles /
|
|
122
|
-
* 规则包启停 auditDisabledSlots / 权重 weightOverrides)→ 审计结果与插件不一致
|
|
123
|
-
* (实测「CLI 全量扫描分更低、文件更多」:跑了已禁用规则包 + 默认权重 + 不同文件上限)。
|
|
124
|
-
* 现在 CLI 读**同一份** config.json($DSH_HOME/git-push/config.json),用与插件 code_audit
|
|
125
|
-
* 完全相同的 auditOpts 与入口(auditFull),保证功能与结果一致。 */
|
|
126
|
-
/**
|
|
127
|
-
* ⚠️ **当前 CLI 不可达**(2026-11-13 核实):`scan` 命令由注册表 `git_scan` 接管
|
|
128
|
-
* (输出 `count: N` 的仓库扫描),本函数不挂在任何 COMMANDS 表里。
|
|
129
|
-
* 保留原因:它调的是 `auditWithScope(root,{scope:'full',depth})`,是「按审计口径扫描」的
|
|
130
|
-
* 另一种语义,将来若要提供 `scan --audit` 之类可复用。**注意它没传**
|
|
131
|
-
* `maxScanFiles / disabledSlots / rulesetDir` —— 若接回 CLI,需先补这三个,
|
|
132
|
-
* 否则会与插件侧的扫描口径不一致。
|
|
133
|
-
*/
|
|
134
|
-
export async function cmdScan(root, flags) {
|
|
135
|
-
const depth = flags.depth ?? 3;
|
|
136
|
-
const scanResult = await auditWithScope(root, { scope: 'full', depth });
|
|
137
|
-
console.log(`扫描 ${root}(full,depth=${depth})`);
|
|
138
|
-
console.log(` findings: ${scanResult.summary.total}(blocker ${scanResult.summary.blocker} / warning ${scanResult.summary.warning})`);
|
|
139
|
-
for (const f of scanResult.findings.slice(0, AUDIT_PRINT_LIMIT)) {
|
|
140
|
-
console.log(` [${f.severity}] ${f.rule} ${f.file}:${f.line} ${f.message || ''}`);
|
|
141
|
-
}
|
|
142
|
-
}
|
package/lib/cli/commands-doc.mjs
DELETED
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* CLI 命令 · 文档/工具域(file-io/tree-doc/functions/module-splitter)(从 cli.mjs 抽出)
|
|
3
|
-
*
|
|
4
|
-
* 为什么拆出来:cli.mjs 578 行代码超单文件阈值(400),本组 4 个命令是
|
|
5
|
-
* 「文档生成与代码工具」域(扫描文件 I/O / README 目录树 / 函数索引 / 巨型文件拆分),
|
|
6
|
-
* 与审计/账号/VCS 域无共享状态。
|
|
7
|
-
*
|
|
8
|
-
* 保持薄引用:逻辑在 scripts/* 与 lib/git/module-splitter.js(与插件工具同源)。
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import { scanFileIo, summarize } from '../../scripts/scan-file-io.mjs';
|
|
12
|
-
import { runModuleSplitter } from '../git/module-splitter.js';
|
|
13
|
-
import { spawnSync } from 'node:child_process';
|
|
14
|
-
import { fileURLToPath } from 'node:url';
|
|
15
|
-
import { join } from 'node:path';
|
|
16
|
-
|
|
17
|
-
/** 子进程最大等待时长(ms,tree-doc/functions 共用)。 */
|
|
18
|
-
const SUBPROC_TIMEOUT_MS = 120_000;
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* file-io —— 文件读写调用扫描(三标签:类型/操作/上下文)。
|
|
22
|
-
* 输出每条命中带 sync|async、read|write|delete|rename、以及「是否在 async 函数内 /
|
|
23
|
-
* 循环内 / 请求处理路径上」,用于判断同步 I/O 会不会阻塞其他请求、写操作是否高风险。
|
|
24
|
-
* @param {string[]} targets 扫描目标(文件或目录;空=默认 lib/ scripts/ cli.mjs)
|
|
25
|
-
* @param {object} flags { json, summary, write, op, kind, type, risk }
|
|
26
|
-
*/
|
|
27
|
-
export function cmdFileIo(targets = [], flags = {}) {
|
|
28
|
-
const splitMulti = (v) => String(v || '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
29
|
-
const hits = scanFileIo({
|
|
30
|
-
targets,
|
|
31
|
-
opFilter: splitMulti(flags.op),
|
|
32
|
-
kindFilter: splitMulti(flags.kind),
|
|
33
|
-
typeFilter: splitMulti(flags.type),
|
|
34
|
-
riskOnly: flags.risk || '',
|
|
35
|
-
writeOnly: !!flags.write,
|
|
36
|
-
});
|
|
37
|
-
if (flags.json) {
|
|
38
|
-
console.log(JSON.stringify({ ok: true, count: hits.length, hits }, null, 2));
|
|
39
|
-
return hits;
|
|
40
|
-
}
|
|
41
|
-
if (flags.summary) { summarize(hits); return hits; }
|
|
42
|
-
if (!hits.length) { console.log('(未命中任何文件操作)'); return hits; }
|
|
43
|
-
// 按文件分组输出(组内按行号,风险降序已由 scanFileIo 排好)
|
|
44
|
-
const byFile = new Map();
|
|
45
|
-
for (const hit of hits) {
|
|
46
|
-
if (!byFile.has(hit.file)) byFile.set(hit.file, []);
|
|
47
|
-
byFile.get(hit.file).push(hit);
|
|
48
|
-
}
|
|
49
|
-
const riskMark = (r) => (r === 'high' ? '🔴' : r === 'medium' ? '🟠' : '·');
|
|
50
|
-
const tagsOf = (hit) => {
|
|
51
|
-
const t = [hit.type === 'sync' ? '同步' : '异步', hit.kind];
|
|
52
|
-
if (hit.inAsync) t.push('async内');
|
|
53
|
-
if (hit.inLoop) t.push('循环内');
|
|
54
|
-
if (hit.inRequest) t.push('请求路径');
|
|
55
|
-
return t.join('·');
|
|
56
|
-
};
|
|
57
|
-
for (const [file, hs] of [...byFile.entries()].sort()) {
|
|
58
|
-
console.log(`\n── ${file} (${hs.length}) ──`);
|
|
59
|
-
for (const hit of hs.sort((a, b) => a.line - b.line)) {
|
|
60
|
-
console.log(` ${riskMark(hit.risk)} L${String(hit.line).padEnd(4)} ${hit.op.padEnd(14)} ${tagsOf(hit)}`);
|
|
61
|
-
console.log(` ${hit.path}`);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
console.log(`\n合计 ${hits.length} 处文件操作(🔴high=写/删且并发路径 · 🟠medium=同步阻塞或写类 · ·low=普通读)`);
|
|
65
|
-
return hits;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** 子命令:tree-doc — README 目录结构维护(封装 scripts/tree-doc.mjs:sync/gen/check/apply)。 */
|
|
69
|
-
export async function cmdTreeDoc(sub, flags) {
|
|
70
|
-
if (!['sync', 'gen', 'check', 'apply'].includes(sub)) {
|
|
71
|
-
console.error(`tree-doc 子命令应为 sync|gen|check|apply(得「${sub || '(空)'}」)`);
|
|
72
|
-
return 1;
|
|
73
|
-
}
|
|
74
|
-
const script = fileURLToPath(new URL('../../scripts/tree-doc.mjs', import.meta.url));
|
|
75
|
-
const args = [script, sub];
|
|
76
|
-
if (flags.root) args.push('--root', String(flags.root));
|
|
77
|
-
if (flags.readme) args.push('--readme', String(flags.readme));
|
|
78
|
-
if (flags.write) args.push('--write');
|
|
79
|
-
const r = spawnSync(process.execPath, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, timeout: SUBPROC_TIMEOUT_MS, stdio: 'inherit' });
|
|
80
|
-
return r.status === 0 ? 0 : 1;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/** 子命令:functions — 函数索引(analyze)与函数文档(apply,复用 scripts/func-index.js / functions-doc.mjs)。 */
|
|
84
|
-
export async function cmdFunctions(op, target, flags) {
|
|
85
|
-
if (!['analyze', 'apply'].includes(op)) {
|
|
86
|
-
console.error(`functions 子命令应为 analyze|apply(得「${op || '(空)'}」)`);
|
|
87
|
-
return 1;
|
|
88
|
-
}
|
|
89
|
-
if (op === 'analyze') {
|
|
90
|
-
const dir = target || '.';
|
|
91
|
-
// 输出统一落到当前目录(cwd)根,与 apply 读取位置一致(scan 目标只影响扫描范围)
|
|
92
|
-
const outFile = join(process.cwd(), 'functions-index.json');
|
|
93
|
-
const script = fileURLToPath(new URL('../../scripts/func-index.js', import.meta.url));
|
|
94
|
-
const r = spawnSync(process.execPath, [script, dir, '--out', outFile], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, timeout: SUBPROC_TIMEOUT_MS });
|
|
95
|
-
if (r.error) { console.error(`❌ analyze 失败: ${r.error.message}`); return 1; }
|
|
96
|
-
if (flags.json) { console.log(JSON.stringify({ ok: true, outFile }, null, 2)); return 0; }
|
|
97
|
-
console.log(`✅ 函数索引已生成 → ${outFile}`);
|
|
98
|
-
return 0;
|
|
99
|
-
}
|
|
100
|
-
const { applyFunctionsDocs } = await import('../../scripts/functions-doc.mjs');
|
|
101
|
-
const r = applyFunctionsDocs(process.cwd(), { skipEmpty: flags.skipEmpty === true });
|
|
102
|
-
if (!r.ok) { console.error(`❌ ${r.error}`); return 1; }
|
|
103
|
-
if (flags.json) { console.log(JSON.stringify(r, null, 2)); return 0; }
|
|
104
|
-
console.log(`✅ 函数文档已生成:${r.written.length} 个文件${r.archived?.length ? `(归档 ${r.archived.length})` : ''} → ${r.outDir}`);
|
|
105
|
-
return 0;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
/** 子命令:module-splitter — 巨型单文件按职责拆分(复用 scripts/module-splitter.py,python3 零依赖)。 */
|
|
109
|
-
export async function cmdModuleSplitter(positional = [], flags = {}) {
|
|
110
|
-
// python3 调用逻辑抽到 lib/git/module-splitter.js(与工具 module_splitter 共用),
|
|
111
|
-
// 此处只做传参与输出格式化(此前两份相同实现,改一处漏一处)。
|
|
112
|
-
const r = runModuleSplitter({
|
|
113
|
-
sub: String(positional[0] || '').trim(),
|
|
114
|
-
target: String(positional[1] || '').trim(),
|
|
115
|
-
dryRun: flags.dryRun === true,
|
|
116
|
-
});
|
|
117
|
-
if (!r.ok) {
|
|
118
|
-
console.error(r.error);
|
|
119
|
-
return { ok: false, error: r.error };
|
|
120
|
-
}
|
|
121
|
-
if (flags.json) {
|
|
122
|
-
console.log(JSON.stringify({ ok: true, command: r.sub, target: r.target, output: r.output }, null, 2));
|
|
123
|
-
} else {
|
|
124
|
-
console.log(r.output);
|
|
125
|
-
}
|
|
126
|
-
return { ok: true, command: r.sub, target: r.target, output: r.output };
|
|
127
|
-
}
|