包文件→ .shtukbase/packages/hooks/install.ts
install.ts
100 行, 4.3 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // Sync, remove and check the repository's Git stubs and Claude Code dispatcher entries.
- import { existsSync, readFileSync } from 'node:fs';
- import { join } from 'node:path';
- import { gitHooks, repoRoot } from './lib/git-hooks.ts';
- import { replaceFile } from './lib/write.ts';
- const command = (event: string) => `shtuk hook agent:${event}`;
- const OURS: { event: string; matcher?: string; timeout: number }[] = [
- { event: 'SessionStart', timeout: 120 },
- { event: 'PreToolUse', matcher: 'Bash|Write|Edit|MultiEdit', timeout: 30 },
- { event: 'PostToolUse', matcher: 'Write|Edit|MultiEdit', timeout: 60 },
- { event: 'Stop', timeout: 180 },
- ];
- type Settings = Record<string, any>;
- const ours = (h: any) => typeof h?.command === 'string' &&
- (h.command.includes('.shtukbase/packages/hooks/') || /^shtuk hook agent:\S+$/.test(h.command));
- function load(file: string): Settings {
- if (!existsSync(file)) return {};
- const text = readFileSync(file, 'utf8');
- if (!text.trim()) return {};
- const s = JSON.parse(text);
- if (!s || typeof s !== 'object' || Array.isArray(s)) throw new Error('not a JSON object');
- return s;
- }
- function strip(s: Settings): void {
- const hooks = s.hooks;
- if (!hooks || typeof hooks !== 'object') return;
- for (const ev of Object.keys(hooks)) {
- if (!Array.isArray(hooks[ev])) continue;
- hooks[ev] = hooks[ev]
- .map((g: any) => {
- if (!Array.isArray(g?.hooks)) return g;
- return { ...g, hooks: g.hooks.filter((h: any) => !ours(h)) };
- })
- .filter((g: any) => !Array.isArray(g?.hooks) || g.hooks.length);
- if (!hooks[ev].length) delete hooks[ev];
- }
- if (!Object.keys(hooks).length) delete s.hooks;
- }
- function add(s: Settings): void {
- s.hooks ??= {};
- for (const o of OURS) {
- const group: any = o.matcher ? { matcher: o.matcher } : {};
- group.hooks = [{ type: 'command', command: command(o.event), timeout: o.timeout }];
- (s.hooks[o.event] ??= []).push(group);
- }
- }
- /** Findings for the check: what is missing or extra; empty when all stands. */
- export function problems(s: Settings): string[] {
- const out: string[] = [];
- for (const o of OURS) {
- const groups = Array.isArray(s.hooks?.[o.event]) ? s.hooks[o.event] : [];
- const found = groups.flatMap((g: any) => (Array.isArray(g?.hooks) ? g.hooks.filter(ours).map((h: any) => ({ g, h })) : []));
- const right = found.filter(({ g, h }: any) =>
- h.type === 'command' && h.command === command(o.event) && h.timeout === o.timeout &&
- (g.matcher ?? undefined) === o.matcher);
- if (!found.length) out.push(`.claude/settings.json: no hook ${o.event} of the package hooks → shtuk run hooks sync`);
- else if (!right.length) out.push(`.claude/settings.json: the hook ${o.event} of the package hooks is outdated → shtuk run hooks sync`);
- else if (found.length > 1) out.push(`.claude/settings.json: the hook ${o.event} of the package hooks stands ${found.length} times → shtuk run hooks sync`);
- }
- for (const [ev, groups] of Object.entries(s.hooks ?? {}))
- if (!OURS.some((o) => o.event === ev) && Array.isArray(groups) &&
- groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some(ours)))
- out.push(`.claude/settings.json: an extra hook ${ev} of the package hooks → shtuk run hooks sync`);
- return out;
- }
- export function main(mode: 'sync' | 'remove' | 'check'): void {
- const project = process.cwd();
- const root = repoRoot(project);
- const file = join(root ?? project, '.claude', 'settings.json');
- let s: Settings;
- try {
- s = load(file);
- } catch (e) {
- console.log(`.claude/settings.json cannot be read as JSON (${(e as Error).message}); the file is untouched — fix it and run shtuk run hooks sync`);
- process.exit(1);
- }
- try {
- if (mode === 'check') {
- const out = [...problems(s), ...(root ? gitHooks(root, mode) : [])];
- if (out.length) console.log(out.join('\n'));
- process.exit(out.length ? 1 : 0);
- }
- const before = JSON.stringify(s);
- strip(s);
- if (mode === 'sync') add(s);
- if (root) gitHooks(root, mode);
- if (JSON.stringify(s) !== before) replaceFile(file, JSON.stringify(s, null, 2) + '\n', 'utf8');
- console.log(`hooks: dispatcher entries ${mode === 'sync' ? 'installed' : 'removed'}`);
- } catch (e) {
- console.log(`hooks: ${(e as Error).message}`);
- process.exit(1);
- }
- }