dsh-git-push 3.0.0 → 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 -48
- package/cli.mjs +4 -3
- package/lib/app/apply.js +11 -9
- package/lib/app/command-registry.js +4 -2
- package/lib/app/handlers/http-constants.js +8 -0
- package/lib/app/handlers/preprocess.js +3 -6
- package/lib/app/handlers/repo-actions.js +0 -1
- package/lib/app/handlers/repos.js +137 -10
- package/lib/app/handlers/settings.js +34 -15
- package/lib/app/index.js +1 -1
- package/lib/app/inject-text.js +3 -18
- package/lib/app/schema.js +20 -10
- package/lib/app/settings-bridge.js +60 -8
- package/lib/app/tool-call.js +26 -22
- package/lib/cli/commands-vcs.mjs +35 -1
- package/lib/cli/shared.mjs +1 -1
- 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 +584 -32
- package/lib/commit-push.js +63 -47
- package/lib/context/index.js +7 -5
- package/lib/core/config.js +1 -27
- package/lib/core/exec.js +2 -11
- package/lib/git/identity-rewrite.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/npm/install.js +1 -1
- package/lib/npm/registry.js +2 -2
- package/lib/plugin/auto-push.js +3 -6
- package/lib/preprocess/providers.js +5 -1
- package/lib/self/index.js +1 -1
- package/package.json +4 -7
- 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/lib/BUGFIX-NOTES-2026-09-14.md +0 -278
- package/lib/app/schema-preprocess.js +0 -42
- package/lib/user-requirements.json +0 -15
- package/scripts/build-client.mjs +0 -133
- package/scripts/bump-version.mjs +0 -178
- package/scripts/check.mjs +0 -205
- package/scripts/doc-func.mjs +0 -212
- package/scripts/doc-tree.mjs +0 -458
- package/scripts/doc-version.mjs +0 -149
- package/scripts/local-registry.mjs +0 -38
- package/scripts/scan-version.mjs +0 -125
- package/scripts/version-source.mjs +0 -173
|
@@ -12,22 +12,31 @@
|
|
|
12
12
|
//
|
|
13
13
|
// 退出码 1 **不等于**「本次提交被拦」:示例目录豁免、临时豁免、私有库豁免都属于 git 侧判定
|
|
14
14
|
// (依赖仓库语义 / 调用方参数 / GitHub 网络),引擎不知道也不该知道。所以本层只把
|
|
15
|
-
// 「引擎说有 blocker」如实映射成 blocked 标志,**最终拦截判定仍由
|
|
15
|
+
// 「引擎说有 blocker」如实映射成 blocked 标志,**最终拦截判定仍由 runPreprocess 用豁免规则做**。
|
|
16
16
|
//
|
|
17
17
|
// 失败一律 fail-closed(拒绝提交):引擎崩了 / 超时 / 退出码非 0/1 / stdout 解析不了,
|
|
18
18
|
// 都不能当成「审计通过」放行 —— 那是把红线交给「恰好没跑起来」。
|
|
19
19
|
|
|
20
20
|
import { spawn } from 'node:child_process';
|
|
21
|
+
import { createHash } from 'node:crypto';
|
|
22
|
+
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
23
|
+
import { tmpdir } from 'node:os';
|
|
24
|
+
import { join as joinPath } from 'node:path';
|
|
21
25
|
import { existsSync, accessSync, constants as fsConstants } from 'node:fs';
|
|
22
26
|
import { delimiter, isAbsolute, join, resolve } from 'node:path';
|
|
23
27
|
import { fileURLToPath } from 'node:url';
|
|
24
28
|
|
|
25
29
|
import { readSettings } from '../app/settings-bridge.js';
|
|
30
|
+
// 工作树快照用(阶段改动的差集比对;只读 git status,不做任何写操作)
|
|
31
|
+
import { gitRaw } from '../git/index.js';
|
|
26
32
|
// 超时默认值取单一来源:schema 默认值与运行期兜底必须是同一个数字(见 lib/app/constants.js)
|
|
27
33
|
import { PRE_COMMIT_TIMEOUT_MS_DEFAULT } from '../app/constants.js';
|
|
28
34
|
|
|
29
35
|
export { PRE_COMMIT_TIMEOUT_MS_DEFAULT };
|
|
30
36
|
|
|
37
|
+
/** 阶段回执里「命中拦截的文件清单」最多列几个:只是给个线索,完整清单在 audit.blocked 里。 */
|
|
38
|
+
const BLOCKED_FILES_PREVIEW_MAX = 20;
|
|
39
|
+
|
|
31
40
|
/** 内置轻量入口(相对插件根)。配置留空时用它。 */
|
|
32
41
|
|
|
33
42
|
|
|
@@ -41,7 +50,7 @@ export const PREPROCESS_CLI_REL = 'cli.mjs';
|
|
|
41
50
|
|
|
42
51
|
// 注意:这里不再写死具体实现的包名——包名属于 provider 定义(lib/preprocess/providers.js),
|
|
43
52
|
// 通用层只通过 provider 抽象拿它。将来换/加 provider 不需要改本文件。
|
|
44
|
-
import { resolveGateProvider, getProviderDefinition, DEFAULT_PROVIDER_ID } from '../preprocess/providers.js';
|
|
53
|
+
import { resolveGateProvider, resolveProvider, listProviderManifests, getProviderDefinition, DEFAULT_PROVIDER_ID } from '../preprocess/providers.js';
|
|
45
54
|
|
|
46
55
|
export { resolveGateProvider };
|
|
47
56
|
|
|
@@ -93,8 +102,7 @@ export function resolvePreCommitConfig(cfg = {}) {
|
|
|
93
102
|
// · command 空 + args 有值 → node + 配置里给的引擎脚本(args 里相对路径按插件根解析)
|
|
94
103
|
// · command 有值 + args 空 → 那是一个独立可执行文件(Go/Rust 单二进制就是这种形态,
|
|
95
104
|
// 此时**不能**塞我们自己的脚本路径进去)
|
|
96
|
-
// 缺省引擎 =
|
|
97
|
-
// 显式配置 command/args 时仍以配置为准(回滚与自定义引擎都走这条)。
|
|
105
|
+
// 缺省引擎 = 预处理实现的 CLI;显式配置 command/args 时以配置为准(换引擎只改配置)。
|
|
98
106
|
let args = configuredArgs;
|
|
99
107
|
if (!command && configuredArgs.length === 0) {
|
|
100
108
|
const entry = resolveGateProvider();
|
|
@@ -102,15 +110,140 @@ export function resolvePreCommitConfig(cfg = {}) {
|
|
|
102
110
|
// 错误信息里带上具体查过哪些路径(否则用户只看到"命令不存在",不知道该怎么办)。
|
|
103
111
|
args = entry.ok ? [entry.path] : [join(pluginRootDir(), '..', getProviderDefinition(DEFAULT_PROVIDER_ID).packageName, PREPROCESS_CLI_REL)];
|
|
104
112
|
}
|
|
105
|
-
// 是否仍是「内置旧引擎」(显式指回 plugins 自带 预处理实现 CLI 的回滚路径):
|
|
106
|
-
// 旧引擎不认 --visibility/--exempt-paths,也不会返回 blocked —— 传了会直接 exit 2。
|
|
107
|
-
// 两条路径都保留可用,才能做到「切调用但可回滚」。
|
|
108
113
|
const rawTimeout = Number(raw?.timeoutMs);
|
|
109
114
|
// 超时必须是正有限数:0 / 负数 / NaN 一律退回默认(0 表示「立刻超时」会让门禁永远失败)
|
|
110
115
|
const timeoutMs = Number.isFinite(rawTimeout) && rawTimeout > 0 ? Math.floor(rawTimeout) : PRE_COMMIT_TIMEOUT_MS_DEFAULT;
|
|
111
116
|
return { command, args, timeoutMs, source };
|
|
112
117
|
}
|
|
113
118
|
|
|
119
|
+
/**
|
|
120
|
+
* 旧版开关键名(历史配置里这个键就是「提交前检查开不开」)。
|
|
121
|
+
* 单独提常量是为了让「还在兼容什么」一目了然,也便于将来彻底删除时 grep 到唯一出处。
|
|
122
|
+
*/
|
|
123
|
+
const LEGACY_ENABLED_KEY = 'auditEnabled';
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 合法失败语义(provider 声明或用户配置只允许这三个值;其余一律当"没声明"处理)。
|
|
127
|
+
* @type {ReadonlyArray<string>}
|
|
128
|
+
*/
|
|
129
|
+
export const STAGE_ON_FAIL = Object.freeze(['block', 'warn', 'skip']);
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 解析「有序阶段链」配置。
|
|
133
|
+
*
|
|
134
|
+
* 两种形态,语义严格区分(向后兼容是硬要求):
|
|
135
|
+
* · `preCommit.stages` 为空/未配 ⇒ `mode:'legacy'`:**完全走原来的单命令路径**
|
|
136
|
+
* (`command`/`args`,缺省就是门禁 provider 的 CLI),行为与升级前逐字段一致
|
|
137
|
+
* · 非空 ⇒ `mode:'chain'`:按数组顺序逐阶段执行,每阶段独立超时与失败语义
|
|
138
|
+
*
|
|
139
|
+
* onFail 的解析**不看 provider 名字**(写死"audit 拦截 / format 警告"就是把具体实现
|
|
140
|
+
* 固化进宿主,正是要清掉的耦合):用户配置 > provider manifest 的 defaultOnFail > 'block'。
|
|
141
|
+
* 其中 manifest 那一步需要异步读包,放在执行阶段做(见 resolveStageOnFail)。
|
|
142
|
+
*
|
|
143
|
+
* @param {object} [cfg] 运行期配置
|
|
144
|
+
* @returns {{mode: 'legacy'|'chain', stages: Array<{provider: string, onFail: string, timeoutMs: number}>}}
|
|
145
|
+
*/
|
|
146
|
+
export function resolveStages(cfg = {}, paramStages = null) {
|
|
147
|
+
const block = (cfg && typeof cfg.preCommit === 'object' && cfg.preCommit) || {};
|
|
148
|
+
// 优先级:调用参数 > 配置 stages > (由调用方按 command/default 处理)
|
|
149
|
+
const fromParam = Array.isArray(paramStages) && paramStages.length ? paramStages : null;
|
|
150
|
+
const raw = fromParam || (Array.isArray(block.stages) ? block.stages : []);
|
|
151
|
+
const source = fromParam ? 'param' : 'config';
|
|
152
|
+
const stages = raw
|
|
153
|
+
.map((stage, index) => normalizeStageItem(stage, index))
|
|
154
|
+
.filter(Boolean);
|
|
155
|
+
if (!stages.length) return { mode: 'legacy', stages: [], source: 'config' };
|
|
156
|
+
return { mode: 'chain', stages: stages, source: source };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* 归一化单个阶段条目(两种合法形态 + 明确报错)。
|
|
161
|
+
*
|
|
162
|
+
* A. `{ provider }` —— 走 provider 注册表解析(已有通道)
|
|
163
|
+
* B. `{ command, args? }` —— 跑任意脚本(**不要求**对方声明是"我们的扩展")
|
|
164
|
+
*
|
|
165
|
+
* 非法时抛错(`StageConfigError`):参数写错要在跑任何 git 操作之前就失败,
|
|
166
|
+
* 不能等到 spawn 才发现——那会把"配置写错"表现成"提交时莫名报错"。
|
|
167
|
+
* @param {object} stage 原始条目
|
|
168
|
+
* @param {number} index 序号(错误信息里用)
|
|
169
|
+
* @returns {object}
|
|
170
|
+
*/
|
|
171
|
+
function normalizeStageItem(stage, index) {
|
|
172
|
+
const declaredStage = (stage && typeof stage === 'object') ? stage : null;
|
|
173
|
+
if (!declaredStage) throw new StageConfigError(`预处理阶段第 ${index + 1} 项不是对象`);
|
|
174
|
+
const provider = String(declaredStage.provider || '').trim();
|
|
175
|
+
const command = String(declaredStage.command || '').trim();
|
|
176
|
+
if (provider && command) throw new StageConfigError(`预处理阶段第 ${index + 1} 项同时给了 provider 和 command(只能二选一)`);
|
|
177
|
+
if (!provider && !command) throw new StageConfigError(`预处理阶段第 ${index + 1} 项既没有 provider 也没有 command`);
|
|
178
|
+
const onFailRaw = String(declaredStage.onFail || '').trim();
|
|
179
|
+
const timeoutMs = Number(declaredStage.timeoutMs);
|
|
180
|
+
const base = {
|
|
181
|
+
index: index,
|
|
182
|
+
// 空串 = 交给 provider 声明(provider 形态)/ 直接兜底 block(command 形态)
|
|
183
|
+
onFail: STAGE_ON_FAIL.includes(onFailRaw) ? onFailRaw : '',
|
|
184
|
+
timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.floor(timeoutMs) : 0,
|
|
185
|
+
};
|
|
186
|
+
if (provider) return { ...base, kind: 'provider', provider: provider };
|
|
187
|
+
const args = Array.isArray(declaredStage.args) ? declaredStage.args.map((a) => String(a)) : [];
|
|
188
|
+
return { ...base, kind: 'command', command: command, args: args };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 阶段配置错误(与"引擎跑失败"区分开:那是执行错误,这是配置错误)。 */
|
|
192
|
+
export class StageConfigError extends Error {
|
|
193
|
+
constructor(message) {
|
|
194
|
+
super(message);
|
|
195
|
+
this.name = 'StageConfigError';
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* 定某阶段的失败语义:用户配置 > provider manifest 的 defaultOnFail > 'block'。
|
|
201
|
+
*
|
|
202
|
+
* 为什么默认是 block:没声明就等于没承诺"失败也没关系"——放行一个跑失败的阶段,
|
|
203
|
+
* 等于把"恰好没跑起来"当成"通过"(与门禁 fail-closed 同一原则)。
|
|
204
|
+
* 想让格式化失败只警告的实现方,在自己的 manifest 里写 `defaultOnFail: 'warn'` 即可。
|
|
205
|
+
* @param {{onFail: string}} stage resolveStages 的条目
|
|
206
|
+
* @param {object|null} manifest provider 的 preprocessManifest(可为 null)
|
|
207
|
+
* @returns {'block'|'warn'|'skip'}
|
|
208
|
+
*/
|
|
209
|
+
export function resolveStageOnFail(stage, manifest) {
|
|
210
|
+
const fromUser = stage && STAGE_ON_FAIL.includes(stage.onFail) ? stage.onFail : '';
|
|
211
|
+
if (fromUser) return fromUser;
|
|
212
|
+
const fromManifest = manifest && STAGE_ON_FAIL.includes(manifest.defaultOnFail) ? manifest.defaultOnFail : '';
|
|
213
|
+
if (fromManifest) return fromManifest;
|
|
214
|
+
return 'block';
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 判断「提交前预处理要不要跑」(`preCommit.enabled`)。
|
|
219
|
+
*
|
|
220
|
+
* 判定顺序(**先看用户实际写下的配置,再看运行期默认值**):
|
|
221
|
+
* ① `config.json` 里的 `preCommit.enabled`(用户显式配过)
|
|
222
|
+
* ② `config.json` 里的旧版开关键(LEGACY_ENABLED_KEY):直接忽略等于让「本来开着的门禁
|
|
223
|
+
* 悄悄关掉」,这是最难发现的一类行为变化;读回时把来源标出来,用户能看到「本次沿用旧键」
|
|
224
|
+
* ③ 运行期 cfg 的 `preCommit.enabled`(schema 默认值 / 调用方显式传入)
|
|
225
|
+
* ④ 关
|
|
226
|
+
* 为什么 ①② 在 ③ 之前:schema 有默认值,运行期 cfg 里**永远**有 `preCommit.enabled:false`,
|
|
227
|
+
* 若先看 cfg 就永远读不到用户写下的真值(旧键也就永远失效)。
|
|
228
|
+
* @param {object} [cfg] 运行期配置
|
|
229
|
+
* @returns {{enabled: boolean, source: 'config.json'|'legacy'|'cfg'|'default'}}
|
|
230
|
+
*/
|
|
231
|
+
export function resolvePreCommitEnabled(cfg = {}) {
|
|
232
|
+
let fileSettings = null;
|
|
233
|
+
try {
|
|
234
|
+
fileSettings = readSettings({});
|
|
235
|
+
} catch {
|
|
236
|
+
// 配置读不到(无 DSH_HOME / 坏 JSON)→ 当作没配,不让读盘失败影响提交
|
|
237
|
+
fileSettings = null;
|
|
238
|
+
}
|
|
239
|
+
const fileBlock = fileSettings && typeof fileSettings.preCommit === 'object' ? fileSettings.preCommit : null;
|
|
240
|
+
if (typeof fileBlock?.enabled === 'boolean') return { enabled: fileBlock.enabled, source: 'config.json' };
|
|
241
|
+
const legacyEnabled = fileSettings?.[LEGACY_ENABLED_KEY];
|
|
242
|
+
if (typeof legacyEnabled === 'boolean') return { enabled: legacyEnabled, source: 'legacy' };
|
|
243
|
+
if (typeof cfg?.preCommit?.enabled === 'boolean') return { enabled: cfg.preCommit.enabled, source: 'cfg' };
|
|
244
|
+
return { enabled: false, source: 'default' };
|
|
245
|
+
}
|
|
246
|
+
|
|
114
247
|
/**
|
|
115
248
|
* 取 preCommit 配置块(两档来源 + 来源标记)。
|
|
116
249
|
* @param {object} cfg
|
|
@@ -231,26 +364,24 @@ function toSlotCsv(slots) {
|
|
|
231
364
|
/**
|
|
232
365
|
* 组装传给引擎的完整参数表(**由本模块统一追加,调用方不拼**)。
|
|
233
366
|
* 排序固定:先配置里的 args,再契约参数 —— 契约参数在最后,任何引擎都能靠「尾部固定段」解析。
|
|
367
|
+
*
|
|
368
|
+
* 参数只有两类,**界线不能含糊**(宿主/实现分家后的核心约定):
|
|
369
|
+
* ① **调用上下文**(宿主才知道的):repo / 仓库可见性 / 本次临时豁免 / findings 粒度
|
|
370
|
+
* —— 这些是「这一次提交的事实」,不是配置,必须由宿主传给引擎;
|
|
371
|
+
* ② **实现自己的配置**(怎么审):扫描范围 / 权重 / 规则槽位 / 文件数上限
|
|
372
|
+
* —— 属预处理实现自己的 config.json,宿主**不传**(传了等于宿主继续替它做配置决策,
|
|
373
|
+
* 两包就还是耦合的)。命令行 `--scope` 等只用于「显式覆盖」,由调用方在需要时给。
|
|
234
374
|
* @param {object} p
|
|
235
375
|
* @returns {string[]}
|
|
236
376
|
*/
|
|
237
377
|
export function buildEngineArgs({
|
|
238
|
-
args = [], repoPath = '',
|
|
239
|
-
|
|
378
|
+
args = [], repoPath = '', rulesetDir = '', blockersOnly = false,
|
|
379
|
+
visibility = '', exemptPaths = [], exemptReason = '',
|
|
240
380
|
} = {}) {
|
|
241
381
|
const argv = [...resolveEngineArgs(args)];
|
|
242
382
|
argv.push('--repo', String(repoPath || '.'));
|
|
243
|
-
|
|
383
|
+
// 自定规则目录是**调用方显式指定**(工具 ruleset 参数 / API 传参),不是宿主配置,故保留透传。
|
|
244
384
|
if (rulesetDir) argv.push('--ruleset', String(rulesetDir));
|
|
245
|
-
if (weights && typeof weights === 'object' && Object.keys(weights).length) argv.push('--weights', JSON.stringify(weights));
|
|
246
|
-
// maxScanFiles 只在拿到有限数时才传:0 有明确含义(不限),所以不能用 truthy 判断
|
|
247
|
-
if (Number.isFinite(Number(maxScanFiles))) argv.push('--max-scan-files', String(Number(maxScanFiles)));
|
|
248
|
-
// 槽位清单只在「确实有内容」时才传:空数组传成空字符串会被引擎当成一个空槽位名
|
|
249
|
-
const whiteListCsv = toSlotCsv(slots);
|
|
250
|
-
if (whiteListCsv) argv.push('--slots', whiteListCsv);
|
|
251
|
-
const blackListCsv = toSlotCsv(disabledSlots);
|
|
252
|
-
if (blackListCsv) argv.push('--disabled-slots', blackListCsv);
|
|
253
|
-
// 新参数只传给「新引擎」(预处理实现):内置旧引擎不认这些 flag,传了会直接 exit 2。
|
|
254
385
|
// 可见性:只有明确知道时才传(unknown 是引擎缺省,传了也一样);
|
|
255
386
|
// 私有库豁免由预处理实现自己判(它是权威),gitpush 只负责探测后把结论传过去。
|
|
256
387
|
if (visibility === 'private' || visibility === 'public') argv.push('--visibility', visibility);
|
|
@@ -320,7 +451,7 @@ export function parseEngineStdout(stdout) {
|
|
|
320
451
|
* @returns {Promise<{ok: true, stdout: string, stderr: string, exitCode: number|null, signal: string|null}
|
|
321
452
|
* | {ok: false, stage: 'timeout'|'too-large'|'spawn', error: string, stderr: string}>}
|
|
322
453
|
*/
|
|
323
|
-
function runEngineProcess({ command, args, timeoutMs }) {
|
|
454
|
+
function runEngineProcess({ command, args, timeoutMs, env }) {
|
|
324
455
|
return new Promise((settle) => {
|
|
325
456
|
let stdout = '';
|
|
326
457
|
let stderr = '';
|
|
@@ -339,7 +470,8 @@ function runEngineProcess({ command, args, timeoutMs }) {
|
|
|
339
470
|
const killChild = () => { try { child?.kill('SIGKILL'); } catch { /* 进程可能已退出 */ } };
|
|
340
471
|
|
|
341
472
|
try {
|
|
342
|
-
|
|
473
|
+
// env 是**追加**的:不给就完全继承父进程环境(旧行为不变)
|
|
474
|
+
child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...(env || {}) } });
|
|
343
475
|
} catch (e) {
|
|
344
476
|
finish({ ok: false, stage: 'spawn', error: String(e?.message || e), stderr });
|
|
345
477
|
return;
|
|
@@ -373,10 +505,7 @@ function runEngineProcess({ command, args, timeoutMs }) {
|
|
|
373
505
|
* 跑提交前预处理引擎。
|
|
374
506
|
* @param {object} p
|
|
375
507
|
* repoPath : 仓库绝对路径(相对路径按当前工作目录解析,与旧行为一致)
|
|
376
|
-
*
|
|
377
|
-
* rulesetDir: 自定规则目录(透传,不解析——旧行为就是原样传给审计)
|
|
378
|
-
* weights : 已解析好的权重覆盖对象(空对象 = 默认权重表)
|
|
379
|
-
* maxScanFiles / slots / disabledSlots:来自插件配置的审计选项(不传则用引擎默认值)
|
|
508
|
+
* rulesetDir: 自定规则目录(调用方显式指定,透传不解析)
|
|
380
509
|
* blockersOnly: findings 只留 blocker
|
|
381
510
|
* cfg : 运行期配置(读 preCommit)
|
|
382
511
|
* timeoutMs : 覆盖超时(测试用)
|
|
@@ -384,14 +513,23 @@ function runEngineProcess({ command, args, timeoutMs }) {
|
|
|
384
513
|
* engine?: {command: string, args: string[], exitCode: number|null, timedOut: boolean}}>}
|
|
385
514
|
*/
|
|
386
515
|
export async function runPreCommitEngine({
|
|
387
|
-
repoPath = '.',
|
|
388
|
-
|
|
516
|
+
repoPath = '.', rulesetDir = '', blockersOnly = false,
|
|
517
|
+
cfg = {}, timeoutMs, visibility = '', exemptPaths = [], exemptReason = '',
|
|
518
|
+
env = null,
|
|
389
519
|
} = {}) {
|
|
390
520
|
const spec = resolvePreCommitConfig(cfg);
|
|
391
521
|
// 预处理实现是**可热插拔的扩展能力**:不在位时不该拦住提交,而应当「跳过审计并明确标注」。
|
|
392
522
|
// 这正是解耦的目标——拔掉扩展,主流程照常;插上扩展,能力自动回来。
|
|
393
523
|
// 注意:这里返回的是「跳过」而不是「静默通过」,调用方能拿到 preprocessSkipped 与原因。
|
|
394
|
-
|
|
524
|
+
// 「不在位」的判据 = **实现包的 CLI 入口文件不存在**,与有没有显式配置 command 无关:
|
|
525
|
+
// 用户完全可能把 preCommit.command 配成 `node` + args 指到包里的 cli.mjs,
|
|
526
|
+
// 此时包被拔掉(optionalDependency 未装)也属「扩展没插」,不该拦提交;
|
|
527
|
+
// 而自定义引擎换成别的脚本名时不会命中这条,仍是 fail-closed(那是配置错,不是缺扩展)。
|
|
528
|
+
const missingProviderEntry = spec.args.find((rawArg) => {
|
|
529
|
+
const text = String(rawArg || '');
|
|
530
|
+
return text.endsWith(PREPROCESS_CLI_REL) && isAbsolute(text) && !existsSync(text);
|
|
531
|
+
});
|
|
532
|
+
if (missingProviderEntry) {
|
|
395
533
|
const entry = resolveGateProvider();
|
|
396
534
|
return {
|
|
397
535
|
ok: true,
|
|
@@ -405,21 +543,21 @@ export async function runPreCommitEngine({
|
|
|
405
543
|
// 显式配置的引擎命令不可用 ⇒ 这是配置错误(不是「扩展不在位」),仍然 fail-closed
|
|
406
544
|
if (!resolved.ok) return failClosed(`提交前预处理失败:${resolved.error}(未执行任何 git 操作;修复 preCommit.command 后重试)`);
|
|
407
545
|
const command = resolved.command;
|
|
408
|
-
const args = buildEngineArgs({ args: spec.args, repoPath,
|
|
546
|
+
const args = buildEngineArgs({ args: spec.args, repoPath, rulesetDir, blockersOnly, visibility, exemptPaths, exemptReason });
|
|
409
547
|
const commandLine = formatCommandLine(command, args);
|
|
410
548
|
const effectiveTimeout = Number.isFinite(Number(timeoutMs)) && Number(timeoutMs) > 0
|
|
411
549
|
? Math.floor(Number(timeoutMs))
|
|
412
550
|
: spec.timeoutMs;
|
|
413
|
-
const run = await runEngineProcess({ command, args, timeoutMs: effectiveTimeout });
|
|
551
|
+
const run = await runEngineProcess({ command, args, timeoutMs: effectiveTimeout, env: env });
|
|
414
552
|
|
|
415
553
|
if (!run.ok) {
|
|
416
554
|
const label = run.stage === 'timeout' ? '超时' : run.stage === 'too-large' ? '输出超限' : '无法启动';
|
|
417
|
-
return failClosed(`提交前预处理失败:引擎${label}(${run.error})\n 命令:${commandLine}\n stderr: ${stderrTail(run.stderr) || '(空)'}\n (未执行任何 git 操作;修复引擎或临时关闭
|
|
555
|
+
return failClosed(`提交前预处理失败:引擎${label}(${run.error})\n 命令:${commandLine}\n stderr: ${stderrTail(run.stderr) || '(空)'}\n (未执行任何 git 操作;修复引擎或临时关闭 preCommit.enabled 后重试)`);
|
|
418
556
|
}
|
|
419
557
|
const { exitCode, signal, stdout, stderr } = run;
|
|
420
558
|
if (exitCode !== ENGINE_EXIT_OK && exitCode !== ENGINE_EXIT_BLOCKED) {
|
|
421
559
|
const codeText = exitCode === null ? `被信号 ${signal || '?'} 终止` : `退出码 ${exitCode}`;
|
|
422
|
-
return failClosed(`提交前预处理失败:引擎 ${commandLine} ${codeText}\n stderr: ${stderrTail(stderr) || '(空)'}\n (未执行任何 git 操作;修复引擎或临时关闭
|
|
560
|
+
return failClosed(`提交前预处理失败:引擎 ${commandLine} ${codeText}\n stderr: ${stderrTail(stderr) || '(空)'}\n (未执行任何 git 操作;修复引擎或临时关闭 preCommit.enabled 后重试)`);
|
|
423
561
|
}
|
|
424
562
|
const parsed = parseEngineStdout(stdout);
|
|
425
563
|
if (!parsed.ok) {
|
|
@@ -433,3 +571,417 @@ export async function runPreCommitEngine({
|
|
|
433
571
|
engine: { command, args, exitCode, timedOut: false },
|
|
434
572
|
};
|
|
435
573
|
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* 跑「提交前预处理流水线」——阶段链的入口。
|
|
577
|
+
*
|
|
578
|
+
* 与 `runPreCommitEngine` 的分工:后者是**单次执行**(解析命令 → spawn → 按契约解释结果),
|
|
579
|
+
* 本函数只做「按配置决定跑几个阶段、按什么顺序、失败了怎么办」,不重复实现执行细节。
|
|
580
|
+
*
|
|
581
|
+
* 三种形态:
|
|
582
|
+
* · `preCommit.stages` 未配/空 ⇒ **原样调用 runPreCommitEngine**(回执与升级前逐字段一致)
|
|
583
|
+
* · 只配一个阶段 ⇒ 也走同一条单次执行路径(按该阶段 provider 的 CLI 跑),回执形状不变
|
|
584
|
+
* · 多阶段 ⇒ 按数组顺序逐阶段执行;每阶段独立超时;失败语义见 resolveStageOnFail
|
|
585
|
+
*
|
|
586
|
+
* @param {object} opts 与 runPreCommitEngine 相同的入参(repoPath / visibility / exemptPaths / cfg / …)
|
|
587
|
+
* @returns {Promise<object>} legacy/单阶段:与 runPreCommitEngine 同形状;
|
|
588
|
+
* 多阶段:在它基础上追加 `preprocessStages`(逐阶段回执)等 additive 字段
|
|
589
|
+
*/
|
|
590
|
+
export async function runPreCommitPipeline(opts = {}) {
|
|
591
|
+
let plan;
|
|
592
|
+
try {
|
|
593
|
+
plan = resolveStages(opts.cfg, opts.stages);
|
|
594
|
+
} catch (e) {
|
|
595
|
+
// 配置错误要在**跑任何 git 操作之前**就失败(runPreprocess 在 add/commit 之前调用)
|
|
596
|
+
return failClosed(`提交前预处理失败:${e && e.message ? e.message : e}`);
|
|
597
|
+
}
|
|
598
|
+
// ── 兼容路径:没配阶段链 ⇒ 行为与升级前完全一致(不追加任何字段)──
|
|
599
|
+
if (plan.mode === 'legacy') {
|
|
600
|
+
// 单命令 / 单 provider 兜底:回执不变,只补一个来源标识(additive,便于观测本次跑的是谁)
|
|
601
|
+
const legacy = await runPreCommitEngine(opts);
|
|
602
|
+
const block = (opts.cfg && opts.cfg.preCommit) || {};
|
|
603
|
+
const legacySource = (block.command || (Array.isArray(block.args) && block.args.length)) ? 'command' : 'default';
|
|
604
|
+
return { ...legacy, stagesSource: legacySource };
|
|
605
|
+
}
|
|
606
|
+
// ── 配了 stages(哪怕只有一个):一律走链执行 ──
|
|
607
|
+
// 为什么单阶段也走链:这样"改了哪些文件"(preprocessChanges)对单阶段同样可用,
|
|
608
|
+
// 否则「只配了一个格式化 provider」的用户永远看不到改动清单。
|
|
609
|
+
// 代价仅是回执多出 additive 字段(preprocessStages / preprocessChanges),
|
|
610
|
+
// 拦截决策与执行路径完全复用同一实现。
|
|
611
|
+
return runChain(plan.stages, opts, plan.source || 'config');
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** 单文件内容指纹(读不到/非普通文件返回空串,不抛)。 */
|
|
615
|
+
function fileFingerprint(absPath) {
|
|
616
|
+
try {
|
|
617
|
+
const st = statSync(absPath);
|
|
618
|
+
if (!st.isFile()) return 'nonfile';
|
|
619
|
+
const buf = readFileSync(absPath);
|
|
620
|
+
return createHash('sha256').update(buf).digest('hex').slice(0, 16);
|
|
621
|
+
} catch { return ''; }
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** 工作树快照上限:超过就退化为「只比状态码」,避免大改动拖慢提交。 */
|
|
625
|
+
const STAGE_SNAPSHOT_MAX_FILES = 500;
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* 拍一次工作树快照:`git status --porcelain` 列出的每个路径 → `状态码|大小|内容指纹`。
|
|
629
|
+
*
|
|
630
|
+
* 为什么不能只比状态码:格式化器改写一个**本来就已经是 M** 的文件时,status 前后都是 " M",
|
|
631
|
+
* 只看状态码会得出"没改动"的假结论(这正是要防的)。
|
|
632
|
+
* 为什么不只看 mtime:跑两次格式化,第二次内容完全相同时 mtime 仍会变 ⇒ 会把幂等误报成有改动。
|
|
633
|
+
* ⇒ 用**内容指纹**,幂等才是真的幂等。
|
|
634
|
+
* @param {string} repoPath 仓库绝对路径
|
|
635
|
+
* @returns {{ok: boolean, files: Map<string,string>, truncated?: boolean}}
|
|
636
|
+
*/
|
|
637
|
+
export function snapshotWorktree(repoPath) {
|
|
638
|
+
// 必须用 gitRaw + -z:runGit 会 trim 输出,而 porcelain 的状态首列**可能就是一个空格**
|
|
639
|
+
// (未暂存修改 = " M")——trim 会把那个空格吃掉,路径整体左移一位,
|
|
640
|
+
// 结果得到 ".js" 这种假路径(本函数第一版就是这么错的,靠"改动清单里没有 a.js"抓到)。
|
|
641
|
+
// -z 分隔的原始字节不受 trim 影响。
|
|
642
|
+
const res = gitRaw(['status', '--porcelain', '-z'], { cwd: repoPath });
|
|
643
|
+
const files = new Map();
|
|
644
|
+
if (res.error || res.status === null) return { ok: false, files: files };
|
|
645
|
+
const entries = res.stdout.toString('utf8').split('\0').filter((entry) => entry.length > 2);
|
|
646
|
+
const truncated = entries.length > STAGE_SNAPSHOT_MAX_FILES;
|
|
647
|
+
for (const line of entries.slice(0, STAGE_SNAPSHOT_MAX_FILES)) {
|
|
648
|
+
// porcelain v1 -z:每项 "XY path"(重命名是 "XY new\0old",旧路径项会被上面的长度过滤挡住)
|
|
649
|
+
const code = line.slice(0, 2);
|
|
650
|
+
let rel = line.slice(3);
|
|
651
|
+
rel = rel.replace(/^"|"$/g, '');
|
|
652
|
+
if (!rel) continue;
|
|
653
|
+
const abs = joinPath(repoPath, rel);
|
|
654
|
+
const size = (() => { try { return String(statSync(abs).size); } catch { return '0'; } })();
|
|
655
|
+
const fp = truncated ? '' : fileFingerprint(abs);
|
|
656
|
+
files.set(rel, code + '|' + size + '|' + fp);
|
|
657
|
+
}
|
|
658
|
+
return { ok: true, files: files, ...(truncated ? { truncated: true } : {}) };
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* 两次快照的差集 = 这一阶段到底改了什么。
|
|
663
|
+
*
|
|
664
|
+
* 判定:
|
|
665
|
+
* · 只在 after 里 ⇒ 新增
|
|
666
|
+
* · 只在 before 里 ⇒ 删除(格式化器不会删,但"会改文件"的 provider 可能)
|
|
667
|
+
* · 两边都有但指纹/大小/状态码不同 ⇒ 修改(**这是格式化最常见的形态**)
|
|
668
|
+
* @param {Map<string,string>} before
|
|
669
|
+
* @param {Map<string,string>} after
|
|
670
|
+
* @returns {{added: number, modified: number, deleted: number, files: string[]}}
|
|
671
|
+
*/
|
|
672
|
+
export function diffSnapshots(before, after) {
|
|
673
|
+
const added = [];
|
|
674
|
+
const modified = [];
|
|
675
|
+
const deleted = [];
|
|
676
|
+
for (const [rel, sig] of after) {
|
|
677
|
+
if (!before.has(rel)) { added.push(rel); continue; }
|
|
678
|
+
if (before.get(rel) !== sig) modified.push(rel);
|
|
679
|
+
}
|
|
680
|
+
for (const rel of before.keys()) if (!after.has(rel)) deleted.push(rel);
|
|
681
|
+
return {
|
|
682
|
+
added: added.length,
|
|
683
|
+
modified: modified.length,
|
|
684
|
+
deleted: deleted.length,
|
|
685
|
+
files: [...added, ...modified, ...deleted].sort(),
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* 顺序执行阶段链。
|
|
691
|
+
*
|
|
692
|
+
* 语义(与配置解耦,宿主不认 provider 名字):
|
|
693
|
+
* · **顺序**:数组顺序即执行顺序,前一个跑完才跑下一个(格式化必须先于审计改完文件)
|
|
694
|
+
* · **每阶段独立超时**:stage.timeoutMs > 0 时覆盖全局超时
|
|
695
|
+
* · **失败语义**:resolveStageOnFail(用户 > provider 声明 > 'block')
|
|
696
|
+
* block ⇒ 立即中断并拒绝提交;warn ⇒ 记警告继续;skip ⇒ 静默跳过继续
|
|
697
|
+
* · **实现不在位**(provider 没装)不算失败 ⇒ 记 `skipped` + 警告,继续下一阶段
|
|
698
|
+
* (与单阶段「拔掉扩展仍能提交」的热插拔语义一致)
|
|
699
|
+
* @param {Array<{provider: string, onFail: string, timeoutMs: number}>} stages
|
|
700
|
+
* @param {object} opts 与 runPreCommitEngine 相同
|
|
701
|
+
* @returns {Promise<object>} 追加 `preprocessStages`(逐阶段回执)与可选 `preprocessWarnings`
|
|
702
|
+
*/
|
|
703
|
+
async function runChain(stages, opts = {}, chainSource = 'config') {
|
|
704
|
+
const stageReceipts = [];
|
|
705
|
+
const warnings = [];
|
|
706
|
+
const allChanged = [];
|
|
707
|
+
let lastAudit = null;
|
|
708
|
+
let lastEngine = null;
|
|
709
|
+
let lastSkipped = null;
|
|
710
|
+
|
|
711
|
+
// 一次性取全部在位 provider 的声明(onFail 的默认值来自它;读不到就当没声明)
|
|
712
|
+
let manifestsById = new Map();
|
|
713
|
+
try {
|
|
714
|
+
const listed = await listProviderManifests();
|
|
715
|
+
manifestsById = new Map((listed.manifests || []).map((m) => [m.provider.id, m.manifest]));
|
|
716
|
+
} catch { /* 读不到声明不影响执行:onFail 退回默认 block */ }
|
|
717
|
+
|
|
718
|
+
// 链开始时的「本次改动」:这就是用户马上要提交的那批文件(格式化要处理的正是它们)
|
|
719
|
+
const initialSnap = snapshotWorktree(opts.repoPath || '.');
|
|
720
|
+
const changedSoFar = new Set(initialSnap.ok ? [...initialSnap.files.keys()] : []);
|
|
721
|
+
const envDir = mkdtempSync(joinPath(tmpdir(), 'dsh-preprocess-'));
|
|
722
|
+
|
|
723
|
+
try {
|
|
724
|
+
for (const stage of stages) {
|
|
725
|
+
const startedAt = Date.now();
|
|
726
|
+
// 两种阶段形态:provider(走注册表解析)与 command(跑任意脚本,不要求对方声明)
|
|
727
|
+
const stageLabel = stage.kind === 'provider' ? stage.provider : commandLabelOf(stage.command);
|
|
728
|
+
let providerEntry = null;
|
|
729
|
+
if (stage.kind === 'provider') {
|
|
730
|
+
providerEntry = resolveProvider(stage.provider);
|
|
731
|
+
if (!providerEntry.ok) {
|
|
732
|
+
// 两种"解析失败"必须分开处理,否则会把配置错当成"没装"而静默放行:
|
|
733
|
+
// ① provider 名字不在注册表里 ⇒ 配置写错了 ⇒ fail-closed(打错一个字母就让整道门禁消失,太危险)
|
|
734
|
+
// ② 注册过但入口文件不在 ⇒ 扩展没装 ⇒ 跳过 + 警告,不拦提交(热插拔语义)
|
|
735
|
+
if (!getProviderDefinition(stage.provider)) {
|
|
736
|
+
return failClosed(`提交前预处理失败:阶段配置里的 provider 「${stage.provider}」未注册(已注册:audit 等,见 lib/preprocess/providers.js)`);
|
|
737
|
+
}
|
|
738
|
+
stageReceipts.push({ provider: stageLabel, ok: true, skipped: 'provider-not-found', ms: 0, error: providerEntry.error });
|
|
739
|
+
warnings.push(`${stageLabel}: 未安装/入口不可用,已跳过该阶段`);
|
|
740
|
+
lastSkipped = { preprocessSkipped: 'package-not-found', skipReason: providerEntry.error };
|
|
741
|
+
continue;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
const onFail = resolveStageOnFail(stage, stage.kind === 'provider' ? (manifestsById.get(stage.provider) || null) : null);
|
|
745
|
+
// 改动的可见性:阶段前后各拍一次工作树快照,差集就是它改了哪些文件。
|
|
746
|
+
// 放在宿主而不是要求 provider 上报:任何"会改文件"的实现(格式化/自动修复/锁更新)都通用。
|
|
747
|
+
const beforeSnap = snapshotWorktree(opts.repoPath || '.');
|
|
748
|
+
// 把「本次改动」以**环境变量**的形式交给实现方(想读就读,不读就当没看见 ⇒ 不改变既有契约)。
|
|
749
|
+
// 换行分隔而不是逗号:文件名里可以有逗号,换行几乎不可能。
|
|
750
|
+
// 同时落一份文件路径:文件很多时单个环境变量会撞 128KB 上限。
|
|
751
|
+
const stageEnv = buildStageEnv({
|
|
752
|
+
repoPath: opts.repoPath || '.',
|
|
753
|
+
provider: stage.provider,
|
|
754
|
+
changed: [...changedSoFar],
|
|
755
|
+
envDir: envDir,
|
|
756
|
+
});
|
|
757
|
+
const stageCfg = stage.kind === 'provider'
|
|
758
|
+
? withStageOverride(opts.cfg, providerEntry.path, stage.timeoutMs)
|
|
759
|
+
: withCommandStage(opts.cfg, stage, {
|
|
760
|
+
repo: opts.repoPath || '.',
|
|
761
|
+
filesFile: stageEnv.listFile,
|
|
762
|
+
filesCount: String(changedSoFar.size),
|
|
763
|
+
stage: String(stageReceipts.length + 1),
|
|
764
|
+
}, stage.timeoutMs);
|
|
765
|
+
const res = await runPreCommitEngine({ ...opts, cfg: stageCfg, env: stageEnv.env });
|
|
766
|
+
const afterSnap = snapshotWorktree(opts.repoPath || '.');
|
|
767
|
+
const changed = (beforeSnap.ok && afterSnap.ok) ? diffSnapshots(beforeSnap.files, afterSnap.files) : null;
|
|
768
|
+
const ms = Date.now() - startedAt;
|
|
769
|
+
const providerSkipped = !!res.preprocessSkipped;
|
|
770
|
+
const hitBlockers = res.ok === true && res.blocked === true;
|
|
771
|
+
const failed = res.ok !== true;
|
|
772
|
+
|
|
773
|
+
stageReceipts.push({
|
|
774
|
+
provider: stageLabel,
|
|
775
|
+
...(stage.kind === 'command' ? { kind: 'command' } : {}),
|
|
776
|
+
ok: !failed && !hitBlockers,
|
|
777
|
+
onFail: onFail,
|
|
778
|
+
ms: ms,
|
|
779
|
+
...(providerSkipped ? { skipped: res.preprocessSkipped, reason: res.skipReason || '' } : {}),
|
|
780
|
+
...(hitBlockers ? { blocked: blockedSummaryOf(res) } : {}),
|
|
781
|
+
...(failed ? { error: res.error || '执行失败' } : {}),
|
|
782
|
+
// 本阶段改动的文件清单(null = 拍不到快照,例如非 git 目录)
|
|
783
|
+
...(changed ? { changed: changed } : {}),
|
|
784
|
+
});
|
|
785
|
+
allChanged.push(...((changed && changed.files) || []));
|
|
786
|
+
for (const rel of (changed && changed.files) || []) changedSoFar.add(rel);
|
|
787
|
+
if (res.engine) lastEngine = res.engine;
|
|
788
|
+
if (res.audit) lastAudit = res.audit;
|
|
789
|
+
if (providerSkipped) { lastSkipped = { preprocessSkipped: res.preprocessSkipped, skipReason: res.skipReason || '' }; continue; }
|
|
790
|
+
|
|
791
|
+
if (failed) {
|
|
792
|
+
if (onFail === 'warn') { warnings.push(`${stage.provider}: ${res.error || '执行失败'}(该阶段为 warn,继续)`); continue; }
|
|
793
|
+
if (onFail === 'skip') continue;
|
|
794
|
+
// block:中断整条链,拒绝提交(保留可诊断信息 + 已跑阶段的回执)
|
|
795
|
+
return {
|
|
796
|
+
...res,
|
|
797
|
+
preprocessStages: stageReceipts,
|
|
798
|
+
preprocessChanges: { total: new Set(allChanged).size, files: [...new Set(allChanged)].sort() },
|
|
799
|
+
...(warnings.length ? { preprocessWarnings: warnings } : {}),
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
if (hitBlockers) {
|
|
803
|
+
if (onFail === 'warn') { warnings.push(`${stage.provider}: 命中拦截项(该阶段为 warn,仅记录)`); continue; }
|
|
804
|
+
if (onFail === 'skip') continue;
|
|
805
|
+
return {
|
|
806
|
+
ok: true,
|
|
807
|
+
blocked: true,
|
|
808
|
+
audit: res.audit || null,
|
|
809
|
+
engine: res.engine || null,
|
|
810
|
+
preprocessStages: stageReceipts,
|
|
811
|
+
preprocessChanges: { total: new Set(allChanged).size, files: [...new Set(allChanged)].sort() },
|
|
812
|
+
...(warnings.length ? { preprocessWarnings: warnings } : {}),
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
return {
|
|
818
|
+
ok: true,
|
|
819
|
+
blocked: false,
|
|
820
|
+
audit: lastAudit,
|
|
821
|
+
engine: lastEngine,
|
|
822
|
+
...(lastSkipped && !lastAudit ? lastSkipped : {}),
|
|
823
|
+
preprocessStages: stageReceipts,
|
|
824
|
+
// 汇总:整条链一共改了哪些文件(去重排序;格式化改的文件会被后续 git add 一并提交)
|
|
825
|
+
preprocessChanges: { total: new Set(allChanged).size, files: [...new Set(allChanged)].sort() },
|
|
826
|
+
// 本次链的来源:param(调用参数覆盖)/ config(配置文件)
|
|
827
|
+
stagesSource: chainSource,
|
|
828
|
+
...(warnings.length ? { preprocessWarnings: warnings } : {}),
|
|
829
|
+
};
|
|
830
|
+
} finally {
|
|
831
|
+
// 临时目录只装「改动文件清单」,链跑完就删(不在 /tmp 里堆垃圾)
|
|
832
|
+
try { rmSync(envDir, { recursive: true, force: true }); } catch { /* 清理失败不影响结果 */ }
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* 造「当前阶段」的环境变量(想读就读,不读就当没看见 ⇒ 不改变既有 provider 契约)。
|
|
838
|
+
*
|
|
839
|
+
* 变量(都是**加法**,老实现完全不需要知道它们):
|
|
840
|
+
* PREPROCESS_REPO 当前仓库绝对路径
|
|
841
|
+
* PREPROCESS_CHANGED_FILES 本次改动文件(**换行**分隔;文件名里可以有逗号,换行几乎不可能)
|
|
842
|
+
* PREPROCESS_CHANGED_FILES_COUNT 条数
|
|
843
|
+
* PREPROCESS_CHANGED_FILES_FILE 同一份清单落盘的绝对路径(文件多时单个变量会撞 128KB 上限)
|
|
844
|
+
* PREPROCESS_STAGE_PROVIDER 当前阶段的 provider id
|
|
845
|
+
* @param {{repoPath: string, provider: string, changed: string[], envDir: string}} p
|
|
846
|
+
* @returns {{env: object, listFile: string}}
|
|
847
|
+
*/
|
|
848
|
+
export function buildStageEnv({ repoPath = '.', provider = '', changed = [], envDir = '' } = {}) {
|
|
849
|
+
const list = changed.filter(Boolean);
|
|
850
|
+
const text = list.join('\n');
|
|
851
|
+
let listFile = '';
|
|
852
|
+
if (envDir) {
|
|
853
|
+
listFile = joinPath(envDir, 'changed-files.txt');
|
|
854
|
+
try { writeFileSync(listFile, text, 'utf8'); } catch { listFile = ''; }
|
|
855
|
+
}
|
|
856
|
+
const env = {
|
|
857
|
+
PREPROCESS_REPO: String(repoPath || '.'),
|
|
858
|
+
PREPROCESS_CHANGED_FILES: text,
|
|
859
|
+
PREPROCESS_CHANGED_FILES_COUNT: String(list.length),
|
|
860
|
+
...(listFile ? { PREPROCESS_CHANGED_FILES_FILE: listFile } : {}),
|
|
861
|
+
...(provider ? { PREPROCESS_STAGE_PROVIDER: String(provider) } : {}),
|
|
862
|
+
};
|
|
863
|
+
return { env: env, listFile: listFile };
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
/**
|
|
867
|
+
* 从单阶段回执里抽出「拦截清单摘要」——阶段回执只报事实(几条、头几条文件),
|
|
868
|
+
* 完整 findings 仍在最终 audit 里,不在这里复制一份(避免两份真相)。
|
|
869
|
+
* @param {object} res runPreCommitEngine 的回执
|
|
870
|
+
* @returns {{count: number, files: string[]}}
|
|
871
|
+
*/
|
|
872
|
+
function blockedSummaryOf(res) {
|
|
873
|
+
const audit = (res && res.audit) || {};
|
|
874
|
+
const blocked = Array.isArray(audit.blocked) ? audit.blocked : [];
|
|
875
|
+
return {
|
|
876
|
+
count: blocked.length,
|
|
877
|
+
files: [...new Set(blocked.map((b) => String(b && b.file || '')).filter(Boolean))].slice(0, BLOCKED_FILES_PREVIEW_MAX),
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* 造一份「指定 provider 入口」的临时 cfg:让 runPreCommitEngine 走显式 args 分支。
|
|
883
|
+
*
|
|
884
|
+
* 为什么不改 runPreCommitEngine 的签名:它已经支持「command/args 显式指定」,这里只是
|
|
885
|
+
* 把阶段解析结果喂进那条既有通道 —— 单次执行只有一份实现,避免两套 spawn 逻辑漂移。
|
|
886
|
+
* @param {object} cfg 原运行期配置
|
|
887
|
+
* @param {string} cliPath provider 的 CLI 绝对路径
|
|
888
|
+
* @param {number} timeoutMs 该阶段超时(0=沿用全局)
|
|
889
|
+
* @returns {object}
|
|
890
|
+
*/
|
|
891
|
+
function withStageOverride(cfg, cliPath, timeoutMs) {
|
|
892
|
+
const base = (cfg && typeof cfg.preCommit === 'object' && cfg.preCommit) || {};
|
|
893
|
+
return {
|
|
894
|
+
...cfg,
|
|
895
|
+
preCommit: {
|
|
896
|
+
...base,
|
|
897
|
+
command: '',
|
|
898
|
+
args: [cliPath],
|
|
899
|
+
...(timeoutMs > 0 ? { timeoutMs: timeoutMs } : {}),
|
|
900
|
+
},
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/** 阶段标签(command 形态):取可执行文件名,便于回执里认人。 */
|
|
905
|
+
function commandLabelOf(command) {
|
|
906
|
+
const first = splitCommandLine(String(command || ''))[0] || String(command || '');
|
|
907
|
+
return joinPath('.', first).replace(/^\.\//, '') || 'command';
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/**
|
|
911
|
+
* 按 shell-like 规则切词 —— **不启动真 shell**。
|
|
912
|
+
*
|
|
913
|
+
* 为什么不用 `sh -c`:那等于把配置里的字符串当代码执行(`; rm -rf /` 会被执行)。
|
|
914
|
+
* 这里只做引号/空白切分,任何 `;` `|` `$()` 都原样当作普通参数传下去。
|
|
915
|
+
* 规则:单/双引号成组(引号内空格不切分);反斜杠转义下一个字符;其余按空白切分。
|
|
916
|
+
* @param {string} text 命令行文本
|
|
917
|
+
* @returns {string[]} 词数组(首项通常是可执行文件)
|
|
918
|
+
*/
|
|
919
|
+
export function splitCommandLine(text) {
|
|
920
|
+
const out = [];
|
|
921
|
+
let cur = '';
|
|
922
|
+
let quote = '';
|
|
923
|
+
let has = false;
|
|
924
|
+
const src = String(text || '');
|
|
925
|
+
for (let i = 0; i < src.length; i += 1) {
|
|
926
|
+
const ch = src[i];
|
|
927
|
+
if (quote) {
|
|
928
|
+
if (ch === quote) { quote = ''; continue; }
|
|
929
|
+
if (ch === '\\' && quote === '"' && i + 1 < src.length) { cur += src[i + 1]; i += 1; continue; }
|
|
930
|
+
cur += ch;
|
|
931
|
+
continue;
|
|
932
|
+
}
|
|
933
|
+
if (ch === '"' || ch === "'") { quote = ch; has = true; continue; }
|
|
934
|
+
if (ch === '\\' && i + 1 < src.length) { cur += src[i + 1]; i += 1; has = true; continue; }
|
|
935
|
+
if (/\s/.test(ch)) {
|
|
936
|
+
if (has || cur) { out.push(cur); cur = ''; has = false; }
|
|
937
|
+
continue;
|
|
938
|
+
}
|
|
939
|
+
cur += ch;
|
|
940
|
+
has = true;
|
|
941
|
+
}
|
|
942
|
+
if (has || cur) out.push(cur);
|
|
943
|
+
return out;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/** 占位符替换:{repo} / {filesFile} / {filesCount} / {stage}(宿主替换,未知占位符原样保留)。 */
|
|
947
|
+
export function substitutePlaceholders(value, ctx = {}) {
|
|
948
|
+
return String(value == null ? '' : value).replace(/\{(repo|filesFile|filesCount|stage)\}/g,
|
|
949
|
+
(whole, key) => (ctx[key] === undefined || ctx[key] === null ? whole : String(ctx[key])));
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* 造「command 形态阶段」的临时 cfg。
|
|
954
|
+
*
|
|
955
|
+
* 两种写法都支持:
|
|
956
|
+
* A. `{ command: 'node', args: ['x.mjs', '{filesFile}'] }` —— **不走 shell**,文件名含空格也安全(推荐)
|
|
957
|
+
* B. `{ command: 'node x.mjs --mode staged' }` —— 按 shell-like 切词(不启动真 shell)
|
|
958
|
+
* 占位符在两种写法里都替换({repo} / {filesFile} / {filesCount} / {stage})。
|
|
959
|
+
* @param {object} cfg 原运行期配置
|
|
960
|
+
* @param {{command: string, args: string[]}} stage 阶段条目
|
|
961
|
+
* @param {object} ctx 占位符上下文
|
|
962
|
+
* @param {number} timeoutMs 该阶段超时(0=沿用全局)
|
|
963
|
+
* @returns {object}
|
|
964
|
+
*/
|
|
965
|
+
function withCommandStage(cfg, stage, ctx, timeoutMs) {
|
|
966
|
+
const base = (cfg && typeof cfg.preCommit === 'object' && cfg.preCommit) || {};
|
|
967
|
+
const declaredArgs = Array.isArray(stage.args) ? stage.args : [];
|
|
968
|
+
let command = '';
|
|
969
|
+
let args = [];
|
|
970
|
+
if (declaredArgs.length) {
|
|
971
|
+
command = substitutePlaceholders(stage.command, ctx); // A:可执行文件 + 参数数组
|
|
972
|
+
args = declaredArgs.map((a) => substitutePlaceholders(a, ctx));
|
|
973
|
+
} else {
|
|
974
|
+
const words = splitCommandLine(stage.command).map((w) => substitutePlaceholders(w, ctx)); // B:整串切词
|
|
975
|
+
command = words[0] || '';
|
|
976
|
+
args = words.slice(1);
|
|
977
|
+
}
|
|
978
|
+
return {
|
|
979
|
+
...cfg,
|
|
980
|
+
preCommit: {
|
|
981
|
+
...base,
|
|
982
|
+
command: command,
|
|
983
|
+
args: args,
|
|
984
|
+
...(timeoutMs > 0 ? { timeoutMs: timeoutMs } : {}),
|
|
985
|
+
},
|
|
986
|
+
};
|
|
987
|
+
}
|