#!/usr/bin/env node /** * 把版本化的 git 钩子接入提交门禁。 * * 做法:设置 `core.hooksPath = tools/hooks`,而不是把钩子复制进 `.git/hooks/`。 * 原因:`.git/hooks/` 不受版本管理,复制过去后模板更新钩子、克隆者都收不到; * `core.hooksPath` 只是一个仓库级配置项,指向受版本管理的目录,改一次即长期有效。 * * 用法: * node tools/install-hooks.mjs # 安装(设置 core.hooksPath) * node tools/install-hooks.mjs --uninstall # 卸载(清除 core.hooksPath) * * 注:调用 git 时用 `stdio: 'inherit'`,不捕获输出——受限环境(沙箱)里 node 无法为子进程 * 开管道(EPERM),捕获输出会让脚本在能正常写配置的情况下假失败。退出码已足够判定。 */ import { chmodSync, existsSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import { spawnSync } from 'node:child_process'; const ROOT = dirname(dirname(fileURLToPath(import.meta.url))); const HOOKS_DIR = 'tools/hooks'; const UNINSTALL = process.argv.includes('--uninstall'); function git(args) { const r = spawnSync('git', args, { cwd: ROOT, stdio: 'inherit' }); if (r.error) return { status: -1, error: r.error }; return { status: r.status }; } if (!existsSync(join(ROOT, '.git'))) { console.error('[fail] 当前目录不是 git 仓库根(找不到 .git)——钩子只能在仓库内安装。'); process.exit(1); } if (!existsSync(join(ROOT, HOOKS_DIR, 'pre-commit'))) { console.error(`[fail] 缺少钩子源文件:${HOOKS_DIR}/pre-commit`); process.exit(1); } if (UNINSTALL) { const r = git(['config', '--unset', 'core.hooksPath']); if (r.error) { console.error(`[fail] 无法执行 git:${r.error.code || r.error.message}——请在普通终端里重试本命令。`); process.exit(1); } if (r.status === 0) console.log('[ok] 已清除 core.hooksPath(提交门禁停用)'); else console.log('[skip] core.hooksPath 本来就没设置'); process.exit(0); } // Windows 下 chmod 无实际 exec 位作用,但保留以便 POSIX 生效 try { chmodSync(join(ROOT, HOOKS_DIR, 'pre-commit'), 0o755); } catch { /* ignore */ } const set = git(['config', 'core.hooksPath', HOOKS_DIR]); if (set.error) { console.error(`[fail] 无法执行 git:${set.error.code || set.error.message}——请在普通终端里重试本命令。`); process.exit(1); } if (set.status !== 0) { console.error('[fail] 写入 core.hooksPath 失败(见上方 git 输出)。'); process.exit(1); } console.log(`[ok] core.hooksPath = ${HOOKS_DIR}`); // 旧安装方式(复制到 .git/hooks/)会与 core.hooksPath 冲突,提示清掉 const legacy = join(ROOT, '.git', 'hooks', 'pre-commit'); if (existsSync(legacy)) { console.warn('[warn] 检测到 .git/hooks/pre-commit(旧安装方式遗留)——core.hooksPath 生效后它不会再被执行,' + '可安全删除:git config --unset core.hooksPath 后再手工检查。'); } console.log(`[done] 提交门禁已接入 —— rules/ tools/ local-rules/ AGENTS.md project.json 变更时校验规则库,` + `codeScanDirs 下源码变更时跑代码规则检查。`);