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
package/lib/audit/collector.js
DELETED
|
@@ -1,610 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-git-push 审计总入口:文件收集(gitignore 感知)
|
|
3
|
-
*
|
|
4
|
-
* 修 P0 教训:git 忽略文件默认排除(listTextFiles 支持 git check-ignore)。
|
|
5
|
-
* - gitIgnoreRoot 为 git 仓库:git check-ignore --stdin 批量判定(Map 缓存)
|
|
6
|
-
* - 非 git 目录:全量收集不报错
|
|
7
|
-
*/
|
|
8
|
-
import { readdirSync, statSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
9
|
-
import { tmpdir } from 'node:os';
|
|
10
|
-
import { createHash } from 'node:crypto';
|
|
11
|
-
import { readdir, stat } from 'node:fs/promises';
|
|
12
|
-
import { join, relative, extname, sep } from 'node:path';
|
|
13
|
-
import { execFileSync, spawnSync } from 'node:child_process';
|
|
14
|
-
import { isTestExemptDir } from '../exempt/index.js';
|
|
15
|
-
import { SKIP_DIRS as HARDCODED_SKIP, getSkipSet } from '../skip-dirs.js';
|
|
16
|
-
import { parseGitignore, isIgnoredByRules } from './gitignore-match.js';
|
|
17
|
-
import { splitAuditIgnore } from './auditignore-rules.js';
|
|
18
|
-
import { GIT_GLOBAL_ARGS } from '../core/exec.js';
|
|
19
|
-
|
|
20
|
-
/** 跳过目录集合 = 硬编码基线(node_modules/.git) ∪ yml 黑名单关键词(加载一次缓存)。 */
|
|
21
|
-
const SKIP_DIRS = getSkipSet();
|
|
22
|
-
|
|
23
|
-
export const TEXT_EXT = new Set([
|
|
24
|
-
'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'json', 'yml', 'yaml', 'md', 'txt', 'html', 'css',
|
|
25
|
-
'sh', 'py', 'rb', 'go', 'rs', 'java', 'c', 'cpp', 'h', 'hpp', 'xml', 'toml', 'ini', 'cfg',
|
|
26
|
-
'conf', 'env', 'gitignore', 'npmrc', 'properties', 'sql', 'vue', 'svelte',
|
|
27
|
-
// 2026-10-16 补:PHP / Swift / Kotlin——此前只补了占位规则包 yml,**收集白名单没放行** ✗
|
|
28
|
-
// ⇒ 这两个语言的文件从来没进过审计管道,规则写了也永远 0 命中(实测合成样例 0 命中定位到此处)。
|
|
29
|
-
// phtml 是 PHP 模板扩展名(同 PHP 槽位 exts),kt 与 java 槽位共用一个包。
|
|
30
|
-
'php', 'phtml', 'swift', 'kt',
|
|
31
|
-
// 2026-10-29 补:C# 与 C/C++ 的其余常见扩展名。
|
|
32
|
-
// .cs 此前不在白名单 ⇒ C# 文件**完全不进审计管道**(668 个 .cs 的全量审计只收到 26 个非 .cs 文件);
|
|
33
|
-
// cc/cxx/hh/hxx 同理——EXT_TO_GRAMMAR 里映射了语法,但白名单不放行的话文件根本到不了解析那一步。
|
|
34
|
-
// 这两处必须同时改:只补映射 = 语法永远用不上,只补白名单 = 一直走 token 级回退。
|
|
35
|
-
'cs', 'cc', 'cxx', 'hh', 'hxx',
|
|
36
|
-
// mts/cts 是 TypeScript 的模块变体扩展名:EXT_TO_GRAMMAR 早已映射到 typescript 语法,
|
|
37
|
-
// 但这里一直没放行 ⇒ 文件不进管道(与 .cs 同一类缺口)。wasms 里没有独立语法,复用 typescript 即可。
|
|
38
|
-
'mts', 'cts',
|
|
39
|
-
]);
|
|
40
|
-
/** git 探活 / 忽略清单批量判定 / 单目录判定 的超时(毫秒)。 */
|
|
41
|
-
const GIT_PROBE_TIMEOUT_MS = 10_000;
|
|
42
|
-
const IGNORE_BATCH_TIMEOUT_MS = 60_000;
|
|
43
|
-
const IGNORE_SINGLE_TIMEOUT_MS = 5_000;
|
|
44
|
-
/**
|
|
45
|
-
* git 命令统一前缀:直接用 lib/core/exec.js 的权威包装(GIT_GLOBAL_ARGS)。
|
|
46
|
-
*
|
|
47
|
-
* 为什么不再本地定义:此前这里只抄了 `-c core.quotepath=false`(禁路径转义,
|
|
48
|
-
* 中文/空格文件名按原样匹配),与 exec.js 的权威前缀「抄写不一致」——
|
|
49
|
-
* exec.js 那份还带 `safe.directory=*`(防不信任目录误伤工作区)与
|
|
50
|
-
* `core.filemode=false`(忽略权限位抖动,CIFS/NFS/跨机同步后不再刷一堆 M)。
|
|
51
|
-
* 直接复用权威定义 ⇒ 三件一次到位,以后只改一处。
|
|
52
|
-
*/
|
|
53
|
-
const GIT_QUOTEPATH_ARGS = GIT_GLOBAL_ARGS;
|
|
54
|
-
/** 单文件大小上限:超过 1MB 的文件跳过(防止读入大文件拖死扫描进程)。 */
|
|
55
|
-
const MAX_FILE_SIZE = 1024 * 1024;
|
|
56
|
-
|
|
57
|
-
/** git 忽略文件集合缓存(按 repo 根缓存:git 目录存忽略集,非 git 目录存 null)。 */
|
|
58
|
-
const ignoreCache = new Map();
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* 非 git 目录忽略文件的**读取缓存**:键 = 忽略文件绝对路径。
|
|
62
|
-
*
|
|
63
|
-
* 为什么需要:插件请求路径上每次收集都会读 `.gitignore` / `.auditignore`,
|
|
64
|
-
* 原先每处都是 `existsSync + readFileSync` 两次同步系统调用(审计 robustness/io-risk
|
|
65
|
-
* 命中「请求处理路径上的 I/O」)。进程内一次审计里忽略文件不会变,缓存即可;
|
|
66
|
-
* CLI / 工具每次审计都是新进程,因此不存在跨次陈旧问题。
|
|
67
|
-
* @param {string} p 忽略文件绝对路径
|
|
68
|
-
* @returns {string|null} 文件内容;不存在或读失败返回 null
|
|
69
|
-
*/
|
|
70
|
-
const ignoreFileTextCache = new Map();
|
|
71
|
-
function readIgnoreFileCached(p) {
|
|
72
|
-
if (ignoreFileTextCache.has(p)) return ignoreFileTextCache.get(p);
|
|
73
|
-
let out = null;
|
|
74
|
-
try { if (existsSync(p)) out = readFileSync(p, 'utf8'); } catch { out = null; }
|
|
75
|
-
ignoreFileTextCache.set(p, out);
|
|
76
|
-
return out;
|
|
77
|
-
}
|
|
78
|
-
/** git 工作树探活缓存(与 ignoreCache 分开:后者存忽略集,可为 null)。 */
|
|
79
|
-
const gitProbeCache = new Map();
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* 该目录是否 git 工作树(带缓存,避免与 tryLoadGitIgnoreSet 重复 spawn)。
|
|
83
|
-
*
|
|
84
|
-
* 为什么要单独探活:`collectTextFiles` 的文件级豁免需要区分「git 仓库」与「非 git 兜底」,
|
|
85
|
-
* 而 `gitIgnoreRoot` 在两者下都非空(非 git 但有 .auditignore 时也传 root)。
|
|
86
|
-
* 探活结果按目录缓存;失败(git 不可用)按非 git 处理,即走兜底——兜底总是可用的。
|
|
87
|
-
* @param {string} dir
|
|
88
|
-
* @returns {boolean}
|
|
89
|
-
*/
|
|
90
|
-
function isGitWorkTree(dir) {
|
|
91
|
-
if (gitProbeCache.has(dir)) return gitProbeCache.get(dir);
|
|
92
|
-
let ok = false;
|
|
93
|
-
try {
|
|
94
|
-
const r = spawnSync('git', [...GIT_QUOTEPATH_ARGS, '-C', dir, 'rev-parse', '--is-inside-work-tree'], {
|
|
95
|
-
encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: GIT_PROBE_TIMEOUT_MS,
|
|
96
|
-
});
|
|
97
|
-
ok = r.status === 0 && String(r.stdout || '').trim() === 'true';
|
|
98
|
-
} catch { ok = false; }
|
|
99
|
-
gitProbeCache.set(dir, ok);
|
|
100
|
-
return ok;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* `.auditignore` 里出现细粒度条目(`路径 : 规则`)时,采集阶段要用**去掉这些行**的副本
|
|
105
|
-
* 作为 `core.excludesFile` —— 否则文件会被整文件跳过,细粒度豁免就退化成整文件豁免了。
|
|
106
|
-
* 无细粒度条目时直接用原文件(零额外开销,行为与旧版完全一致)。
|
|
107
|
-
* 结果按「根目录 + 文件 mtime/size」缓存:一次审计里 collectTextFiles 会被调用多次。
|
|
108
|
-
*/
|
|
109
|
-
const AUDIT_IGNORE_COMPAT_CACHE = new Map();
|
|
110
|
-
function auditIgnoreExcludesFile(root, auditIgnorePath) {
|
|
111
|
-
let text;
|
|
112
|
-
try { text = readFileSync(auditIgnorePath, 'utf8'); } catch { return auditIgnorePath; }
|
|
113
|
-
let splitted;
|
|
114
|
-
try { splitted = splitAuditIgnore(text); } catch { return auditIgnorePath; }
|
|
115
|
-
if (!splitted.scoped.length) return auditIgnorePath;
|
|
116
|
-
const st = (() => { try { return statSync(auditIgnorePath); } catch { return null; } })();
|
|
117
|
-
const stamp = `${st ? st.mtimeMs : 0}:${text.length}`;
|
|
118
|
-
const cached = AUDIT_IGNORE_COMPAT_CACHE.get(root);
|
|
119
|
-
if (cached && cached.stamp === stamp) return cached.path;
|
|
120
|
-
const hash = createHash('sha1').update(`${root}:${stamp}`).digest('hex').slice(0, 16);
|
|
121
|
-
const out = join(tmpdir(), `dsh-auditignore-${hash}.txt`);
|
|
122
|
-
try { writeFileSync(out, splitted.wholeText, 'utf8'); } catch { return auditIgnorePath; }
|
|
123
|
-
AUDIT_IGNORE_COMPAT_CACHE.set(root, { path: out, stamp });
|
|
124
|
-
return out;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* 非 git 目录下用纯 JS 匹配 `.auditignore`,产出与 git 路径同构的「被忽略目录集」。
|
|
129
|
-
*
|
|
130
|
-
* 为什么要预计算目录集而非逐文件判定:`collectTextFiles` 的 walk 阶段用该集合做
|
|
131
|
-
* **目录级剪枝**(命中即整棵跳过),与 git 路径保持同一调用契约;逐文件判定会退化成
|
|
132
|
-
* 全量遍历后再过滤,在大目录上明显更慢。
|
|
133
|
-
*
|
|
134
|
-
* 返回的 Set 同时含「被忽略的目录」与其下**任意层级的后代目录**吗?不含——下游
|
|
135
|
-
* walk 是逐目录判定的,父目录命中即整棵跳过,因此只需把命中的目录本身放进集合。
|
|
136
|
-
* 但 `collectTextFiles` 的文件级兜底会再逐文件判定一次(见该函数),两处互补。
|
|
137
|
-
*
|
|
138
|
-
* @param {string} root 扫描根目录(非 git)
|
|
139
|
-
* @returns {Set<string>|null} 被忽略的目录相对路径集合;无 .auditignore 时返回 null
|
|
140
|
-
*/
|
|
141
|
-
function tryLoadAuditIgnoreFallback(root, respectAuditIgnore = true) {
|
|
142
|
-
// 非 git 目录的忽略信息来自**目录里的文件本身**:
|
|
143
|
-
// `.gitignore` **永远生效**——它是仓库自带的忽略声明,与是否 `git init` 无关
|
|
144
|
-
// (解压的源码包 / 临时导出目录 / 未 init 的工程同样带它)。
|
|
145
|
-
// 实测 bug:非 git 目录下 `.gitignore` 被完全无视 ⇒ 被忽略的 `ignored/secret.js`
|
|
146
|
-
// 照样进审计并报 3 条(默认与 `--include-ignored` 结果一模一样)。
|
|
147
|
-
// `.auditignore` 只在 respectAuditIgnore 时叠加(审计豁免语义,见下方 git 分支注释)。
|
|
148
|
-
const gitIgnorePath = join(root, '.gitignore');
|
|
149
|
-
const auditIgnorePath = join(root, '.auditignore');
|
|
150
|
-
const parts = [];
|
|
151
|
-
const gitSrc = readIgnoreFileCached(gitIgnorePath);
|
|
152
|
-
if (gitSrc !== null) parts.push(gitSrc);
|
|
153
|
-
if (respectAuditIgnore) {
|
|
154
|
-
const auditSrc = readIgnoreFileCached(auditIgnorePath);
|
|
155
|
-
// 细粒度条目(路径 : 规则)只豁免指定规则,**不能**让文件整体跳过 ⇒ 采集期剔除这些行
|
|
156
|
-
if (auditSrc !== null) parts.push(splitAuditIgnore(auditSrc).wholeText);
|
|
157
|
-
}
|
|
158
|
-
if (!parts.length) return null;
|
|
159
|
-
let rules;
|
|
160
|
-
try {
|
|
161
|
-
rules = parseGitignore(parts.join('\n'));
|
|
162
|
-
} catch {
|
|
163
|
-
return null;
|
|
164
|
-
}
|
|
165
|
-
if (!rules.length) return null;
|
|
166
|
-
const ignored = new Set();
|
|
167
|
-
/**
|
|
168
|
-
* 处理一个目录项(抽出以降低 walkDirs 的嵌套深度;读起来是「目录→剪枝/递归、文件→判规则」两件事)。
|
|
169
|
-
* 注意 walkDirs 在下方定义:两者同作用域,调用发生在定义之后,闭包取值安全。
|
|
170
|
-
*/
|
|
171
|
-
const handleEntry = (dir, en) => {
|
|
172
|
-
// 与 git 路径一致:枚举阶段只用硬编码基线跳过(yml 黑名单在此跳过会让白名单恢复失效)
|
|
173
|
-
if (HARDCODED_SKIP.has(en.name)) return;
|
|
174
|
-
const rel = dir ? `${dir}/${en.name}` : en.name;
|
|
175
|
-
if (en.isDirectory()) {
|
|
176
|
-
if (isIgnoredByRules(rules, rel, true)) { ignored.add(rel); return; } // 命中即整棵剪枝
|
|
177
|
-
walkDirs(rel);
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
// **文件级规则**也要收(*.sh / lib/client.js 这类):原来这里 `if (!en.isDirectory()) continue;`
|
|
181
|
-
// 直接跳过文件 ⇒ 文件级 .auditignore 规则在非 git 目录下永远不生效
|
|
182
|
-
// (实测 test-gitignore-match 的端到端用例失败:非 git 下 *.sh 未被豁免)。
|
|
183
|
-
if (isIgnoredByRules(rules, rel, false)) ignored.add(rel);
|
|
184
|
-
};
|
|
185
|
-
const walkDirs = (dir) => {
|
|
186
|
-
let entries;
|
|
187
|
-
try { entries = readdirSync(join(root, dir), { withFileTypes: true }); } catch { return; }
|
|
188
|
-
for (const en of entries) handleEntry(dir, en);
|
|
189
|
-
};
|
|
190
|
-
walkDirs('');
|
|
191
|
-
return ignored;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* 收集 git 忽略文件相对路径集合(git check-ignore --stdin 批量判定)。
|
|
196
|
-
* 修复 1.0.4 缺陷:原实现以空 stdin 调用 check-ignore,从未传入文件路径 → 忽略集恒空 → gitignore 感知失效
|
|
197
|
-
* (被忽略文件全被扫入,大仓库性能爆炸 + 私密文件误入)。按 full-scan 语义正确实现:
|
|
198
|
-
* 1) git rev-parse 探活(非 git 目录返回 null = 不启用忽略判定)
|
|
199
|
-
* 2) 递归收集全部文件相对路径,一次性喂给 check-ignore --stdin(尊重 .gitignore 全部语法含 negation)
|
|
200
|
-
* 3) 输出 = 被忽略的路径集合;按 repo 根缓存,避免递归重复 spawn
|
|
201
|
-
* @param {string} root git 仓库根目录
|
|
202
|
-
* @returns {Set<string>|null} 被忽略路径集合;非 git 目录/失败返回 null
|
|
203
|
-
*/
|
|
204
|
-
function tryLoadGitIgnoreSet(root, respectAuditIgnore = true) {
|
|
205
|
-
// 缓存键要带上开关:否则「尊重 .auditignore」与「不尊重」两次调用会互相污染
|
|
206
|
-
const cacheKey = `${root}|${respectAuditIgnore}`;
|
|
207
|
-
if (ignoreCache.has(cacheKey)) return ignoreCache.get(cacheKey);
|
|
208
|
-
let ignoreSet = null;
|
|
209
|
-
try {
|
|
210
|
-
const probe = spawnSync('git', [...GIT_QUOTEPATH_ARGS, '-C', root, 'rev-parse', '--is-inside-work-tree'], {
|
|
211
|
-
encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: GIT_PROBE_TIMEOUT_MS,
|
|
212
|
-
});
|
|
213
|
-
if (probe.status !== 0 || String(probe.stdout || '').trim() !== 'true') {
|
|
214
|
-
// 非 git 目录的 `.auditignore` 兜底。原先此处直接返回 null,
|
|
215
|
-
// 导致 `.auditignore` 仅在 git 仓库生效——同一个 `*.sh` 规则在 git init 前后行为相反,
|
|
216
|
-
// 解压的源码包/临时导出目录/未 init 的工程里该文件形同不存在(实测确认)。
|
|
217
|
-
// 改为用纯 JS 匹配器(lib/audit/gitignore-match.js)解析 `.auditignore`,
|
|
218
|
-
// 按**目录**预计算忽略集,与 git 路径返回同构的 Set,下游无感知。
|
|
219
|
-
// 非 git 目录只有 `.auditignore` 可用:调用方要求「不尊重审计豁免」时直接返回空集
|
|
220
|
-
// (架构事实提取走这条——它要的是「仓库里有什么代码」,不是「审计扫哪些」)
|
|
221
|
-
if (!respectAuditIgnore) { ignoreCache.set(cacheKey, null); return null; }
|
|
222
|
-
const fallback = tryLoadAuditIgnoreFallback(root, respectAuditIgnore);
|
|
223
|
-
ignoreCache.set(cacheKey, fallback);
|
|
224
|
-
return fallback;
|
|
225
|
-
}
|
|
226
|
-
// `.auditignore` 审计豁免文件(复用 .gitignore 解析方式)——根目录存在该文件时,
|
|
227
|
-
// 把它作为 git core.excludesFile 追加进 check-ignore 判定(与 .gitignore 叠加生效;
|
|
228
|
-
// 实测 .gitignore 的 node_modules/ 与 .auditignore 的 generated/ 同时被忽略)。
|
|
229
|
-
// 语法 = gitignore 语法(目录规则 generated/ 整棵豁免、`*.lock` 文件豁免、`!` 白名单恢复)。
|
|
230
|
-
const auditIgnorePath = join(root, '.auditignore');
|
|
231
|
-
// 开关:`respectAuditIgnore=false` 时**不叠加** `.auditignore`(架构事实提取用)——
|
|
232
|
-
// 审计豁免的语义是「别对它报误报」,不是「它不是代码」;实测把它当排除项会让
|
|
233
|
-
// adapters/KToolBox-webui.js 这类被豁免的文件整片从架构图里消失。
|
|
234
|
-
const hasAuditIgnore = respectAuditIgnore && existsSync(auditIgnorePath);
|
|
235
|
-
const ignoreExtraArgs = hasAuditIgnore ? ['-c', `core.excludesFile=${auditIgnoreExcludesFile(root, auditIgnorePath)}`] : [];
|
|
236
|
-
// 修复(大仓库忽略失效):原实现枚举**全部文件**路径喂 check-ignore——大仓
|
|
237
|
-
// (如 DeepSeekHarness-NAS 9.9 万个文件)输入过大导致 spawnSync 超时被 SIGTERM,status=null
|
|
238
|
-
// 时仍用**残缺的 stdout** 构造忽略集合 → 忽略集不完整 → 被 .gitignore 忽略的 src/ 等
|
|
239
|
-
// 整棵子树漏进审计(用户看到「全量扫描有 /src」)。
|
|
240
|
-
// 改为:① 只枚举**目录**(数量少一个量级)② 逐个目录用 check-ignore -q 判定
|
|
241
|
-
// ③ 命中即整棵跳过;文件级再兜一次判定,保证「子文件夹也忽略」。
|
|
242
|
-
const ignoredDirs = new Set();
|
|
243
|
-
const allDirs = [];
|
|
244
|
-
const allFiles = [];
|
|
245
|
-
const walkDirs = (dir) => {
|
|
246
|
-
let es;
|
|
247
|
-
try { es = readdirSync(join(root, dir), { withFileTypes: true }); } catch { return; }
|
|
248
|
-
for (const en of es) {
|
|
249
|
-
// 枚举忽略集时只用**硬编码基线**(node_modules/.git):yml 黑名单(build 等)不能在此跳过——
|
|
250
|
-
// 否则 build/keep(白名单恢复)与 build/drop(真黑名单)都不会被枚举,gitignore 判定全错。
|
|
251
|
-
if (HARDCODED_SKIP.has(en.name)) continue;
|
|
252
|
-
const rel = join(dir, en.name).split(sep).join('/');
|
|
253
|
-
if (en.isDirectory()) {
|
|
254
|
-
allDirs.push(rel);
|
|
255
|
-
walkDirs(join(dir, en.name));
|
|
256
|
-
} else {
|
|
257
|
-
allFiles.push(rel);
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
};
|
|
261
|
-
walkDirs('');
|
|
262
|
-
// 批量判定:一次 check-ignore --stdin 喂**目录 + 文件**。
|
|
263
|
-
// 原来只喂目录 ⇒ 集合里只有「被忽略的目录」⇒ **文件级规则**(lib/client.js、*.log 这类)永远命中不了,
|
|
264
|
-
// 于是下游又加了一层「事后过滤」去补,而两层参数还不一致(一个有 --no-index 一个没有)
|
|
265
|
-
// ⇒ 行为互相掩盖。这是本文件「四层忽略补丁」的结构性根源,故在此一次喂全、只做一次判定。
|
|
266
|
-
// 直接拼成 stdin 文本,避免 [...allDirs, ...allFiles] 把两个大数组各复制一遍
|
|
267
|
-
// (性能规则 performance/memory-bomb 命中「展开多个大数组会一次性创建新数组」;
|
|
268
|
-
// 拼接结果与 spread + join('\n') 逐字节等价,大仓库下少一次整表复制)
|
|
269
|
-
const totalPaths = allDirs.length + allFiles.length;
|
|
270
|
-
const stdinPaths = totalPaths
|
|
271
|
-
? (allDirs.length && allFiles.length
|
|
272
|
-
? `${allDirs.join('\n')}\n${allFiles.join('\n')}`
|
|
273
|
-
: (allDirs.length ? allDirs.join('\n') : allFiles.join('\n')))
|
|
274
|
-
: '';
|
|
275
|
-
if (totalPaths) {
|
|
276
|
-
const r = spawnSync('git', [...GIT_QUOTEPATH_ARGS, '-C', root, ...ignoreExtraArgs, 'check-ignore', '--stdin', '--no-index'], {
|
|
277
|
-
input: stdinPaths, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: IGNORE_BATCH_TIMEOUT_MS,
|
|
278
|
-
});
|
|
279
|
-
// status 为 null(超时/被杀)时**不采信残缺输出**:保守视为无忽略信息,避免「漏忽略」
|
|
280
|
-
if (r.status === 0 || r.status === 1) {
|
|
281
|
-
for (const line of String(r.stdout || '').split('\n')) {
|
|
282
|
-
const t = line.trim().replace(/\/+$/, '');
|
|
283
|
-
if (t) ignoredDirs.add(t);
|
|
284
|
-
}
|
|
285
|
-
} else {
|
|
286
|
-
// 兜底:批量失败则逐个目录判定(只在异常路径触发,保证正确性优先)
|
|
287
|
-
for (const dirRel of allDirs) {
|
|
288
|
-
const probeResult = spawnSync('git', [...GIT_QUOTEPATH_ARGS, '-C', root, ...ignoreExtraArgs, 'check-ignore', '-q', '--', dirRel], {
|
|
289
|
-
encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: IGNORE_SINGLE_TIMEOUT_MS,
|
|
290
|
-
});
|
|
291
|
-
if (probeResult.status === 0) ignoredDirs.add(dirRel);
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
ignoreSet = ignoredDirs;
|
|
296
|
-
} catch {
|
|
297
|
-
ignoreSet = null;
|
|
298
|
-
}
|
|
299
|
-
ignoreCache.set(cacheKey, ignoreSet);
|
|
300
|
-
return ignoreSet;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
/**
|
|
304
|
-
* 递归收集文本文件。
|
|
305
|
-
* @param {string} dir 扫描目录
|
|
306
|
-
* @param {object} opts { depth, gitIgnoreRoot, includeIgnored }
|
|
307
|
-
* @returns {Array<{path, ext, full}>}
|
|
308
|
-
*/
|
|
309
|
-
/** 目录是否硬编码基线跳过(node_modules/.git——机器依赖/内部元数据,恒不进审计)。 */
|
|
310
|
-
function isHardSkipped(name) {
|
|
311
|
-
return HARDCODED_SKIP.has(name);
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/** gitignore 判定:目录/文件是否在忽略集内(includeIgnored 或非 git 根时 false)。 */
|
|
315
|
-
function computeGitIgnored(full, gitIgnoreRoot, includeIgnored, respectAuditIgnore = true) {
|
|
316
|
-
if (includeIgnored || !gitIgnoreRoot) return false;
|
|
317
|
-
const relDir = relative(gitIgnoreRoot, full).replace(/\\/g, '/');
|
|
318
|
-
const igSet = tryLoadGitIgnoreSet(gitIgnoreRoot, respectAuditIgnore);
|
|
319
|
-
return !!(igSet && igSet.has(relDir));
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/** yml 黑名单目录是否跳过:命中且 git 未忽略(白名单恢复)→ 保留(false);否则跳过(true)。 */
|
|
323
|
-
function shouldSkipDirByYml(name, ignoredByGit, gitIgnoreRoot) {
|
|
324
|
-
if (!SKIP_DIRS.has(name)) return false;
|
|
325
|
-
// 黑名单命中:git 仓库里未被 gitignore 忽略(白名单恢复)→ 保留;否则跳过
|
|
326
|
-
return !(gitIgnoreRoot && !ignoredByGit);
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
/** 文件级 gitignore 兜底:父目录在忽略集内 → 跳过(防「直接以被忽略目录为扫描根」边界)。 */
|
|
330
|
-
function isFileGitIgnored(full, gitIgnoreRoot, includeIgnored, respectAuditIgnore = true) {
|
|
331
|
-
if (includeIgnored || !gitIgnoreRoot) return false;
|
|
332
|
-
const rel = relative(gitIgnoreRoot, full).replace(/\\/g, '/');
|
|
333
|
-
const set = tryLoadGitIgnoreSet(gitIgnoreRoot, respectAuditIgnore);
|
|
334
|
-
if (!set) return false;
|
|
335
|
-
if (set.has(rel)) return true;
|
|
336
|
-
const seg = rel.split('/');
|
|
337
|
-
for (let i = seg.length - 1; i > 0; i -= 1) {
|
|
338
|
-
if (set.has(seg.slice(0, i).join('/'))) return true;
|
|
339
|
-
}
|
|
340
|
-
return false;
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
export async function collectTextFiles(dir, { depth = 10, gitIgnoreRoot = null, includeIgnored = false, testExemptRoot = null, respectAuditIgnore = true } = {}) {
|
|
344
|
-
// ── git 快路径(2026-11-01)───────────────────────────────────────────────
|
|
345
|
-
// 背景(外部会话实测移交):CIFS/SMB 挂载上的仓库,一次 diff 审计卡 9 分钟不返回,
|
|
346
|
-
// ps 里看不到 git 子进程——瓶颈其实是**文件系统遍历**:实测某仓 231 个文本文件,
|
|
347
|
-
// readdir+stat 递归要 103.8s(sys 29s,全耗在跨网 stat),而 `git ls-files` 列 733 个路径只要 0.046s。
|
|
348
|
-
// 做法:git 仓库里改用 git 自己维护的路径清单(已跟踪 + 未跟踪未忽略),
|
|
349
|
-
// 再用**同一套过滤**(扩展名/大小/跳过目录/测试豁免)筛出文本文件;非 git 目录仍走原遍历。
|
|
350
|
-
// `DSH_AUDIT_NO_GIT_FASTPATH=1` 可强制回退旧路径(排查用)。
|
|
351
|
-
if (process.env.DSH_AUDIT_NO_GIT_FASTPATH !== '1') {
|
|
352
|
-
const fast = gitListTextFiles(dir, { gitIgnoreRoot, includeIgnored, testExemptRoot, respectAuditIgnore });
|
|
353
|
-
if (fast) return fast;
|
|
354
|
-
}
|
|
355
|
-
const out = [];
|
|
356
|
-
await walk(dir, 0);
|
|
357
|
-
// `.auditignore` **文件级**豁免(目录级已在 walk 剪枝)——收集完成后把
|
|
358
|
-
// 已收集的文件路径批量喂 check-ignore(带 core.excludesFile 追加 .auditignore),
|
|
359
|
-
// 命中 `src/vendor.js` / `*.lock` 等文件级规则即剔除(收集到的文本文件数少,一次 spawn 可接受)。
|
|
360
|
-
// 目录规则(generated/)已由 tryLoadGitIgnoreSet 的目录集整棵跳过,此处只补文件级。
|
|
361
|
-
// 修复(theme 全量审计漏忽略):文件级判定门控从「存在 .auditignore」放宽为
|
|
362
|
-
// 「git 仓库」——.gitignore 的**文件级规则**(lib/client.js / *.log / 任务.md)目录级剪枝
|
|
363
|
-
// 覆盖不到,此前仅在 .auditignore 存在时补判,普通 .gitignore 的文件规则全部漏进审计
|
|
364
|
-
// (实测 theme 的 lib/client.js 构建产物与任务.md 被扫入)。git 路径下无条件批量
|
|
365
|
-
// check-ignore(有 .auditignore 则追加为 core.excludesFile,与 .gitignore 叠加);
|
|
366
|
-
// 非 git 且无 .auditignore 时无忽略信息(tryLoadGitIgnoreSet=null)保持跳过。
|
|
367
|
-
// 「事后过滤」层已删除(重新设计第 2 步)。
|
|
368
|
-
// 它的职责(补**文件级** .gitignore/.auditignore 规则)已并入**建集阶段**:建集现在同时喂
|
|
369
|
-
// 目录与文件、并统一带 `--no-index`,一次判定即覆盖目录与文件两级规则。
|
|
370
|
-
// 留着它会出现「两层参数不同、行为互相掩盖」——实测 adapters/KToolBox-webui.js 长期被莫名剔除,
|
|
371
|
-
// 排查了 6 轮才定位到是这两层在打架。忽略策略今后由 `ignorePolicy` 参数**显式表达**,
|
|
372
|
-
// 不再散落在 includeIgnored / respectAuditIgnore 等多处 flag 上。
|
|
373
|
-
return out;
|
|
374
|
-
|
|
375
|
-
// 递归遍历改异步:大仓库上逐目录 readdirSync + 逐项 statSync 会阻塞事件循环
|
|
376
|
-
async function walk(cur, level) {
|
|
377
|
-
if (level > depth) return;
|
|
378
|
-
// .test 空文件豁免(1.0.5):整目录扫描跳过(含子目录),专为测试 fixture 目录设计
|
|
379
|
-
if (testExemptRoot && cur !== testExemptRoot && isTestExemptDir(testExemptRoot, relative(testExemptRoot, cur))) return;
|
|
380
|
-
let entries;
|
|
381
|
-
try { entries = await readdir(cur); } catch { return; }
|
|
382
|
-
for (const name of entries) {
|
|
383
|
-
const full = join(cur, name);
|
|
384
|
-
let st;
|
|
385
|
-
try { st = await stat(full); } catch { continue; }
|
|
386
|
-
if (st.isDirectory()) {
|
|
387
|
-
// 「黑名单初筛 + 白名单补充」:
|
|
388
|
-
// 1) 硬编码基线(node_modules/.git)**绝对跳过**——机器依赖/内部元数据目录,
|
|
389
|
-
// 不受 gitignore 白名单影响(npm 包树里 node_modules 恒不该进审计)。
|
|
390
|
-
// 2) yml 黑名单关键词(build/dist 等)候选跳过;若 gitignore 判定该目录**未忽略**
|
|
391
|
-
// (被 ! 白名单恢复,如 server/project/* + !blueprint/、/build/* + !/build/keep/),
|
|
392
|
-
// 则保留进入——黑名单不能压过 gitignore 白名单。
|
|
393
|
-
if (isHardSkipped(name)) continue;
|
|
394
|
-
let ignoredByGit = computeGitIgnored(full, gitIgnoreRoot, includeIgnored, respectAuditIgnore);
|
|
395
|
-
if (shouldSkipDirByYml(name, ignoredByGit, gitIgnoreRoot)) continue;
|
|
396
|
-
// 非黑名单目录:被 gitignore 忽略 → 整棵跳过(原逻辑)
|
|
397
|
-
if (ignoredByGit) continue;
|
|
398
|
-
await walk(full, level + 1);
|
|
399
|
-
continue;
|
|
400
|
-
}
|
|
401
|
-
if (!st.isFile()) continue;
|
|
402
|
-
// 1MB 上限:超大文件(会话归档/大 JSON/二进制伪装文本)跳过,防读入拖死进程
|
|
403
|
-
if (st.size > MAX_FILE_SIZE) continue;
|
|
404
|
-
const ext = extname(full).replace(/^\./, '');
|
|
405
|
-
const isText = name.endsWith('.gitignore') || name.endsWith('.npmrc') || TEXT_EXT.has(ext);
|
|
406
|
-
if (!isText) continue;
|
|
407
|
-
// gitignore 感知(文件级兜底):父目录若在忽略集内也应跳过(目录遍历已整棵跳过,
|
|
408
|
-
// 此处兜住「直接以被忽略目录为扫描根」等边界)
|
|
409
|
-
if (isFileGitIgnored(full, gitIgnoreRoot, includeIgnored, respectAuditIgnore)) continue;
|
|
410
|
-
out.push({ path: relative(dir, full).replace(/\\/g, '/'), ext, full });
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* 用 `git ls-files` 枚举文本文件(CIFS 快路径,见 collectTextFiles 顶部说明)。
|
|
417
|
-
*
|
|
418
|
-
* 语义对齐:`--cached --others --exclude-standard` = 已跟踪 ∪ 未跟踪但未被忽略,
|
|
419
|
-
* 与「遍历时按 check-ignore 剔除」等价;`.auditignore` 通过 core.excludesFile 叠加。
|
|
420
|
-
* 过滤沿用原遍历的那一套:硬跳过目录、yml 黑名单目录、测试豁免目录、扩展名白名单、
|
|
421
|
-
* 1MB 上限(这里需要 stat,但只对**扩展名通过**的候选做,数量比全量条目少一个量级)。
|
|
422
|
-
* @returns {Array<{path:string, ext:string, full:string}>|null} 非 git 仓库/命令失败 → null(回退遍历)
|
|
423
|
-
*/
|
|
424
|
-
function gitListTextFiles(dir, { gitIgnoreRoot = null, includeIgnored = false, testExemptRoot = null, respectAuditIgnore = true } = {}) {
|
|
425
|
-
const root = gitIgnoreRoot || dir;
|
|
426
|
-
try {
|
|
427
|
-
if (!isGitRepo(root)) return null;
|
|
428
|
-
const cfgArgs = [];
|
|
429
|
-
const auditIgnorePath = join(root, '.auditignore');
|
|
430
|
-
if (respectAuditIgnore && existsSync(auditIgnorePath)) {
|
|
431
|
-
cfgArgs.push('-c', `core.excludesFile=${auditIgnoreExcludesFile(root, auditIgnorePath)}`);
|
|
432
|
-
}
|
|
433
|
-
const args = ['ls-files', '-z'];
|
|
434
|
-
if (includeIgnored) args.push('--cached', '--others');
|
|
435
|
-
else args.push('--cached', '--others', '--exclude-standard');
|
|
436
|
-
const res = spawnSync('git', [...GIT_GLOBAL_ARGS, ...cfgArgs, '-C', root, ...args], {
|
|
437
|
-
encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: IGNORE_BATCH_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024,
|
|
438
|
-
});
|
|
439
|
-
if (res.status !== 0 || !res.stdout) return null;
|
|
440
|
-
const ymlSkip = getSkipSet();
|
|
441
|
-
// `ls-files --cached` 会列出**已跟踪但被 ignore** 的文件(ignore 只影响未跟踪项)。
|
|
442
|
-
// `.auditignore` 的语义是「照常入库但不审」,那些文件恰恰是已跟踪的 ⇒ 必须再补一刀
|
|
443
|
-
// 批量 check-ignore(**--no-index**:强制按路径匹配规则,已跟踪文件同样命中)。
|
|
444
|
-
// 一次 --stdin 调用,几百个路径在 CIFS 上也是毫秒级。
|
|
445
|
-
const ignoredSet = new Set();
|
|
446
|
-
if (!includeIgnored) {
|
|
447
|
-
const rels = String(res.stdout).split('\0').filter(Boolean);
|
|
448
|
-
if (rels.length) {
|
|
449
|
-
const gi = spawnSync('git', [...GIT_GLOBAL_ARGS, ...cfgArgs, '-C', root, 'check-ignore', '--stdin', '--no-index'], {
|
|
450
|
-
input: rels.join('\n'), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: IGNORE_BATCH_TIMEOUT_MS,
|
|
451
|
-
});
|
|
452
|
-
if (gi.status === 0 || gi.status === 1) {
|
|
453
|
-
for (const line of String(gi.stdout || '').split('\n')) if (line.trim()) ignoredSet.add(line.trim());
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
const out = [];
|
|
458
|
-
for (const rel of String(res.stdout).split('\0')) {
|
|
459
|
-
if (!rel) continue;
|
|
460
|
-
if (ignoredSet.has(rel)) continue; // 已跟踪但被 .gitignore/.auditignore 命中
|
|
461
|
-
const segs = rel.split('/');
|
|
462
|
-
// 硬跳过目录(node_modules/.git)——任一目录段命中即整条跳
|
|
463
|
-
if (segs.slice(0, -1).some((d) => HARDCODED_SKIP.has(d))) continue;
|
|
464
|
-
// yml 黑名单目录:**只在 includeIgnored 时**按名单跳过。
|
|
465
|
-
// 语义必须与遍历路径的 shouldSkipDirByYml 对齐:它只在「该目录被 gitignore 忽略」或
|
|
466
|
-
// 「非 git 目录」时才跳,git 仓库里被跟踪的 build/ 等目录是**保留**的。
|
|
467
|
-
// 快路径的来源是 ls-files(--exclude-standard 已排除被忽略项)⇒ 默认情形一律保留,
|
|
468
|
-
// 否则会静默缩小扫描面(实测某仓少 17 个文件:build/* 16 个 + tools/pnpm/dist/worker.js)。
|
|
469
|
-
if (includeIgnored && segs.slice(0, -1).some((d) => ymlSkip.has && ymlSkip.has(d))) continue;
|
|
470
|
-
const full = join(root, rel);
|
|
471
|
-
// 挂载根与被审计目录可能不同(审计子目录):只收 dir 之下的
|
|
472
|
-
const relToDir = relative(dir, full).replace(/\\/g, '/');
|
|
473
|
-
if (!relToDir || relToDir.startsWith('..')) continue;
|
|
474
|
-
const name = segs[segs.length - 1];
|
|
475
|
-
if (testExemptRoot && isTestExemptDir(testExemptRoot, relToDir)) continue;
|
|
476
|
-
const ext = extname(name).replace(/^\./, '');
|
|
477
|
-
const isText = name.endsWith('.gitignore') || name.endsWith('.npmrc') || TEXT_EXT.has(ext);
|
|
478
|
-
if (!isText) continue;
|
|
479
|
-
let st;
|
|
480
|
-
try { st = statSync(full); } catch { continue; }
|
|
481
|
-
if (!st.isFile() || st.size > MAX_FILE_SIZE) continue;
|
|
482
|
-
out.push({ path: relToDir, ext, full });
|
|
483
|
-
}
|
|
484
|
-
return out;
|
|
485
|
-
} catch { return null; }
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
/** 判断目录是否为 git 仓库(有 .git)。 */
|
|
489
|
-
export function isGitRepo(dir) {
|
|
490
|
-
return existsSync(join(dir, '.git')) || existsSync(join(dir, '.git', 'HEAD'));
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
/**
|
|
494
|
-
* 收集 git 仓库工作区变动文件(git status --porcelain)。
|
|
495
|
-
* @param {string} repoPath git 仓库目录
|
|
496
|
-
* @returns {Array<{rel, full, status}>|null} 非 git 仓库或 git 失败返回 null(调用方退化为 full)
|
|
497
|
-
* status:A=新增 M=修改 D=删除 R=重命名 ??=未跟踪
|
|
498
|
-
*/
|
|
499
|
-
export function collectChangedFiles(repoPath) {
|
|
500
|
-
if (!isGitRepo(repoPath)) return null;
|
|
501
|
-
try {
|
|
502
|
-
// 显式捕获 stderr(execFileSync 未设 stdio 时异常会把 git stderr 直通父进程)
|
|
503
|
-
const out = execFileSync('git', [...GIT_GLOBAL_ARGS, '-C', repoPath, 'status', '--porcelain'], {
|
|
504
|
-
encoding: 'utf8', timeout: GIT_PROBE_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'pipe'],
|
|
505
|
-
});
|
|
506
|
-
const files = [];
|
|
507
|
-
for (const line of out.split('\n')) {
|
|
508
|
-
if (!line.trim()) continue;
|
|
509
|
-
const status = line.slice(0, 2).trim() || 'M';
|
|
510
|
-
let rel = line.slice(3);
|
|
511
|
-
// 引号包裹(含空格/非 ASCII):取引号内内容(不处理 \ooo 转义,中文文件名原样)
|
|
512
|
-
const quoted = rel.match(/^"((?:[^"\\]|\\.)*)"/);
|
|
513
|
-
if (quoted) rel = quoted[1].replace(/\\([\\"])/g, '$1');
|
|
514
|
-
else if (rel.includes(' -> ')) rel = rel.split(' -> ').pop(); // 重命名取新路径
|
|
515
|
-
if (!rel) continue;
|
|
516
|
-
// 未跟踪目录(?? dir/):git status --porcelain 只显示目录本身,需展开为目录内文件,
|
|
517
|
-
// 否则审计漏掉整目录(对齐 getDiff 用 git ls-files --others 展开的行为)。
|
|
518
|
-
if (status === '??' && rel.endsWith('/')) {
|
|
519
|
-
const inside = execFileSync('git', [...GIT_GLOBAL_ARGS, '-C', repoPath, 'ls-files', '--others', '--exclude-standard', '--', rel], {
|
|
520
|
-
encoding: 'utf8', timeout: GIT_PROBE_TIMEOUT_MS,
|
|
521
|
-
});
|
|
522
|
-
for (const p of inside.split('\n').filter(Boolean)) {
|
|
523
|
-
files.push({ rel: p, full: join(repoPath, p), status });
|
|
524
|
-
}
|
|
525
|
-
continue;
|
|
526
|
-
}
|
|
527
|
-
files.push({ rel, full: join(repoPath, rel), status });
|
|
528
|
-
}
|
|
529
|
-
// .test 空文件目录豁免对 changed 审计同样生效——与全仓收集
|
|
530
|
-
// (collectTextFiles testExemptRoot)对齐:test fixture 目录(故意构造的坏样本)
|
|
531
|
-
// 在 diff 审计里也应完全跳过,否则「改过 test 文件 → 整个文件进 changed 范围 →
|
|
532
|
-
// 黑名单词样本/超长函数样本被扫出」误拦提交。
|
|
533
|
-
const kept = files.filter((f) => !isTestExemptDir(repoPath, f.rel));
|
|
534
|
-
// `.auditignore` 同样要作用于**变动模式**:此前它只在全仓收集(collectTextFiles)里生效,
|
|
535
|
-
// 于是「要入库但不该被自家规则审」的文件(生成的 HTML、内置 vendor 代码、手写 DOM 的 client.js)
|
|
536
|
-
// 一旦被改动就进 changed 范围并被自家规则拦下提交——实测 test-audit-bad-file 因此转红。
|
|
537
|
-
// 做法与全仓收集完全一致:把已收集路径批量喂 check-ignore(有 .auditignore 则追加为 excludesFile)。
|
|
538
|
-
const auditIgnorePath = join(repoPath, '.auditignore');
|
|
539
|
-
if (!existsSync(auditIgnorePath) || !kept.length) return kept;
|
|
540
|
-
try {
|
|
541
|
-
const r = spawnSync(
|
|
542
|
-
'git',
|
|
543
|
-
[...GIT_QUOTEPATH_ARGS, '-C', repoPath, '-c', `core.excludesFile=${auditIgnoreExcludesFile(repoPath, auditIgnorePath)}`,
|
|
544
|
-
'check-ignore', '--stdin', '--no-index'],
|
|
545
|
-
{ input: kept.map((f) => f.rel).join('\n'), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: IGNORE_BATCH_TIMEOUT_MS },
|
|
546
|
-
);
|
|
547
|
-
if (r.status === 0 || r.status === 1) {
|
|
548
|
-
const ignored = new Set(String(r.stdout || '').split('\n').filter(Boolean));
|
|
549
|
-
return kept.filter((f) => !ignored.has(f.rel));
|
|
550
|
-
}
|
|
551
|
-
} catch { /* 判定失败保留原结果 */ }
|
|
552
|
-
return kept;
|
|
553
|
-
} catch {
|
|
554
|
-
return null; // git 不可用 → 调用方退化为 full
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
/** 判定是否为文本文件(TEXT_EXT 白名单 + 1MB 上限;png/jpg 等二进制扩展名 → false)。 */
|
|
559
|
-
export function isTextFile(full) {
|
|
560
|
-
try {
|
|
561
|
-
const st = statSync(full);
|
|
562
|
-
if (st.size > MAX_FILE_SIZE) return false;
|
|
563
|
-
} catch { return false; }
|
|
564
|
-
const ext = extname(full).replace(/^\./, '');
|
|
565
|
-
const base = full.split('/').pop() || '';
|
|
566
|
-
// bugfix:点文件(.env/.env.local 等)extname 对它们取的是最后一段
|
|
567
|
-
// (.env.local → '.local'),触发 ext 白名单匹配错误;同时 .tmp-x.js 这类
|
|
568
|
-
// 「点开头但带真实扩展名」的文件不能误伤(extname 已能取到 .js)。
|
|
569
|
-
// 判定顺序:①extname 有合法扩展名且命中白名单 → true(.tmp-x.js / .foo.yaml)
|
|
570
|
-
// ②extname 为空或未命中 → 点文件取「去首点后第一段」(.env → env;.env.local → env)
|
|
571
|
-
// ③仍不中 → false。
|
|
572
|
-
const extHit = TEXT_EXT.has(ext);
|
|
573
|
-
const effExt = extHit
|
|
574
|
-
? ext
|
|
575
|
-
: (base.startsWith('.') ? base.slice(1).split('.')[0] : '');
|
|
576
|
-
return base.endsWith('.gitignore') || base.endsWith('.npmrc') || TEXT_EXT.has(effExt);
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
/* ───────── 审计期间的文本读取缓存(性能优化,2026-10-09) ─────────
|
|
580
|
-
* 为什么:全量审计的 fs 画像实测 `readFileSync` **1659 次 / 252 文件 ≈ 6.6×** ✗ ——
|
|
581
|
-
* 同一个文件会在收集、逐文件审计、覆盖率统计等多处被反复读,而 `readText` 是审计路径的统一读入口。
|
|
582
|
-
* 正确性设计:缓存条目带 **size + mtimeMs 指纹**,每次命中前 statSync 复核 ⇒ 文件被改动自动失效,
|
|
583
|
-
* 既不需要调用方维护"何时清缓存"(易漏),也不可能读到旧内容(比"每轮开头 clear"的写法安全)。
|
|
584
|
-
* 代价是每次读多一次 statSync(微秒级),换来少一次整文件读取(NAS/CIFS 上差距很大)。
|
|
585
|
-
* 内存:按累计字符数设预算(env DSH_GIT_PUSH_READ_CACHE_BYTES,默认 16MiB),超限整体清空(退化为不缓存)。
|
|
586
|
-
*/
|
|
587
|
-
const READ_CACHE = new Map();
|
|
588
|
-
let READ_CACHE_BYTES = 0;
|
|
589
|
-
|
|
590
|
-
/** 清空读取缓存(测试用;正常运行无需调用——指纹复核已保证正确性)。 */
|
|
591
|
-
export function clearReadCache() {
|
|
592
|
-
READ_CACHE.clear();
|
|
593
|
-
READ_CACHE_BYTES = 0;
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
/** 读文件(UTF-8,失败返回 null)。同一文件在指纹未变时不重复落盘读。 */
|
|
597
|
-
export function readText(full) {
|
|
598
|
-
let st;
|
|
599
|
-
try { st = statSync(full); } catch { return null; } // 与原来"读不到返回 null"一致(stat 失败必然也读不到)
|
|
600
|
-
const key = String(full);
|
|
601
|
-
const hit = READ_CACHE.get(key);
|
|
602
|
-
if (hit && hit.size === st.size && hit.mtimeMs === st.mtimeMs) return hit.text;
|
|
603
|
-
let text = null;
|
|
604
|
-
try { text = readFileSync(key, 'utf8'); } catch { return null; }
|
|
605
|
-
const max = Number(process.env.DSH_GIT_PUSH_READ_CACHE_BYTES || 16 * 1024 * 1024) || 16 * 1024 * 1024;
|
|
606
|
-
if (READ_CACHE_BYTES + text.length > max) { READ_CACHE.clear(); READ_CACHE_BYTES = 0; } // 超预算整体清空(只影响性能)
|
|
607
|
-
READ_CACHE.set(key, { size: st.size, mtimeMs: st.mtimeMs, text });
|
|
608
|
-
READ_CACHE_BYTES += text.length;
|
|
609
|
-
return text;
|
|
610
|
-
}
|