package file→ .shtukbase/packages/hooks/run.ts
run.ts
62 lines, 2.8 KB.
- // Runs the hooks of one project for a Git or Claude Code event. The dispatcher selects the project.
- import { spawnSync } from 'node:child_process';
- import { existsSync } from 'node:fs';
- import { resolve } from 'node:path';
- import {
- BLOCK, command, fileOwners, inside, installedPackages, list, normHead, projectRoot, readPayload,
- } from './lib/hooklib.ts';
- const [requested = '', ...eventArgs] = process.argv.slice(2);
- const event = requested.replace(/^agent:/, '');
- const git = event === 'pre-commit' || event === 'commit-msg';
- if (event === 'commit-msg' && eventArgs[0] && process.env.SHTUK_ROOT)
- eventArgs[0] = resolve(process.env.SHTUK_ROOT, eventArgs[0]);
- const { raw, p } = git ? { raw: '', p: null } : readPayload();
- if (!event || (!git && !p)) process.exit(0);
- const files = process.env.SHTUK_FILES?.split('\n').filter(Boolean);
- const owners = files ? fileOwners() : {};
- const dispatched = git || requested.startsWith('agent:') || process.env.SHTUK_FILES !== undefined;
- const root = dispatched ? process.cwd() : projectRoot(p);
- const tool = typeof p?.tool_name === 'string' ? p.tool_name : '';
- const blocks: string[] = [];
- const said: string[] = [];
- const broken: string[] = [];
- for (const pkg of installedPackages(root))
- for (const h of list(pkg.head.hooks)) {
- if (!h || h.event !== event) continue;
- const tools = list(h.tools).map(String);
- if (tools.length && !tools.includes(tool)) continue;
- const env = { ...process.env, CLAUDE_PROJECT_DIR: root };
- if (files?.length) {
- const { except } = normHead(root, h.norm);
- if (Array.isArray(except) && except.length) {
- const kept = files.filter((f) => !Object.hasOwn(owners, f) || !except.includes(owners[f]));
- if (!kept.length) continue;
- env.SHTUK_FILES = kept.join('\n');
- }
- }
- const name = `${pkg.id}/${h.name ?? h.run}`;
- const file = inside(pkg.dir, h.run);
- if (!file || !existsSync(file)) {
- broken.push(`${name}: no file ${h.run}`);
- continue;
- }
- const [exe, args] = command(file);
- const r = spawnSync(exe, [...args, ...eventArgs], {
- cwd: root, input: raw, encoding: 'utf8', timeout: (Number(h.timeout) || 60) * 1000,
- env,
- });
- if (r.status === BLOCK) blocks.push(`[${name}] ${(r.stderr || r.stdout || 'blocks').trim()}`);
- else if (r.status === 0) {
- if (r.stdout?.trim()) said.push(r.stdout.trim());
- } else broken.push(`${name}: ${r.error ? r.error.message : `code ${r.status}`} ${(r.stderr ?? '').trim().split('\n')[0] ?? ''}`.trim());
- }
- if (said.length) process.stdout.write(said.join('\n\n') + '\n');
- if (broken.length) process.stderr.write(broken.map((b) => `hook is broken, skipped: ${b}`).join('\n') + '\n');
- if (blocks.length) {
- process.stderr.write(blocks.join('\n\n') + '\n');
- process.exit(BLOCK);
- }
- process.exit(0);