dsh-git-push 2.20.19 → 3.0.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 +3 -2
- package/cli-tool.mjs +2 -4
- package/cli.mjs +7 -1
- package/lib/app/apply.js +4 -4
- package/lib/app/command-registry.js +22 -17
- package/lib/app/handlers/meta.js +2 -2
- package/lib/app/handlers/preprocess.js +107 -0
- package/lib/app/handlers/repo-actions.js +2 -2
- package/lib/app/http-handlers.js +13 -42
- package/lib/app/index.js +2 -1
- package/lib/app/inject-text.js +3 -3
- package/lib/app/preprocess-client.js +136 -0
- package/lib/app/repo-ownership.js +1 -1
- package/lib/app/schema.js +3 -3
- package/lib/app/severity.js +14 -0
- package/lib/app/slash-commands.js +5 -164
- package/lib/app/tool-call.js +73 -144
- package/lib/cli/commands-preprocess.mjs +74 -0
- package/lib/cli/commands-tool.mjs +3 -2
- package/lib/cli/commands-vcs.mjs +4 -4
- package/lib/cli/shared.mjs +35 -9
- package/lib/commit-push/pre-commit-engine.js +57 -10
- package/lib/commit-push.js +71 -27
- package/lib/{exempt/index.js → git/exempt-markers.js} +8 -1
- package/lib/git/ignore.js +1 -1
- package/lib/git/repos.js +2 -2
- package/lib/git/sensitive.js +1 -1
- package/lib/npm/publish.js +20 -5
- package/lib/plugin/auto-push.js +2 -2
- package/lib/preprocess/providers.js +191 -0
- package/lib/self/index.js +1 -1
- package/lib/skip-dirs.js +14 -55
- package/package.json +29 -37
- package/scripts/build-client.mjs +2 -0
- package/scripts/check.mjs +4 -2
- package/scripts/local-registry.mjs +2 -1
- package/cli-audit.mjs +0 -141
- 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/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/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/check-js-scope.mjs +0 -87
- package/scripts/clean-date-comments.py +0 -102
- package/scripts/cpu-sample.mjs +0 -188
- package/scripts/doc-drift.mjs +0 -200
- 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/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/symbol-index.mjs +0 -85
- package/scripts/verify-prestep.mjs +0 -100
- 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/app/{schema-audit.js → schema-preprocess.js} +0 -0
- /package/lib/{audit-defaults.js → git/defaults.js} +0 -0
|
@@ -1,228 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 拼接产物的**作用域撞名检查**(通用:任何「多段 JS 拼进同一作用域」的产物都适用)。
|
|
3
|
-
*
|
|
4
|
-
* 要防的是什么:把多段 JS 拼进同一个作用域时,`var`/`function` 会被提升到函数顶部,
|
|
5
|
-
* 同名声明**后者覆盖前者且完全不报错**——某一段依赖的函数被另一段的同名函数顶掉,
|
|
6
|
-
* 运行时行为错乱却查不到任何异常。`const`/`let`/`class` 虽不提升,但同一块内重复声明
|
|
7
|
-
* 同样会让先声明的那份失效(区别只是某些情形会抛 SyntaxError)。
|
|
8
|
-
*
|
|
9
|
-
* 典型落点(本插件是一个代表,不是特例):
|
|
10
|
-
* · 浏览器端插件把多个分片拼成一个 `factory` 函数体(本插件 14 个分片);
|
|
11
|
-
* · 用 `<script>` 直接引入多段脚本(共享全局作用域);
|
|
12
|
-
* · 任何 `cat a.js b.js > bundle.js` 的土制打包。
|
|
13
|
-
*
|
|
14
|
-
* 判定方式(关键:**按真实作用域帧**而不是按缩进/深度):
|
|
15
|
-
* 遍历 token 维护一个花括号帧栈,每个 `{` 是一个**唯一帧**;声明绑定到
|
|
16
|
-
* 「最近的外层作用域帧」——
|
|
17
|
-
* · `var` / `function` → 绑定到最近的**函数作用域帧**(函数体或顶层);
|
|
18
|
-
* · `const` / `let` / `class` → 绑定到**当前帧**(块级作用域);
|
|
19
|
-
* · `for (…)` 头部里的声明 → 绑定到该 for 语句的**专属帧**(每次迭代新绑定,
|
|
20
|
-
* 兄弟循环同名合法;不这样处理会把 `for (const r of a)` + `for (const r of b)`
|
|
21
|
-
* 误判成同帧重名——实测本项目 16 处误报全是这种写法)。
|
|
22
|
-
* 于是「两个不同函数里的同名局部变量」天然分属不同帧 → 不算撞名(不会误报),
|
|
23
|
-
* 而「同一函数体里两段各声明一次同名」会被抓住(这正是静默覆盖的触发条件)。
|
|
24
|
-
*
|
|
25
|
-
* 三条可选检查项(都能关,便于不同项目按自己的契约启用):
|
|
26
|
-
* ① 顶层声明:`topLevelMustBeEmpty`(拼接产物常要求「文件顶层零声明」以免与别家撞名);
|
|
27
|
-
* ② 命名前缀:`prefix`(如 `dshgp_`;留空则跳过),`allowlist` 放行宿主/契约名;
|
|
28
|
-
* ③ 同帧重名:始终启用(这是本检查存在的理由)。
|
|
29
|
-
*/
|
|
30
|
-
import { tokenize } from './tokenizer.js';
|
|
31
|
-
|
|
32
|
-
/** 会产生声明的关键字(其后第一个 ident 即声明名)。 */
|
|
33
|
-
const DECL_KEYWORDS = new Set(['function', 'const', 'let', 'var', 'class']);
|
|
34
|
-
/** 这些关键字后面跟的 `(`…`)` 是**控制语句条件**,其 `{` 是块而不是函数体。 */
|
|
35
|
-
const CONTROL_KEYWORDS = new Set(['if', 'for', 'while', 'switch', 'catch', 'with']);
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* 扫描文本,找出「同一作用域内被声明多次」的名字,以及对顶层/前缀契约的违反。
|
|
39
|
-
*
|
|
40
|
-
* @param {string} text 待检查的 JS 文本
|
|
41
|
-
* @param {{prefix?:string, allowlist?:string[], topLevelMustBeEmpty?:boolean,
|
|
42
|
-
* topLevelAllowlist?:string[]}} [opts]
|
|
43
|
-
* prefix:要求标识符带的前缀(如 `dshgp_`);留空表示不检查前缀。
|
|
44
|
-
* allowlist:前缀例外(宿主注入或契约固定的名字)。
|
|
45
|
-
* topLevelMustBeEmpty:是否禁止文件顶层出现声明(默认 true)。
|
|
46
|
-
* @returns {{ok:boolean, declarations:Array, duplicates:Array, topLevel:Array,
|
|
47
|
-
* missingPrefix:Array, violations:string[]}}
|
|
48
|
-
*/
|
|
49
|
-
export function analyzeScopeCollisions(text = '', {
|
|
50
|
-
prefix = '', allowlist = [], topLevelMustBeEmpty = true, topLevelAllowlist = [],
|
|
51
|
-
} = {}) {
|
|
52
|
-
const tokens = tokenize(String(text));
|
|
53
|
-
const allowed = new Set(allowlist);
|
|
54
|
-
const topAllowed = new Set(topLevelAllowlist);
|
|
55
|
-
|
|
56
|
-
// 帧栈:{ id, isFunction }。id=0 表示文件顶层(虚拟帧,永远在栈底)。
|
|
57
|
-
const frames = [{ id: 0, isFunction: true }];
|
|
58
|
-
let nextFrameId = 1;
|
|
59
|
-
/** 上一个「有效」token 的形态标记,用于判断 `{` 是否为函数体。 */
|
|
60
|
-
let prevSignificant = '';
|
|
61
|
-
/**
|
|
62
|
-
* for 头部作用域:`for (const r of …)` 的绑定属于该 for 语句自己的作用域,
|
|
63
|
-
* 每次迭代都是新绑定 ⇒ 兄弟循环里同名合法。把这类声明绑到**专属虚拟帧**
|
|
64
|
-
* (负 id,与花括号帧号不冲突),否则两个兄弟 for 循环的 `const r`/`let i`
|
|
65
|
-
* 会被误判成同帧重名(本项目自审计实测 16 处误报,全是这种写法)。
|
|
66
|
-
* 覆盖 `for await (…)`:token 流是 for → await → (。
|
|
67
|
-
*/
|
|
68
|
-
const parenStack = []; // { inFor, id } —— 当前打开的括号(只关心是否 for 头部)
|
|
69
|
-
let nextForFrameId = -1;
|
|
70
|
-
let forPending = false; // 刚读到 for(其后可能跟 await),下一个 ( 即 for 头部
|
|
71
|
-
|
|
72
|
-
const declarations = [];
|
|
73
|
-
const duplicates = [];
|
|
74
|
-
/** `${frameId}|${name}` → { count, firstLine }(firstLine 用于「哪两行撞了」的可定位文案)。 */
|
|
75
|
-
const seen = new Map();
|
|
76
|
-
/**
|
|
77
|
-
* 共享作用域帧=**最外层的函数体**(拼接后各段共同落入的那一个)。
|
|
78
|
-
* 前缀检查只针对它:函数内部的局部变量各属自己的帧、彼此不可能撞名,
|
|
79
|
-
* 要求它们也带前缀属过度约束(实测把 244 个局部变量误判成「缺前缀」)。
|
|
80
|
-
* 用「第一个函数帧」而非固定深度 ⇒ 包装形态变了也不用改判定。
|
|
81
|
-
*/
|
|
82
|
-
let sharedFrameId = -1;
|
|
83
|
-
|
|
84
|
-
/** 找最近的外层函数作用域帧(var/function 绑定到它)。 */
|
|
85
|
-
const nearestFunctionFrame = () => {
|
|
86
|
-
for (let i = frames.length - 1; i >= 0; i -= 1) if (frames[i].isFunction) return frames[i].id;
|
|
87
|
-
return 0;
|
|
88
|
-
};
|
|
89
|
-
|
|
90
|
-
for (let i = 0; i < tokens.length; i += 1) {
|
|
91
|
-
const token = tokens[i];
|
|
92
|
-
const value = String(token.value);
|
|
93
|
-
|
|
94
|
-
// ── `for` 头部识别:for [await] ( → 该括号里的声明归 for 自己的作用域 ──
|
|
95
|
-
if (value === 'for') {
|
|
96
|
-
forPending = true;
|
|
97
|
-
prevSignificant = value;
|
|
98
|
-
continue;
|
|
99
|
-
}
|
|
100
|
-
if (value === 'await' && forPending) {
|
|
101
|
-
prevSignificant = value;
|
|
102
|
-
continue; // 保持 pending:`for await (…)`
|
|
103
|
-
}
|
|
104
|
-
if (value === '(') {
|
|
105
|
-
parenStack.push(forPending ? { inFor: true, id: nextForFrameId-- } : { inFor: false, id: 0 });
|
|
106
|
-
forPending = false;
|
|
107
|
-
prevSignificant = value;
|
|
108
|
-
continue;
|
|
109
|
-
}
|
|
110
|
-
if (value === ')') {
|
|
111
|
-
parenStack.pop();
|
|
112
|
-
forPending = false;
|
|
113
|
-
prevSignificant = value;
|
|
114
|
-
continue;
|
|
115
|
-
}
|
|
116
|
-
forPending = false;
|
|
117
|
-
|
|
118
|
-
if (value === '{') {
|
|
119
|
-
// 判断这个 `{` 是不是函数体:紧跟在 `=>` 后,或紧跟在函数参数表 `)` 后,
|
|
120
|
-
// 且该 `)` 不是 if/for/while/switch/catch 的控制条件。
|
|
121
|
-
let isFunction = false;
|
|
122
|
-
if (prevSignificant === '=>') isFunction = true;
|
|
123
|
-
else if (prevSignificant === ')') {
|
|
124
|
-
// 往回找与这个 `)` 配对的 `(`,看它前面是不是控制关键字
|
|
125
|
-
let depthParen = 0;
|
|
126
|
-
let openIdx = -1;
|
|
127
|
-
for (let k = i - 1; k >= 0; k -= 1) {
|
|
128
|
-
const v = String(tokens[k].value);
|
|
129
|
-
if (v === ')') depthParen += 1;
|
|
130
|
-
else if (v === '(') {
|
|
131
|
-
depthParen -= 1;
|
|
132
|
-
if (depthParen === 0) { openIdx = k; break; }
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
const beforeParen = openIdx > 0 ? String(tokens[openIdx - 1].value) : '';
|
|
136
|
-
isFunction = !CONTROL_KEYWORDS.has(beforeParen);
|
|
137
|
-
}
|
|
138
|
-
frames.push({ id: nextFrameId, isFunction });
|
|
139
|
-
if (isFunction && sharedFrameId < 0) sharedFrameId = nextFrameId;
|
|
140
|
-
nextFrameId += 1;
|
|
141
|
-
prevSignificant = '{';
|
|
142
|
-
continue;
|
|
143
|
-
}
|
|
144
|
-
if (value === '}') {
|
|
145
|
-
if (frames.length > 1) frames.pop();
|
|
146
|
-
prevSignificant = '}';
|
|
147
|
-
continue;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
if (DECL_KEYWORDS.has(value)) {
|
|
151
|
-
// 跳过修饰符后取声明名
|
|
152
|
-
let j = i + 1;
|
|
153
|
-
while (j < tokens.length && ['*', 'async', 'export', 'default'].includes(String(tokens[j].value))) j += 1;
|
|
154
|
-
const nameToken = tokens[j];
|
|
155
|
-
if (nameToken && nameToken.type === 'ident') {
|
|
156
|
-
const name = String(nameToken.value);
|
|
157
|
-
const blockScoped = value === 'const' || value === 'let' || value === 'class';
|
|
158
|
-
const inForHeader = Boolean(parenStack.length && parenStack[parenStack.length - 1].inFor);
|
|
159
|
-
// for 头部里的声明(含 var)绑到该 for 的专属帧:兄弟循环同名合法,不算撞名
|
|
160
|
-
const frameId = inForHeader
|
|
161
|
-
? parenStack[parenStack.length - 1].id
|
|
162
|
-
: (blockScoped ? frames[frames.length - 1].id : nearestFunctionFrame());
|
|
163
|
-
// frameDepth 只对花括号帧有意义;for 头部(虚拟帧)记为 -1,既不会误入「顶层声明」,
|
|
164
|
-
// 也不会参与共享作用域(sharedFrameId ≥1)的前缀判定。
|
|
165
|
-
const frameDepth = inForHeader ? -1 : frames.length - 1;
|
|
166
|
-
declarations.push({ name, keyword: value, line: token.line, frameId, frameDepth });
|
|
167
|
-
const key = `${frameId}|${name}`;
|
|
168
|
-
const prev = seen.get(key);
|
|
169
|
-
const count = (prev?.count || 0) + 1;
|
|
170
|
-
const keywords = prev ? [...prev.keywords, value] : [value];
|
|
171
|
-
seen.set(key, { count, firstLine: prev ? prev.firstLine : token.line, keywords });
|
|
172
|
-
// 只报一次:第 3 次及以后的同名声明不再重复入列(同一个名字一条命中,避免刷屏)
|
|
173
|
-
if (count === 2) {
|
|
174
|
-
duplicates.push({
|
|
175
|
-
name,
|
|
176
|
-
frameId,
|
|
177
|
-
scope: blockScoped ? 'block' : 'function',
|
|
178
|
-
line: token.line, // 后来者(静默覆盖的那份)
|
|
179
|
-
firstLine: prev.firstLine, // 先声明的那份
|
|
180
|
-
keywords, // 两次声明用的关键字(决定这条命中算不算真缺陷,见检查器)
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
prevSignificant = value;
|
|
185
|
-
continue;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
prevSignificant = value;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
const topLevel = declarations.filter((d) => d.frameDepth === 0);
|
|
192
|
-
// 前缀只约束**共享作用域帧**(最外层函数体):各函数内部的局部变量分属自己的帧、
|
|
193
|
-
// 彼此不可能撞名,要求它们也带前缀属过度约束(实测会把片段里的局部变量全判成缺前缀)。
|
|
194
|
-
const missingPrefix = !prefix ? [] : declarations.filter(
|
|
195
|
-
(d) => d.frameId === sharedFrameId && !d.name.startsWith(prefix) && !allowed.has(d.name),
|
|
196
|
-
);
|
|
197
|
-
|
|
198
|
-
// 三类命中都带上 message:violations 直接由它们汇总而成 —— **单一措辞源**。
|
|
199
|
-
// 审计检查器(lib/checks/scope-collision.js)出 finding 时直接用 item.message,
|
|
200
|
-
// 不再各自重写一遍文案(两处措辞必然漂移)。
|
|
201
|
-
const topLevelHits = !topLevelMustBeEmpty ? [] : topLevel
|
|
202
|
-
.filter((d) => !topAllowed.has(d.name))
|
|
203
|
-
.map((d) => ({
|
|
204
|
-
...d,
|
|
205
|
-
message: `顶层声明 ${d.name}(第 ${d.line} 行):拼接产物应保持文件顶层零声明,避免与其它脚本/插件撞名`,
|
|
206
|
-
}));
|
|
207
|
-
const prefixHits = !prefix ? [] : missingPrefix.map((d) => ({
|
|
208
|
-
...d,
|
|
209
|
-
message: `声明 ${d.name}(第 ${d.line} 行)缺少 ${prefix} 前缀:拼接分片共用同一作用域,裸名易被别段覆盖`,
|
|
210
|
-
}));
|
|
211
|
-
const duplicateHits = duplicates.map((d) => ({
|
|
212
|
-
...d,
|
|
213
|
-
message: `「${d.scope === 'function' ? '同一函数作用域' : '同一代码块'}」内 ${d.name} 被声明 2 次以上`
|
|
214
|
-
+ `(第 ${d.firstLine} 行与第 ${d.line} 行):var/function 会静默覆盖,后者顶掉前者且不报错`,
|
|
215
|
-
}));
|
|
216
|
-
|
|
217
|
-
const violations = [...topLevelHits, ...prefixHits, ...duplicateHits].map((d) => d.message);
|
|
218
|
-
|
|
219
|
-
return {
|
|
220
|
-
ok: violations.length === 0,
|
|
221
|
-
declarations,
|
|
222
|
-
duplicates: duplicateHits,
|
|
223
|
-
topLevel: topLevelHits,
|
|
224
|
-
missingPrefix: prefixHits,
|
|
225
|
-
violations,
|
|
226
|
-
sharedFrameId,
|
|
227
|
-
};
|
|
228
|
-
}
|
package/lib/ast/scope.js
DELETED
|
@@ -1,241 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 变量作用域分类器 · 最小版(方案 Step 1)
|
|
3
|
-
*
|
|
4
|
-
* 基于 token 流的行号区间法(零依赖,复用 dataflow 的函数体区间思路):
|
|
5
|
-
* 预扫描 tokens 得到「函数体区间」与「循环体区间」,再按声明所在行号归类:
|
|
6
|
-
* - 在函数体内 → 'function'
|
|
7
|
-
* - 在循环体内 → 'loop'(同时标注 inFunction)
|
|
8
|
-
* - 其余 → 'module'(顶层)
|
|
9
|
-
* 另提供「模块级常量赋值」判定(isModuleConstAssignment)——供 magic-number 等规则
|
|
10
|
-
* 豁免 `const MAX_RETRY = 3` 这类模块级命名常量(评审方案:模块/全局作用域豁免常量)。
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import { tokenize } from './tokenizer.js';
|
|
14
|
-
|
|
15
|
-
/** return 语句向后扫「暴露了哪些函数名」的最大 token 跨度(防遍历到语句外)。 */
|
|
16
|
-
const RETURN_SCAN_LOOKAHEAD = 40;
|
|
17
|
-
|
|
18
|
-
/** 收集函数体行号区间 [startLine, endLine](function 声明/表达式/箭头/方法)。 */
|
|
19
|
-
export function collectFnLineRanges(text) {
|
|
20
|
-
const tokens = tokenize(text);
|
|
21
|
-
const ranges = [];
|
|
22
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
23
|
-
const t = tokens[i];
|
|
24
|
-
if (!(t.type === 'ident' && t.value === 'function')) continue;
|
|
25
|
-
let openIdx = -1;
|
|
26
|
-
for (let j = i + 1; j < Math.min(tokens.length, i + 24); j++) {
|
|
27
|
-
if (tokens[j].type === 'punct' && tokens[j].value === '{') { openIdx = j; break; }
|
|
28
|
-
if (tokens[j].type === 'punct' && (tokens[j].value === ';' || tokens[j].value === '}')) break;
|
|
29
|
-
}
|
|
30
|
-
if (openIdx === -1) continue;
|
|
31
|
-
const depth = braceCloseIdx(tokens, openIdx);
|
|
32
|
-
if (depth > openIdx) ranges.push([tokens[openIdx].line, tokens[depth].line]);
|
|
33
|
-
}
|
|
34
|
-
return ranges;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** 收集循环体行号区间 [startLine, endLine](for/while/do/for-in/for-of)。 */
|
|
38
|
-
export function collectLoopLineRanges(text) {
|
|
39
|
-
const tokens = tokenize(text);
|
|
40
|
-
const ranges = [];
|
|
41
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
42
|
-
const t = tokens[i];
|
|
43
|
-
if (t.type !== 'ident' || !['for', 'while', 'do'].includes(t.value)) continue;
|
|
44
|
-
// for (...) { / while (...) { / do { —— 找循环后第一个 '{'
|
|
45
|
-
for (let j = i + 1; j < Math.min(tokens.length, i + 24); j++) {
|
|
46
|
-
const tj = tokens[j];
|
|
47
|
-
if (tj.type === 'punct' && tj.value === '{') {
|
|
48
|
-
const depth = braceCloseIdx(tokens, j);
|
|
49
|
-
if (depth > j) ranges.push([tokens[j].line, tokens[depth].line]);
|
|
50
|
-
break;
|
|
51
|
-
}
|
|
52
|
-
// fix:for 头部分号(for (let i=0; ...))不能提前 break——只以 } 或超限终止
|
|
53
|
-
if (tj.type === 'punct' && tj.value === '}') break;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
return ranges;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** 从 openIdx(应为 `{`)找配对闭括号下标(无配对返回 openIdx)。 */
|
|
60
|
-
function braceCloseIdx(tokens, openIdx) {
|
|
61
|
-
let depth = 0;
|
|
62
|
-
for (let j = openIdx; j < tokens.length; j++) {
|
|
63
|
-
if (tokens[j].type === 'punct' && tokens[j].value === '{') depth++;
|
|
64
|
-
else if (tokens[j].type === 'punct' && tokens[j].value === '}') {
|
|
65
|
-
depth--;
|
|
66
|
-
if (depth === 0) return j;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return openIdx;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
/** 启动路径函数名模式(一次性初始化:apply/init/main/bootstrap/setup 等),豁免大函数/high 复杂度。 */
|
|
75
|
-
const STARTUP_PATH_PATTERNS = ['apply', 'init', 'main', 'bootstrap', 'setup', 'mount', 'start', 'boot', 'register', 'configure', 'sync', 'restore', 'migrate'];
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* 序列化/反序列化职责函数名模式(评审规则③):
|
|
79
|
-
* 序列化/反序列化函数(to_json/from_json/dumps/loads/serialize/deserialize/parse/unpack 等)
|
|
80
|
-
* 在意义明确、变量生命周期仅当前会话时,代码常超百行——过度拆分反而让数据传递与
|
|
81
|
-
* 生命周期处理复杂化,得不偿失。故函数长度/复杂度规则对其放宽(非全豁免,见规则 yml)。
|
|
82
|
-
* 收紧面:仅「职责名」命中(含 serialize/deserial/serializ/to_json/from_json/dumps/loads/
|
|
83
|
-
* parse/unpack/pack/encode/decode 语义的函数名),普通业务函数不含这些词不受影响。
|
|
84
|
-
*/
|
|
85
|
-
const SERIALIZATION_PATH_PATTERNS = ['serial', 'to_json', 'from_json', 'dumps', 'loads', 'parse', 'unpack', 'pack', 'encode', 'decode'];
|
|
86
|
-
|
|
87
|
-
/** 按函数名判执行路径:'startup' | 'serialization' | 'unknown'(请求路径等复杂判定留给调用链分析)。 */
|
|
88
|
-
export function classifyFunctionPath(fnName = '') {
|
|
89
|
-
const name = String(fnName).toLowerCase();
|
|
90
|
-
if (STARTUP_PATH_PATTERNS.some((p) => name.includes(p))) return 'startup';
|
|
91
|
-
if (SERIALIZATION_PATH_PATTERNS.some((p) => name.includes(p))) return 'serialization';
|
|
92
|
-
return 'unknown';
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* 声明行号归类:'module' | 'function' | 'loop'。
|
|
96
|
-
* @param {string} text 文件全文
|
|
97
|
-
* @param {number} line 声明所在行号(1-based)
|
|
98
|
-
* @returns {{scope: string, inFunction: boolean, inLoop: boolean}}
|
|
99
|
-
*/
|
|
100
|
-
export function classifyLineScope(text, line) {
|
|
101
|
-
const inLoop = collectLoopLineRanges(text).some(([s, e]) => line >= s && line <= e);
|
|
102
|
-
const inFunction = collectFnLineRanges(text).some(([s, e]) => line >= s && line <= e);
|
|
103
|
-
return { scope: inFunction ? 'function' : 'module', inFunction, inLoop };
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* 模块级常量赋值判定:该行形如 `const NAME = <数字>`(或 let/var + 大写常量名),
|
|
108
|
-
* 且声明在模块顶层(不在函数体内)——magic-number 等规则豁免这类命名常量。
|
|
109
|
-
* @param {string} text 文件全文
|
|
110
|
-
* @param {number} line 目标行号
|
|
111
|
-
* @returns {boolean}
|
|
112
|
-
*/
|
|
113
|
-
export function isModuleConstAssignment(text, line) { // dsh-skip-complexity: 模块级常量判定器(顶层过滤+常量名风格+行内=num 多条件链,职责单一)
|
|
114
|
-
// 仅模块顶层:函数体内 `const x = 3` 不算命名常量(评审方案:函数内魔数照报)
|
|
115
|
-
if (collectFnLineRanges(text).some(([sf, ef]) => line >= sf && line <= ef)) return false;
|
|
116
|
-
const tokens = tokenize(text);
|
|
117
|
-
// 行内找 const/let/var → ident → = 且右侧是 num(含大写常量名风格)
|
|
118
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
119
|
-
const t = tokens[i];
|
|
120
|
-
if (t.line !== line) continue;
|
|
121
|
-
if (t.type !== 'ident' || !['const', 'let', 'var'].includes(t.value)) continue;
|
|
122
|
-
const name = tokens[i + 1];
|
|
123
|
-
if (!name || name.type !== 'ident' || name.line !== line) continue;
|
|
124
|
-
// 常量名风格:全大写或 CamelCase(小写则不算命名常量)
|
|
125
|
-
const isConstStyle = /^[A-Z]/.test(name.value) || /^[a-z]+[A-Z]/.test(name.value);
|
|
126
|
-
if (!isConstStyle) continue;
|
|
127
|
-
// 跳过 = 后是函数/表达式(非纯数字)的情况——找行内 '=' 后的 num
|
|
128
|
-
for (let j = i + 2; j < tokens.length && tokens[j].line === line; j++) {
|
|
129
|
-
if (tokens[j].type === 'punct' && tokens[j].value === '=') {
|
|
130
|
-
const rhs = tokens[j + 1];
|
|
131
|
-
if (rhs && rhs.type === 'num' && rhs.line === line) return true;
|
|
132
|
-
break;
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
return false;
|
|
137
|
-
}
|
|
138
|
-
/**
|
|
139
|
-
* 闭包双重作用域(方案 Step 6/P4)——词法作用域 vs 功能作用域。
|
|
140
|
-
*
|
|
141
|
-
* 词法上在函数内(局部),功能上可能被暴露(return / 挂 this / 挂 exports)→ 公共 API,
|
|
142
|
-
* 按模块级规则处理(不享受 startup 等豁免);作为参数传递 → 回调(unknown 路径)。
|
|
143
|
-
* @param {string} text 文件全文
|
|
144
|
-
* @returns {Map<string, string>} fnName → 'public' | 'callback'
|
|
145
|
-
*/
|
|
146
|
-
export function analyzeFunctionalScope(text = '') {
|
|
147
|
-
const tokens = tokenize(text);
|
|
148
|
-
const fnNames = collectFnNames(tokens);
|
|
149
|
-
const scope = new Map();
|
|
150
|
-
scanReturnExposed(tokens, fnNames, scope); // ① return 暴露
|
|
151
|
-
scanAssignmentExposed(tokens, fnNames, scope); // ② this/exports 暴露
|
|
152
|
-
scanCallbackPassed(tokens, fnNames, scope); // ③ 参数传递
|
|
153
|
-
return scope;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/** 收集全部具名函数名(function NAME / const NAME = function / const NAME = (...) =>)。 */
|
|
157
|
-
function collectFnNames(tokens) { // dsh-skip-complexity: 函数名收集器(function/const function/箭头三形态扫描,拆分后职责单一)
|
|
158
|
-
const fnNames = new Set();
|
|
159
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
160
|
-
const t = tokens[i];
|
|
161
|
-
if (t.type === 'ident' && t.value === 'function') {
|
|
162
|
-
const nx = tokens[i + 1];
|
|
163
|
-
if (nx && nx.type === 'ident') { fnNames.add(nx.value); continue; }
|
|
164
|
-
// function (xxx) { —— const f = function 场景
|
|
165
|
-
for (let k = i - 1; k >= Math.max(0, i - 5); k--) {
|
|
166
|
-
const tk = tokens[k];
|
|
167
|
-
if (tk && tk.type === 'ident' && ['const', 'let', 'var'].includes(tk.value)) {
|
|
168
|
-
const nm = tokens[k + 1];
|
|
169
|
-
if (nm && nm.type === 'ident') { fnNames.add(nm.value); break; }
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
} else if (t.type === 'ident' && ['const', 'let', 'var'].includes(t.value)) {
|
|
173
|
-
const nm = tokens[i + 1];
|
|
174
|
-
// const NAME = (...) => { 箭头函数(后续有 =>)
|
|
175
|
-
if (nm && nm.type === 'ident') {
|
|
176
|
-
for (let j = i + 2; j < Math.min(tokens.length, i + 30); j++) {
|
|
177
|
-
if (tokens[j].type === 'punct' && tokens[j].value === '=>') { fnNames.add(nm.value); break; }
|
|
178
|
-
if (tokens[j].type === 'punct' && tokens[j].value === ';') break;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
return fnNames;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/** ① return 暴露:return { fnA, fnB } / return fnA。 */
|
|
187
|
-
function scanReturnExposed(tokens, fnNames, scope) {
|
|
188
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
189
|
-
const t = tokens[i];
|
|
190
|
-
if (!(t.type === 'ident' && t.value === 'return')) continue;
|
|
191
|
-
for (let j = i + 1; j < Math.min(tokens.length, i + RETURN_SCAN_LOOKAHEAD); j++) {
|
|
192
|
-
const tj = tokens[j];
|
|
193
|
-
if (tj.type === 'punct' && (tj.value === ';' || tj.value === '}')) break;
|
|
194
|
-
if (tj.type === 'ident' && fnNames.has(tj.value) && !scope.has(tj.value)) scope.set(tj.value, 'public');
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/** ② this.xxx = fn / exports.xxx = fn / module.exports = { fn }。 */
|
|
200
|
-
function scanAssignmentExposed(tokens, fnNames, scope) { // dsh-skip-complexity: this/exports/module 赋值暴露扫描(三前缀分支为结构必然)
|
|
201
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
202
|
-
const t = tokens[i];
|
|
203
|
-
if (!(t.type === 'ident' && ['this', 'exports', 'module'].includes(t.value))) continue;
|
|
204
|
-
let j = i + 1;
|
|
205
|
-
if (t.value === 'module') {
|
|
206
|
-
if (!(tokens[j]?.type === 'punct' && tokens[j].value === '.')) continue;
|
|
207
|
-
j += 1;
|
|
208
|
-
if (!(tokens[j]?.type === 'ident' && tokens[j].value === 'exports')) continue;
|
|
209
|
-
j += 1;
|
|
210
|
-
}
|
|
211
|
-
if (tokens[j]?.type === 'punct' && tokens[j].value === '.') {
|
|
212
|
-
j += 1;
|
|
213
|
-
if (tokens[j]?.type === 'punct' && tokens[j].value === '=') { continue; } // 赋值场景下面处理
|
|
214
|
-
j += 1; // exports.xxx
|
|
215
|
-
}
|
|
216
|
-
// 找 = 后的 ident(function 名)
|
|
217
|
-
for (let k = j; k < Math.min(tokens.length, j + 12); k++) {
|
|
218
|
-
const tk = tokens[k];
|
|
219
|
-
if (tk.type === 'punct' && tk.value === '=') {
|
|
220
|
-
const rhs = tokens[k + 1];
|
|
221
|
-
if (rhs && rhs.type === 'ident' && fnNames.has(rhs.value)) scope.set(rhs.value, 'public');
|
|
222
|
-
break;
|
|
223
|
-
}
|
|
224
|
-
if (tk.type === 'punct' && tk.value === ';') break;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
/** ③ 作为参数传递(回调/未知路径):call(fnA) / arr.map(fnA)。 */
|
|
230
|
-
function scanCallbackPassed(tokens, fnNames, scope) {
|
|
231
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
232
|
-
const t = tokens[i];
|
|
233
|
-
if (!(t.type === 'ident' && fnNames.has(t.value))) continue;
|
|
234
|
-
if (scope.has(t.value)) continue;
|
|
235
|
-
const prevT = tokens[i - 1];
|
|
236
|
-
const nextT = tokens[i + 1];
|
|
237
|
-
const passedAsArg = prevT && (prevT.type === 'punct' && (prevT.value === '(' || prevT.value === ','))
|
|
238
|
-
&& nextT && (nextT.type === 'punct' && (nextT.value === ')' || nextT.value === ','));
|
|
239
|
-
if (passedAsArg) scope.set(t.value, 'callback');
|
|
240
|
-
}
|
|
241
|
-
}
|
package/lib/ast/shell.js
DELETED
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 分层位置(三层审计架构)② 具体实现 lib/ast/*(token 级判定):
|
|
3
|
-
* shell 相关精筛——cd 到动态路径、写操作目标命中 .gitignore。
|
|
4
|
-
* 调用包装在 lib/checks/common.js(转成应报行集合后由 regex.js 消费)。
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
-
import { join, resolve } from 'node:path';
|
|
9
|
-
import { makeCodeLineFilter } from './code-lines.js';
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* astConfirmKind: "shell-cd-dynamic" 的精筛——cd 到动态路径($VAR / $(cmd))且无失败兜底的行。
|
|
13
|
-
* 报出条件(全部满足才报):
|
|
14
|
-
* ① 候选行在代码里(注释/字符串内不报)
|
|
15
|
-
* ② 含 cd 命令且目标含 $(变量/命令替换 → 目录运行时才知道,可能不存在)
|
|
16
|
-
* ③ 非脚本自我定位(`cd "$(dirname "$0")"` / `"${BASH_SOURCE[0]%/*}"`——目录必然存在,豁免)
|
|
17
|
-
* ④ 同行无 `||` 兜底(cd ... || exit/return/echo)
|
|
18
|
-
* ⑤ 非 `&&` 链结尾(cd x && ... 失败即断链)
|
|
19
|
-
* @param {string} text 文件全文
|
|
20
|
-
* @returns {Set<number>} 应报的行号集合
|
|
21
|
-
*/
|
|
22
|
-
export function shellCdDynamicLines(text) {
|
|
23
|
-
const t = String(text || '');
|
|
24
|
-
const lines = t.split('\n');
|
|
25
|
-
const candidates = [];
|
|
26
|
-
for (let i = 0; i < lines.length; i++) {
|
|
27
|
-
if (lines[i] && /(?:^|[;&])\s*cd\s+\S+/.test(lines[i])) candidates.push(i + 1);
|
|
28
|
-
}
|
|
29
|
-
if (!candidates.length) return new Set();
|
|
30
|
-
const codeFilter = makeCodeLineFilter(t, candidates);
|
|
31
|
-
const out = new Set();
|
|
32
|
-
for (const ln of candidates) {
|
|
33
|
-
const line = lines[ln - 1];
|
|
34
|
-
const match = /(?:^|[;&])\s*cd\s+(\S+)/.exec(line);
|
|
35
|
-
if (!match) continue;
|
|
36
|
-
const target = match[1];
|
|
37
|
-
if (!target.includes('$')) continue; // ② 字面量路径(仓库内存在性由人工/仓库级判定)
|
|
38
|
-
if (/dirname|BASH_SOURCE|%\/\*/.test(target)) continue; // ③ 自我定位豁免
|
|
39
|
-
if (!codeFilter.isCode(ln)) continue; // ① 注释/字符串内不报
|
|
40
|
-
if (/\|\|/.test(line.slice(match.index))) continue; // ④ 有兜底
|
|
41
|
-
if (/&&/.test(line.slice(match.index))) continue; // ⑤ && 链(cd 失败即断链)
|
|
42
|
-
out.add(ln);
|
|
43
|
-
}
|
|
44
|
-
return out;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/* ────────────────── .gitignore 解析(轻量版,够规则判定用) ────────────────── */
|
|
48
|
-
|
|
49
|
-
/** 解析 .gitignore:逐行 → { negate, re }(! 取反 / 目录尾 / glob 通配)。 */
|
|
50
|
-
function parseGitignore(text) {
|
|
51
|
-
const patterns = [];
|
|
52
|
-
for (const raw of String(text || '').split('\n')) {
|
|
53
|
-
let line = raw.trim();
|
|
54
|
-
if (!line || line.startsWith('#')) continue;
|
|
55
|
-
let negate = false;
|
|
56
|
-
if (line.startsWith('!')) { negate = true; line = line.slice(1).trim(); }
|
|
57
|
-
if (!line) continue;
|
|
58
|
-
const dirOnly = line.endsWith('/');
|
|
59
|
-
const anchored = line.startsWith('/');
|
|
60
|
-
line = line.replace(/^\/+/, '').replace(/\/+$/, '');
|
|
61
|
-
if (!line) continue;
|
|
62
|
-
let re = '';
|
|
63
|
-
for (const ch of line) {
|
|
64
|
-
if (ch === '*') re += '[^/]*';
|
|
65
|
-
else if (ch === '?') re += '[^/]';
|
|
66
|
-
else if (ch === '.') re = re + '\\.';
|
|
67
|
-
else if ('/\\^$+{}()|'.includes(ch)) re += '\\' + ch;
|
|
68
|
-
else re += ch;
|
|
69
|
-
}
|
|
70
|
-
const tail = dirOnly ? '(?:/|$)' : '(?:/|$)';
|
|
71
|
-
// 含 / 或前导 / 的模式相对仓库根匹配;否则匹配任意层级 basename
|
|
72
|
-
const body = (anchored || line.includes('/')) ? `(?:^|.*/)${re}${tail}` : `(?:^|.*/)${re}${tail}`;
|
|
73
|
-
patterns.push({ negate, re: new RegExp(body) });
|
|
74
|
-
}
|
|
75
|
-
return patterns;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** 目标是否被规则忽略(最后一个匹配生效;! 取反恢复)。 */
|
|
79
|
-
function isIgnored(target, patterns) {
|
|
80
|
-
let ignored = false;
|
|
81
|
-
for (const { negate, re } of patterns) {
|
|
82
|
-
if (re.test(target)) ignored = !negate;
|
|
83
|
-
}
|
|
84
|
-
return ignored;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** 从行里提取写操作的目标路径(node 字面量 / shell 命令参数)。 */
|
|
88
|
-
function extractWriteTarget(line) {
|
|
89
|
-
const match = /\b(writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream|mkdir|mkdirSync)\s*\(\s*['"]([^'"]+)['"]/.exec(line);
|
|
90
|
-
if (match && match[2]) return match[2];
|
|
91
|
-
const sh = /(?:^|[;&])\s*mkdir\s+(?:-p\s+)?['"]?([^'"\s]+)['"]?/.exec(line);
|
|
92
|
-
if (sh) return sh[1];
|
|
93
|
-
return '';
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* astConfirmKind: "write-into-gitignored" 的精筛——写文件/目录的目标路径命中仓库
|
|
98
|
-
* .gitignore(产出目录被忽略、可能不存在)的行。
|
|
99
|
-
* 依赖仓库上下文 repoPath(读 .gitignore);无 repoPath(单文件审计)或 .gitignore
|
|
100
|
-
* 不存在时返回空集合(不报——没有仓库上下文不臆测)。
|
|
101
|
-
* 豁免:node_modules 内写入(安装产物)、/tmp 前缀(临时目录)、.gitignore 中 ! 取反。
|
|
102
|
-
* @param {string} text 文件全文
|
|
103
|
-
* @param {string} [repoPath] 仓库根目录(auditFile 传入的 opts.repoPath)
|
|
104
|
-
* @returns {Set<number>} 应报的行号集合
|
|
105
|
-
*/
|
|
106
|
-
export function writeIntoGitignoredLines(text, repoPath = '') {
|
|
107
|
-
const t = String(text || '');
|
|
108
|
-
if (!t || !repoPath) return new Set();
|
|
109
|
-
const gi = resolve(join(String(repoPath), '.gitignore'));
|
|
110
|
-
if (!existsSync(gi)) return new Set();
|
|
111
|
-
let giText = '';
|
|
112
|
-
try { giText = readFileSync(gi, 'utf8'); } catch { return new Set(); }
|
|
113
|
-
const patterns = parseGitignore(giText);
|
|
114
|
-
if (!patterns.length) return new Set();
|
|
115
|
-
const lines = t.split('\n');
|
|
116
|
-
const candidates = [];
|
|
117
|
-
for (let i = 0; i < lines.length; i++) {
|
|
118
|
-
if (lines[i] && extractWriteTarget(lines[i])) candidates.push(i + 1);
|
|
119
|
-
}
|
|
120
|
-
if (!candidates.length) return new Set();
|
|
121
|
-
const codeFilter = makeCodeLineFilter(t, candidates);
|
|
122
|
-
const out = new Set();
|
|
123
|
-
for (const ln of candidates) {
|
|
124
|
-
const line = lines[ln - 1];
|
|
125
|
-
const target = extractWriteTarget(line);
|
|
126
|
-
if (!target || !codeFilter.isCode(ln)) continue;
|
|
127
|
-
if (/node_modules/.test(target) || /^\/?tmp\b/.test(target)) continue; // 豁免
|
|
128
|
-
if (isIgnored(target, patterns)) out.add(ln);
|
|
129
|
-
}
|
|
130
|
-
return out;
|
|
131
|
-
}
|