dsh-git-push 2.14.2 → 2.15.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 CHANGED
@@ -14,6 +14,7 @@ DSH 的 git 提交推送与代码审计插件:提交前自动过审计门禁
14
14
  | 克隆预演 | 只看将拉取什么,不落盘 | `git_clone_preview` / `clone-preview` |
15
15
  | 建远端仓 | 给本地仓库建远端并设置 origin | `git_remote_create` / `remote-create` |
16
16
  | 可见性 | 切换仓库 public / private | `git_set_visibility` / `set-visibility` |
17
+ | 改名 | 给远程仓库改名(dryRun 默认开,列出旧名出现位置) | `git_remote_rename` / `rename` |
17
18
  | 凭据与账号 | 校验 GitHub token 与 SSH 公钥、生成密钥对 | `git_account_check` / `git_gen_ssh_key` |
18
19
  | 身份改写 | 把历史提交身份统一成登录账号 | `git_identity_rewrite` / `identity-rewrite` |
19
20
  | npm 发包 | 发布前体检,默认 dry-run,真发需二次确认 | `npm_publish` / `npm-publish` |
@@ -96,6 +96,15 @@ export const TOOL_REGISTRY = [
96
96
  { flag: 'dryRun', type: 'boolean', desc: '只探测预演' },
97
97
  ],
98
98
  },
