ShtukbaseStandard
файл пакета→ .shtukbase/packages/hooks/install.ts

install.ts

100 строк, 4.3 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // Sync, remove and check the repository's Git stubs and Claude Code dispatcher entries.
  2. import { existsSync, readFileSync } from 'node:fs';
  3. import { join } from 'node:path';
  4. import { gitHooks, repoRoot } from './lib/git-hooks.ts';
  5. import { replaceFile } from './lib/write.ts';
  6. const command = (event: string) => `shtuk hook agent:${event}`;
  7. const OURS: { event: string; matcher?: string; timeout: number }[] = [
  8. { event: 'SessionStart', timeout: 120 },
  9. { event: 'PreToolUse', matcher: 'Bash|Write|Edit|MultiEdit', timeout: 30 },
  10. { event: 'PostToolUse', matcher: 'Write|Edit|MultiEdit', timeout: 60 },
  11. { event: 'Stop', timeout: 180 },
  12. ];
  13. type Settings = Record<string, any>;
  14. const ours = (h: any) => typeof h?.command === 'string' &&
  15. (h.command.includes('.shtukbase/packages/hooks/') || /^shtuk hook agent:\S+$/.test(h.command));
  16. function load(file: string): Settings {
  17. if (!existsSync(file)) return {};
  18. const text = readFileSync(file, 'utf8');
  19. if (!text.trim()) return {};
  20. const s = JSON.parse(text);
  21. if (!s || typeof s !== 'object' || Array.isArray(s)) throw new Error('not a JSON object');
  22. return s;
  23. }
  24. function strip(s: Settings): void {
  25. const hooks = s.hooks;
  26. if (!hooks || typeof hooks !== 'object') return;
  27. for (const ev of Object.keys(hooks)) {
  28. if (!Array.isArray(hooks[ev])) continue;
  29. hooks[ev] = hooks[ev]
  30. .map((g: any) => {
  31. if (!Array.isArray(g?.hooks)) return g;
  32. return { ...g, hooks: g.hooks.filter((h: any) => !ours(h)) };
  33. })
  34. .filter((g: any) => !Array.isArray(g?.hooks) || g.hooks.length);
  35. if (!hooks[ev].length) delete hooks[ev];
  36. }
  37. if (!Object.keys(hooks).length) delete s.hooks;
  38. }
  39. function add(s: Settings): void {
  40. s.hooks ??= {};
  41. for (const o of OURS) {
  42. const group: any = o.matcher ? { matcher: o.matcher } : {};
  43. group.hooks = [{ type: 'command', command: command(o.event), timeout: o.timeout }];
  44. (s.hooks[o.event] ??= []).push(group);
  45. }
  46. }
  47. /** Findings for the check: what is missing or extra; empty when all stands. */
  48. export function problems(s: Settings): string[] {
  49. const out: string[] = [];
  50. for (const o of OURS) {
  51. const groups = Array.isArray(s.hooks?.[o.event]) ? s.hooks[o.event] : [];
  52. const found = groups.flatMap((g: any) => (Array.isArray(g?.hooks) ? g.hooks.filter(ours).map((h: any) => ({ g, h })) : []));
  53. const right = found.filter(({ g, h }: any) =>
  54. h.type === 'command' && h.command === command(o.event) && h.timeout === o.timeout &&
  55. (g.matcher ?? undefined) === o.matcher);
  56. if (!found.length) out.push(`.claude/settings.json: no hook ${o.event} of the package hooks → shtuk run hooks sync`);
  57. else if (!right.length) out.push(`.claude/settings.json: the hook ${o.event} of the package hooks is outdated → shtuk run hooks sync`);
  58. 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`);
  59. }
  60. for (const [ev, groups] of Object.entries(s.hooks ?? {}))
  61. if (!OURS.some((o) => o.event === ev) && Array.isArray(groups) &&
  62. groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some(ours)))
  63. out.push(`.claude/settings.json: an extra hook ${ev} of the package hooks → shtuk run hooks sync`);
  64. return out;
  65. }
  66. export function main(mode: 'sync' | 'remove' | 'check'): void {
  67. const project = process.cwd();
  68. const root = repoRoot(project);
  69. const file = join(root ?? project, '.claude', 'settings.json');
  70. let s: Settings;
  71. try {
  72. s = load(file);
  73. } catch (e) {
  74. 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`);
  75. process.exit(1);
  76. }
  77. try {
  78. if (mode === 'check') {
  79. const out = [...problems(s), ...(root ? gitHooks(root, mode) : [])];
  80. if (out.length) console.log(out.join('\n'));
  81. process.exit(out.length ? 1 : 0);
  82. }
  83. const before = JSON.stringify(s);
  84. strip(s);
  85. if (mode === 'sync') add(s);
  86. if (root) gitHooks(root, mode);
  87. if (JSON.stringify(s) !== before) replaceFile(file, JSON.stringify(s, null, 2) + '\n', 'utf8');
  88. console.log(`hooks: dispatcher entries ${mode === 'sync' ? 'installed' : 'removed'}`);
  89. } catch (e) {
  90. console.log(`hooks: ${(e as Error).message}`);
  91. process.exit(1);
  92. }
  93. }