99
+ {
100
+ name: 'git_remote_rename', cli: 'rename', description: '给 GitHub 远程仓库改名(PATCH /repos/{owner}/{repo} 的 name 字段)。**dryRun 默认开**:只报告当前名→新名、会改哪些本地 remote,并逐条列出旧名在仓库里出现的位置(package.json/README/CI/文档),确认后传 dryRun=false 才真改;真改成功后自动把 origin 等 remote 同步到新地址。改名不可逆(旧地址只做 301 跳转),外部引用需自行更新',
101
+ params: [
102
+ { flag: 'repo', type: 'string', positional: 0, required: true, desc: '本地 git 仓库绝对路径' },
103
+ { flag: 'newName', type: 'string', positional: 1, required: true, desc: '新仓库名(字母数字 . _ -,≤100 字符)' },
104
+ { flag: 'dryRun', type: 'boolean', desc: '只预演不真改(默认 true)' },
105
+ { flag: 'updateRemotes', type: 'boolean', desc: '改完同步本地 remote(默认 true)' },
106
+ ],
107
+ },
99
108
  {
100
109
  name: 'git_set_visibility', cli: 'set-visibility', description: '切换 GitHub 仓库 public/private(改 public 有敏感信息暴露风险——先确认无凭据/隐私)',
101
110
  params: [
@@ -18,7 +18,7 @@ import { auditWithScope, auditFull, summarize, isBlockerFinding } from '../audit
18
18
  import { formatAnalysisCoverageLine } from '../audit/analysis-coverage.js';
19
19
  import { scoreQuality } from '../score/index.js';
20
20
  import {
21
- cloneViaApi, previewClone, resolveMaxCloneFileMB, ensureRemoteRepo, setVisibility, maintainRepoIndex, updateRepoIndex, resolveToken, commitAndPush,
21
+ cloneViaApi, previewClone, resolveMaxCloneFileMB, ensureRemoteRepo, setVisibility, renameRepo, maintainRepoIndex, updateRepoIndex, resolveToken, commitAndPush,
22
22
  scanReposAsync, scanRepos, checkGithubAccount, formatGithubAccountBlock, generateSshKey, persistSshPub,
23
23
  refreshAccountStatus,
24
24
  } from '../git/index.js';
@@ -602,6 +602,13 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
602
602
  case 'git_set_visibility':
603
603
  if (!args.repo || !args.visibility) return { ok: false, error: 'repo 与 visibility 必填' };
604
604
  return setVisibility({ repoPath: args.repo, visibility: args.visibility });
605
+ case 'git_remote_rename':
606
+ // 改名不可逆:dryRun 默认 true,并把「旧名在仓库里出现的位置」逐条列出
607
+ if (!args.repo || !args.newName) return { ok: false, error: 'repo 与 newName 必填' };
608
+ return renameRepo({
609
+ repoPath: args.repo, newName: args.newName,
610
+ dryRun: args.dryRun !== false, updateRemotes: args.updateRemotes !== false,
611
+ });
605
612
  case 'io_scan': {
606
613
  // 复用 scripts/scan-file-io.mjs(AST 四级分级,与审计 robustness/io-risk 同标准)
607
614
  // 不在此另写扫描逻辑,避免两套判定漂移。
@@ -341,6 +341,17 @@ function isFileGitIgnored(full, gitIgnoreRoot, includeIgnored, respectAuditIgnor
341
341
  }
342
342
 
343
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
+ }
344
355
  const out = [];
345
356
  await walk(dir, 0);
346
357
  // `.auditignore` **文件级**豁免(目录级已在 walk 剪枝)——收集完成后把
@@ -401,6 +412,79 @@ export async function collectTextFiles(dir, { depth = 10, gitIgnoreRoot = null,
401
412
  }
402
413
  }
403
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
+
404
488
  /** 判断目录是否为 git 仓库(有 .git)。 */
405
489
  export function isGitRepo(dir) {
406
490
  return existsSync(join(dir, '.git')) || existsSync(join(dir, '.git', 'HEAD'));
@@ -0,0 +1,91 @@
1
+ /**
2
+ * git 钩子探针:提交/推送前告诉用户「本次会触发哪些钩子」,并识别**坏钩子**。
3
+ *
4
+ * 为什么需要(2026-11-01 同机会话实测移交):CIFS 挂载上的仓库里存在一个从旧机器
5
+ * 随 `.git/` 一起迁过来的 `prepare-commit-msg` 垫片,里面写死了上一台机器的
6
+ * pnpm 绝对路径(`/volume13/...`)。插件对此**零感知**:既不在回执里说明会跑钩子,
7
+ * 也不知道这个钩子一执行就失败。用户只能看到"提交很慢/失败"而没有任何线索。
8
+ *
9
+ * 处置口径(刻意保守):
10
+ * · 默认**照常运行**钩子 —— 很多仓库靠 pre-commit 做 lint/格式化,插件不能替用户关掉;
11
+ * · 只有当钩子**可证明是坏的**(解释器不存在 / 脚本里引用的绝对路径不存在)时,
12
+ * 才为该次提交加 `LEFTHOOK=0`(lefthook 官方跳过开关)+ 在回执里说明原因;
13
+ * · 探针结果始终随回执返回,dryRun 预览里也会列出。
14
+ *
15
+ * 不做 `git config core.hooksPath` 之类的绕法:实测本机对 `.git/config.lock` 的
16
+ * chmod 会 EPERM(`Operation not permitted`),写配置这条路在 CIFS 上根本走不通。
17
+ */
18
+ import { existsSync, readFileSync, statSync } from 'node:fs';
19
+ import { join } from 'node:path';
20
+
21
+ /** 与提交/推送生命周期相关的钩子(顺序即执行顺序)。 */
22
+ export const HOOK_NAMES = ['pre-commit', 'prepare-commit-msg', 'commit-msg', 'post-commit', 'pre-push'];
23
+
24
+ /** 脚本里出现的绝对路径(用于判断「引用的是不是一台不存在的机器上的路径」)。 */
25
+ const ABS_PATH_RE = /(?:^|[\s'"`=])(\/[A-Za-z0-9._\-/]{3,})/g;
26
+
27
+ /**
28
+ * 判断单个钩子是否「可证明坏掉」。
29
+ * @returns {{broken:boolean, reason:string}}
30
+ */
31
+ function inspectHook(path) {
32
+ let text = '';
33
+ try { text = readFileSync(path, 'utf8'); } catch { return { broken: false, reason: '' }; }
34
+ // ① 解释器不存在(shebang 指向的绝对路径)
35
+ const shebang = /^#!\s*(\S+)/.exec(text);
36
+ if (shebang) {
37
+ const interp = shebang[1];
38
+ if (interp.startsWith('/') && !existsSync(interp)) {
39
+ return { broken: true, reason: `解释器不存在:${interp}` };
40
+ }
41
+ }
42
+ // ② 脚本里引用了一个不存在的绝对路径,且该路径带明显的机器前缀(/volume..、/home/..、/Users/..)
43
+ // 只认这类「机器相关」前缀,避免把 `/bin/sh`、`/usr/bin/env` 之类正常路径误判。
44
+ const machineish = /^\/(?:volume\d+|home|Users|Volumes|mnt|opt\/[^/]+\/target)\b/;
45
+ for (const m of text.matchAll(ABS_PATH_RE)) {
46
+ const p = m[1];
47
+ if (!machineish.test(p)) continue;
48
+ if (existsSync(p)) continue;
49
+ return { broken: true, reason: `脚本引用的路径不存在:${p}` };
50
+ }
51
+ return { broken: false, reason: '' };
52
+ }
53
+
54
+ /**
55
+ * 探针:列出该仓库当前会触发的钩子。
56
+ * @param {string} repoPath 仓库根
57
+ * @returns {{items:Array<{name:string, path:string, broken:boolean, reason:string}>,
58
+ * active:string[], broken:string[], env:object}}
59
+ * env = 需要附加到 git 调用的环境变量(仅在存在坏钩子时给 LEFTHOOK=0)
60
+ */
61
+ export function probeHooks(repoPath) {
62
+ const dir = join(repoPath, '.git', 'hooks');
63
+ const items = [];
64
+ for (const name of HOOK_NAMES) {
65
+ const path = join(dir, name);
66
+ let st = null;
67
+ try { st = statSync(path); } catch { continue; }
68
+ if (!st.isFile()) continue;
69
+ const executable = (st.mode & 0o111) !== 0;
70
+ if (!executable) continue; // 不可执行的钩子 git 不会跑,不必列
71
+ const { broken, reason } = inspectHook(path);
72
+ items.push({ name, path, broken, reason });
73
+ }
74
+ const active = items.map((it) => it.name);
75
+ const broken = items.filter((it) => it.broken).map((it) => it.name);
76
+ return {
77
+ items,
78
+ active,
79
+ broken,
80
+ // 只有**存在坏钩子**时才跳过(LEFTHOOK=0 对非 lefthook 钩子无副作用,但这里语义上
81
+ // 只承诺"坏钩子不阻断提交";正常钩子一律照跑)
82
+ env: broken.length ? { LEFTHOOK: '0' } : {},
83
+ };
84
+ }
85
+
86
+ /** 人读的一行摘要(回执/dryRun 用)。 */
87
+ export function describeHooks(probe) {
88
+ if (!probe || !probe.items.length) return '本次不触发任何 git 钩子';
89
+ const parts = probe.items.map((it) => (it.broken ? `${it.name}(坏:${it.reason},已跳过)` : it.name));
90
+ return `本次会触发的 git 钩子:${parts.join(', ')}`;
91
+ }
package/lib/git/index.js CHANGED
@@ -32,6 +32,7 @@ export { fetchRemoteHeads, dispatchPush, pushViaSsh, pushViaApi, sshReason, isNo
32
32
  export { readmeCheckHint, commitAndPush, pushCurrentBranch } from './push.js';
33
33
  export { cloneViaApi, previewClone, resolveMaxCloneFileMB, isPartialCloneDir } from './clone.js';
34
34
  export { ensureRemoteRepo, setVisibility } from './remote.js';
35
+ export { renameRepo } from './rename.js';
35
36
  export { scanRepos, scanReposAsync, collectRepoPaths, describeRepo, describeRepoAsync, maskRemoteUrl } from './repos.js';
36
37
  export { browseDir } from './browse.js';
37
38
  export { listCloudRepos } from './cloud.js';
package/lib/git/push.js CHANGED
@@ -6,6 +6,7 @@
6
6
  * 具体通道实现在 transport.js,本模块只做编排与前置检查。
7
7
  */
8
8
 
9
+ import { describeHooks, probeHooks } from './hooks.js';
9
10
  import { existsSync } from 'node:fs';
10
11
  import { join } from 'node:path';
11
12
  import { autoTagDSHProject, ensureAuxSshRemote, readPkgVersion, updateRemoteTrackingRef } from './post-push.js';
@@ -91,7 +92,15 @@ export async function commitAndPush({ repoPath = '', message = '', messageItems
91
92
  if (!cur.ok) return { ok: false, steps: ['预检'], error: `git 调用失败:${cur.stderr}` };
92
93
  const curBranch = cur.stdout;
93
94
  if (!curBranch) return { ok: false, steps: ['预检'], error: 'HEAD 处于 detached 状态,请先 checkout 分支' };
94
- if (dryRun) return { ok: true, dryRun: true, steps: ['预检', 'commit', push ? 'push' : 'skip-push'] };
95
+ // 钩子探针(只读):回执里说明「本次会触发哪些钩子」,坏钩子会被跳过并附原因。
96
+ // 用户此前对钩子零感知:迁移来的坏钩子让人只看到"提交失败/很慢"却没有任何线索。
97
+ const hookProbe = probeHooks(repoPath);
98
+ if (dryRun) {
99
+ return {
100
+ ok: true, dryRun: true, steps: ['预检', 'commit', push ? 'push' : 'skip-push'],
101
+ hooks: describeHooks(hookProbe), hookNames: hookProbe.active, hooksBroken: hookProbe.broken,
102
+ };
103
+ }
95
104
  // ── 「零改动就不写 .gitignore、不提交」(前置判定)──
96
105
  // 为什么必须前置:仓库没有 .gitignore 时,ensureGitignore 会**新建/追加** .gitignore,
97
106
  // 于是「本来干净的仓」被自己写脏 ⇒ 凭空多出一个只含 .gitignore 的提交 ✗
@@ -169,7 +178,10 @@ export async function commitAndPush({ repoPath = '', message = '', messageItems
169
178
  const identityArgs = identity.complete
170
179
  ? []
171
180
  : ['-c', `user.name=${identity.name}`, '-c', `user.email=${identity.email}`];
172
- const commit = runGit([...identityArgs, 'commit', '-m', commitMessage], { cwd: repoPath });
181
+ // env 只在**存在坏钩子**时给 LEFTHOOK=0(正常钩子一律照跑,不替用户关 lint/格式化)
182
+ const commit = runGit([...identityArgs, 'commit', '-m', commitMessage], {
183
+ cwd: repoPath, ...(Object.keys(hookProbe.env).length ? { env: hookProbe.env } : {}),
184
+ });
173
185
  if (!commit.ok) {
174
186
  if (/nothing to commit|no changes added/i.test(commit.stderr)) {
175
187
  // 同上:git 自己回「nothing to commit」也只是「没东西可提交」,属于成功跳过
@@ -179,7 +191,10 @@ export async function commitAndPush({ repoPath = '', message = '', messageItems
179
191
  }
180
192
  }
181
193
  const commitSha = runGit(['rev-parse', 'HEAD'], { cwd: repoPath }).stdout;
182
- if (!push) return { ok: true, steps: [...steps, 'skip-push'], commitSha, pushed: false, committed: !cleanSkipCommit, identity, legacyIdentity };
194
+ if (!push) return {
195
+ ok: true, steps: [...steps, 'skip-push'], commitSha, pushed: false, committed: !cleanSkipCommit, identity, legacyIdentity,
196
+ hooks: describeHooks(hookProbe), hooksBroken: hookProbe.broken,
197
+ };
183
198
  // 推送门禁(类似会话指挥家写操作拦截)——开启后 push 必须带 pushConfirmed:true
184
199
  // (显式放行标记),否则**拦截推送步骤**(commit 已落本地,push 被挡、不产生远端变更)。
185
200
  if (pushGate && !pushConfirmed) {
@@ -0,0 +1,137 @@
1
+ /**
2
+ * 远程仓库改名(GitHub `PATCH /repos/{owner}/{repo}` 的 `name` 字段)。
3
+ *
4
+ * 为什么单独做一个动作:改名前要看清**旧名散落在哪里**(package.json 的 name/repository、
5
+ * README 里的克隆地址、CI 配置、文档链接……),改完还要把本地 remote 同步过去。
6
+ * 这些如果交给用户手工做,最常见的结局是「远端改了、本地还指着旧的」,
7
+ * 或者包名/文档链接集体失效。故 dryRun 默认开启,并**逐条列出旧名出现位置**。
8
+ *
9
+ * 不可逆性:改名后旧地址 301 跳转到新地址(clone/issue/PR 跟着走),但外部引用
10
+ * (npm 包元数据、第三方文档)不会自动更新;所以默认 dryRun=true,必须显式关闭才真改。
11
+ */
12
+ import { runGit } from './exec.js';
13
+ import { resolveToken } from './credentials.js';
14
+ import { githubFetch } from './api.js';
15
+ import { parseOwnerRepoFromRemote } from './remote.js';
16
+
17
+ /** GitHub 仓库名规则:字母数字与 `._-`,不超过 100 字符。 */
18
+ const NAME_RE = /^[A-Za-z0-9._-]{1,100}$/;
19
+
20
+ /**
21
+ * 扫描旧仓库名在仓库内的出现位置(dryRun 用)。
22
+ *
23
+ * 用 `git grep`(比 FS 递归快几个数量级,挂载盘上尤其明显);带超时与条数上限,
24
+ * 宁可少报也不让探针本身把 dryRun 拖住。非 git 目录返回 skipped。
25
+ * @returns {{scanned:boolean, total:number, byFile:Record<string,number>, samples:Array<{file:string,line:number,text:string}>}}
26
+ */
27
+ export function scanOldName(repoPath, oldName, { limit = 60, timeoutMs = 20000 } = {}) {
28
+ const empty = { scanned: false, total: 0, byFile: {}, samples: [], urlLike: 0 };
29
+ if (!oldName) return empty;
30
+ const res = runGit(['grep', '-n', '-I', '-F', '--no-color', '-e', oldName, '--', '.'], { cwd: repoPath, timeoutMs });
31
+ if (!res.ok && !res.stdout) return { ...empty, skipped: res.stderr?.slice(0, 200) || 'git grep 失败' };
32
+ const urlSamples = []; // URL 形态优先展示:改名后**必须**改的就是它们
33
+ const textSamples = [];
34
+ const byFile = {};
35
+ let total = 0;
36
+ let urlLike = 0;
37
+ // 分类:「URL 形态」(github.com/owner/repo、git@…:owner/repo.git 等,改名后**必须**跟着改)
38
+ // 与「普通文字」(说明/标题/user.name,通常不用改)。dryRun 里分开报,避免 293 条一起糊上来。
39
+ const urlRe = new RegExp(`(github\\.com|ssh\\.github\\.com)[/:][^/\\s:]+/${oldName}(\\.git)?\\b`, 'i');
40
+ for (const line of String(res.stdout || '').split('\n')) {
41
+ if (!line.trim()) continue;
42
+ // 形如 `path:12:内容`
43
+ const m = /^([^:]+):(\d+):(.*)$/.exec(line);
44
+ if (!m) continue;
45
+ total += 1;
46
+ const isUrl = urlRe.test(m[3]);
47
+ if (isUrl) urlLike += 1;
48
+ byFile[m[1]] = (byFile[m[1]] || 0) + 1;
49
+ const item = { file: m[1], line: Number(m[2]), kind: isUrl ? 'url' : 'text', text: m[3].trim().slice(0, 160) };
50
+ if (isUrl) urlSamples.push(item); else textSamples.push(item);
51
+ }
52
+ const samples = [...urlSamples, ...textSamples].slice(0, limit);
53
+ return { scanned: true, total, urlLike, byFile, samples };
54
+ }
55
+
56
+ /** 列出指向该仓库的本地 remote(含 URL,便于回执里说明会改哪几条)。 */
57
+ export function remotesPointingTo(repoPath, owner, repo) {
58
+ const res = runGit(['remote', '-v'], { cwd: repoPath });
59
+ const out = [];
60
+ for (const line of String(res.stdout || '').split('\n')) {
61
+ const m = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(line.trim());
62
+ if (!m) continue;
63
+ const [, name, url] = m;
64
+ if (!new RegExp(`[/:]${owner}/${repo}(\\.git)?/?$`, 'i').test(url)) continue;
65
+ if (out.some((it) => it.name === name)) continue;
66
+ out.push({ name, url });
67
+ }
68
+ return out;
69
+ }
70
+
71
+ /**
72
+ * 改名主流程。
73
+ * @param {{repoPath?:string, owner?:string, repo?:string, newName:string, dryRun?:boolean,
74
+ * token?:string, updateRemotes?:boolean, scanLimit?:number}} o
75
+ */
76
+ export async function renameRepo({
77
+ repoPath = '', owner = '', repo = '', newName = '', dryRun = true, token = '', updateRemotes = true, scanLimit = 60,
78
+ } = {}) {
79
+ const target = String(newName || '').trim();
80
+ if (!NAME_RE.test(target)) return { ok: false, error: `新仓库名不合法(只允许字母数字 . _ -,≤100 字符):${target || '(空)'}` };
81
+ if (!repoPath) return { ok: false, error: 'repo 必填(本地仓库路径)' };
82
+ // 从 origin 解析 owner/repo(与 git_set_visibility 同口径)
83
+ if (!owner || !repo) {
84
+ const cur = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath });
85
+ const parsed = parseOwnerRepoFromRemote(cur.stdout || cur.stderr || '');
86
+ owner = owner || parsed.owner;
87
+ repo = repo || parsed.repo;
88
+ }
89
+ if (!owner || !repo) return { ok: false, error: '缺 owner/repo(origin 里解析不出 GitHub 地址)' };
90
+ if (target === repo) return { ok: false, error: `新名与当前名相同:${repo}` };
91
+
92
+ const tok = token || resolveToken({ workspaceRoot: repoPath }).token;
93
+ if (!tok) return { ok: false, error: '无 token' };
94
+
95
+ // 远端现状(顺带确认仓库存在、以及现在的 full_name)
96
+ const info = await githubFetch(`/repos/${owner}/${repo}`, { token: tok });
97
+ if (info.status !== 200) return { ok: false, error: info.json?.message || info.error || `HTTP ${info.status}` };
98
+ const current = { owner, repo, fullName: info.json?.full_name || `${owner}/${repo}`, private: info.json?.private === true, htmlUrl: info.json?.html_url || '' };
99
+
100
+ const remotes = remotesPointingTo(repoPath, owner, repo);
101
+ const occurrences = scanOldName(repoPath, repo, { limit: scanLimit });
102
+
103
+ if (dryRun) {
104
+ return {
105
+ ok: true, dryRun: true, current, target: { owner, repo: target, fullName: `${owner}/${target}` },
106
+ remotes, occurrences,
107
+ hint: '确认无误后传 dryRun=false 才真正改名;改名不可逆(旧地址只做 301 跳转)',
108
+ };
109
+ }
110
+
111
+ const patched = await githubFetch(`/repos/${owner}/${repo}`, { token: tok, method: 'PATCH', body: { name: target } });
112
+ if (patched.status !== 200) return { ok: false, error: patched.json?.message || patched.error || `HTTP ${patched.status}`, current };
113
+
114
+ // 同步本地 remote(GitHub 会给旧地址 301,但别依赖跳转:SSH remote 不一定跟着走)
115
+ const updated = [];
116
+ if (updateRemotes) {
117
+ for (const r of remotes) {
118
+ const nextUrl = String(r.url).replace(new RegExp(`([/:])${owner}/${repo}(\\.git)?/?$`, 'i'), `$1${owner}/${target}$2`);
119
+ if (nextUrl === r.url) continue;
120
+ const set = runGit(['remote', 'set-url', r.name, nextUrl], { cwd: repoPath });
121
+ updated.push({ name: r.name, from: r.url, to: nextUrl, ok: set.ok, error: set.ok ? '' : String(set.stderr || '').slice(0, 200) });
122
+ }
123
+ }
124
+ return {
125
+ ok: true, dryRun: false,
126
+ current, renamedTo: { owner, repo: target, fullName: patched.json?.full_name || `${owner}/${target}` },
127
+ remotesUpdated: updated,
128
+ occurrences,
129
+ // URL 形态的出现位置 = 改名后**必须**更新引用(其余是文字提及,通常不用动)
130
+ urlOccurrencesHint: occurrences.scanned && occurrences.urlLike > 0
131
+ ? `仓库内有 ${occurrences.urlLike} 处 URL 形态引用仍写着旧名,建议一并更新`
132
+ : '',
133
+ hint: updated.some((u) => !u.ok)
134
+ ? '远端已改名,但有本地 remote 未更新成功——请手工执行 git remote set-url 修正'
135
+ : '远端与本地 remote 均已指向新名;外部引用(npm 包元数据/第三方文档)需自行更新',
136
+ };
137
+ }
package/lib/self/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
 
12
- export const VERSION = '2.14.2'; // 2.14.2:mkdir-before-write 的作用域判定修正(外部复测 16→21 的净增根因)。三处硬伤:①「非函数关键字」负向前瞻没加词边界,`if (!x) {` 会从第二个字符 `f (!x) {` 被当成函数起点、`} catch (e) {` 会从 `atch (e) {` 被匹配 ⇒ 作用域一步错全盘错;②数花括号前没剔除字符串/注释里的括号,配平被带偏;③解构参数 `function f({ a, b }) {` 的花括号把深度配平到 0 ⇒ 作用域结束在本行。另加:作用域并入「包含写语句的顶层函数」(写语句常在嵌套回调里),以及 best-effort 写入(try 内 + catch 兜底)降级为提示。实测 ModelStage:21 条 → 1 条(剩余那条 mkdir 在另一个顶层函数里,跨函数静态证明不了)。历史:2.14.1 认封装与一层间接。
12
+ export const VERSION = '2.15.0'; // 2.15.0:挂载盘采集走 git 快路径 + git 钩子探针。①采集提速:CIFS 上「231 个文本文件」的文件系统遍历实测 103.8s(sys 29s,全耗在跨网 stat),改走 `git ls-files --cached --others --exclude-standard` 后 0.1s(同一仓库实测),语义与原遍历对齐(已跟踪 + 未跟踪未忽略;.gitignore/.auditignore 照旧生效;非 git 目录仍走原遍历;可用 DSH_AUDIT_NO_GIT_FASTPATH=1 关闭);顺带修掉旧遍历漏判文件级 ignore 的问题。②钩子探针:提交/预演回执里列出本次会触发的钩子,识别「解释器不存在 / 引用了已不存在的机器路径」的坏钩子,仅在这种情况下给 LEFTHOOK=0 —— 正常钩子(lint/格式化)一律照跑,不替用户关。历史:2.14.2 mkdir 作用域判定修正。
13
13
  // 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
14
14
  // 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
15
15
  // 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-git-push",
3
- "version": "2.14.2",
3
+ "version": "2.15.0",
4
4
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",