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

test/hooks.test.ts

224 строки, 10.1 КБ.

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

  1. import { afterEach, beforeEach, expect, test } from 'bun:test';
  2. import { spawnSync } from 'node:child_process';
  3. import {
  4. existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync,
  5. } from 'node:fs';
  6. import { tmpdir } from 'node:os';
  7. import { dirname, join } from 'node:path';
  8. const source = dirname(import.meta.dir);
  9. const norm = 'norms/rules/hooks/HK-R03.md';
  10. const gitEnv = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
  11. let temp: string;
  12. let repo: string;
  13. let project: string;
  14. function git(...args: string[]): string {
  15. const result = spawnSync('git', args, { cwd: repo, env: gitEnv, encoding: 'utf8' });
  16. if (result.status !== 0) throw new Error(result.stderr || String(result.error));
  17. return result.stdout.trimEnd();
  18. }
  19. function write(file: string, content: string, mode?: number): void {
  20. mkdirSync(dirname(file), { recursive: true });
  21. writeFileSync(file, content, { mode });
  22. }
  23. function run(script: string, args: string[] = [], env: NodeJS.ProcessEnv = {}, input = '') {
  24. return spawnSync(process.execPath, [join(source, script), ...args], {
  25. cwd: project, input, encoding: 'utf8', env: { ...gitEnv, ...env }, timeout: 10_000,
  26. });
  27. }
  28. function requireSuccess(result: ReturnType<typeof run>): void {
  29. if (result.status !== 0) throw new Error(result.stderr || result.stdout || String(result.error));
  30. }
  31. const read = (file: string) => readFileSync(file, 'utf8');
  32. const settings = () => join(repo, '.claude/settings.json');
  33. const stubs = () => git('rev-parse', '--path-format=absolute', '--git-path', 'hooks');
  34. const blockCount = (file: string) => read(file).split('# >>> shtuk hook >>>').length - 1;
  35. beforeEach(() => {
  36. temp = mkdtempSync(join(realpathSync(tmpdir()), 'shtuk-hooks-'));
  37. repo = join(temp, 'repo');
  38. mkdirSync(repo);
  39. git('init', '-q');
  40. git('config', 'user.name', 'Hook Test');
  41. git('config', 'user.email', 'hooks@example.invalid');
  42. project = join(repo, 'workspace', 'projects', 'site');
  43. mkdirSync(join(project, '.shtukbase', 'packages'), { recursive: true });
  44. });
  45. afterEach(() => rmSync(temp, { recursive: true, force: true }));
  46. test('nested installs share one pair of stubs and one set of repo-level settings', () => {
  47. expect(run('installed.ts').status).toBe(1);
  48. requireSuccess(run('sync.ts'));
  49. for (const event of ['pre-commit', 'commit-msg']) {
  50. const file = join(stubs(), event);
  51. expect(blockCount(file)).toBe(1);
  52. expect(statSync(file).mode & 0o100).toBe(0o100);
  53. }
  54. expect(read(join(stubs(), 'commit-msg'))).toContain('shtuk hook commit-msg "$1"');
  55. const initialSettings = read(settings());
  56. project = join(repo, 'workspace', 'projects', 'cloud');
  57. mkdirSync(join(project, '.shtukbase'), { recursive: true });
  58. requireSuccess(run('sync.ts'));
  59. requireSuccess(run('installed.ts'));
  60. expect(read(settings())).toBe(initialSettings);
  61. const claude = JSON.parse(initialSettings);
  62. expect(Object.keys(claude.hooks)).toEqual(['SessionStart', 'PreToolUse', 'PostToolUse', 'Stop']);
  63. for (const [event, groups] of Object.entries(claude.hooks)) {
  64. expect(groups).toEqual([expect.objectContaining({
  65. hooks: [expect.objectContaining({ command: `shtuk hook agent:${event}` })],
  66. })]);
  67. }
  68. expect(existsSync(join(project, '.claude'))).toBe(false);
  69. requireSuccess(run('remove.ts'));
  70. expect(existsSync(join(stubs(), 'pre-commit'))).toBe(false);
  71. expect(existsSync(join(stubs(), 'commit-msg'))).toBe(false);
  72. expect(JSON.parse(read(settings()))).toEqual({});
  73. });
  74. test('foreign hooks and Claude entries survive sync and remove', () => {
  75. const file = join(stubs(), 'pre-commit');
  76. const foreign = '#!/bin/sh\nprintf "foreign\n"';
  77. write(file, foreign, 0o644);
  78. const otherHook = { type: 'command', command: 'other-command', timeout: 8 };
  79. const existing = {
  80. permissions: { allow: ['Read'] },
  81. hooks: {
  82. PreToolUse: [{
  83. matcher: 'Write', hooks: [
  84. otherHook, { type: 'command', command: 'bun "$CLAUDE_PROJECT_DIR/.shtukbase/packages/hooks/run.ts" PreToolUse' },
  85. ],
  86. }],
  87. },
  88. };
  89. write(settings(), JSON.stringify(existing));
  90. requireSuccess(run('sync.ts'));
  91. const synced = read(file);
  92. expect(synced.startsWith(foreign + '\n')).toBe(true);
  93. expect(blockCount(file)).toBe(1);
  94. expect(statSync(file).mode & 0o100).toBe(0o100);
  95. requireSuccess(run('sync.ts'));
  96. expect(read(file)).toBe(synced);
  97. requireSuccess(run('installed.ts'));
  98. writeFileSync(file, synced + synced.slice(foreign.length));
  99. expect(run('installed.ts').stdout).toContain('Git pre-commit');
  100. requireSuccess(run('sync.ts'));
  101. expect(read(file)).toBe(synced);
  102. const claude = JSON.parse(read(settings()));
  103. claude.hooks.PreToolUse.push(claude.hooks.PreToolUse[1]);
  104. write(settings(), JSON.stringify(claude));
  105. expect(run('installed.ts').stdout).toContain('PreToolUse of the package hooks stands 2 times');
  106. requireSuccess(run('sync.ts'));
  107. requireSuccess(run('remove.ts'));
  108. expect(read(file)).toBe(foreign);
  109. expect(statSync(file).mode & 0o111).toBe(0);
  110. existing.hooks.PreToolUse[0].hooks.pop();
  111. expect(JSON.parse(read(settings()))).toEqual(existing);
  112. });
  113. test('Git uses relative core.hooksPath and passes the commit message path', () => {
  114. git('config', 'core.hooksPath', 'custom hooks');
  115. expect(stubs()).toBe(join(repo, 'custom hooks'));
  116. write(join(stubs(), 'pre-commit'), '#!/bin/sh\nprintf "existing\n" >> "$HOOK_LOG"\ntest ! -e reject\n', 0o755);
  117. requireSuccess(run('sync.ts'));
  118. const log = join(temp, 'hook log');
  119. const bin = join(temp, 'bin');
  120. write(join(bin, 'shtuk'), '#!/bin/sh\nprintf "<%s>\n" "$@" >> "$HOOK_LOG"\n', 0o755);
  121. const commit = () => spawnSync('git', ['commit', '-qm', 'test hooks', '--allow-empty'], {
  122. cwd: repo, encoding: 'utf8', env: { ...gitEnv, HOOK_LOG: log, PATH: bin + ':' + gitEnv.PATH },
  123. });
  124. const result = commit();
  125. if (result.status !== 0) throw new Error(result.stderr);
  126. expect(read(log)).toBe('existing\n<hook>\n<pre-commit>\n<hook>\n<commit-msg>\n<.git/COMMIT_EDITMSG>\n');
  127. expect(existsSync(join(repo, '.git/hooks/pre-commit'))).toBe(false);
  128. write(join(repo, 'reject'), '');
  129. expect(commit().status).toBe(1);
  130. expect(read(log)).toEndWith('<.git/COMMIT_EDITMSG>\nexisting\n');
  131. });
  132. test('the .git file in a linked worktree selects its Claude settings', () => {
  133. git('commit', '-qm', 'initial', '--allow-empty');
  134. const worktree = join(temp, 'linked');
  135. git('worktree', 'add', '-qb', 'linked', worktree);
  136. project = join(worktree, 'project');
  137. mkdirSync(join(project, '.shtukbase'), { recursive: true });
  138. requireSuccess(run('sync.ts'));
  139. requireSuccess(run('installed.ts'));
  140. expect(existsSync(join(worktree, '.claude/settings.json'))).toBe(true);
  141. expect(existsSync(settings())).toBe(false);
  142. expect(existsSync(join(stubs(), 'pre-commit'))).toBe(true);
  143. });
  144. test('invalid Claude settings are kept intact', () => {
  145. write(settings(), '{broken');
  146. expect(run('sync.ts').status).toBe(1);
  147. expect(read(settings())).toBe('{broken');
  148. expect(existsSync(join(stubs(), 'pre-commit'))).toBe(false);
  149. });
  150. test('HK-R03 observes mixed owners by default and blocks in enforce mode', () => {
  151. symlinkSync(source, join(project, '.shtukbase/packages/hooks'), 'dir');
  152. const page = join(project, norm);
  153. const initial = read(join(source, 'pages', norm));
  154. write(page, initial);
  155. const files = 'apps/site/file.txt';
  156. const mixed = { [files]: 'site', 'cloud/file.txt': 'cloud', 'README.md': null };
  157. const observed = run('run.ts', ['pre-commit'], { SHTUK_FILES: files, SHTUK_OWNERS: JSON.stringify(mixed) });
  158. requireSuccess(observed);
  159. expect(observed.stdout).toContain('HK-R03');
  160. expect(observed.stdout).toContain('(cloud, site)');
  161. write(page, initial.replace('mode: observe', 'mode: enforce'));
  162. const blocked = run('run.ts', ['pre-commit'], { SHTUK_FILES: files, SHTUK_OWNERS: JSON.stringify(mixed) });
  163. expect(blocked.status).toBe(2);
  164. expect(blocked.stderr).toContain('HK-R03');
  165. const clean = run('run.ts', ['pre-commit'], {
  166. SHTUK_FILES: files, SHTUK_OWNERS: JSON.stringify({ ...mixed, 'cloud/file.txt': 'site' }),
  167. });
  168. requireSuccess(clean);
  169. expect(clean.stdout).toBe('');
  170. });
  171. test('except filters each Git hook independently and preserves unowned files and event args', () => {
  172. const pkg = join(project, '.shtukbase/packages/sample');
  173. write(join(pkg, 'package.md'), `---
  174. hooks:
  175. - {name: filtered, event: commit-msg, run: filtered.ts, norm: /norms/sample.md}
  176. - {name: all, event: commit-msg, run: all.ts}
  177. - {name: other-event, event: pre-commit, run: missing.ts}
  178. ---
  179. `);
  180. write(join(pkg, 'filtered.ts'), 'console.log(JSON.stringify([process.env.SHTUK_FILES, ...process.argv.slice(2)]))');
  181. write(join(pkg, 'all.ts'), 'console.log(JSON.stringify(["all", process.env.SHTUK_FILES]))');
  182. write(join(project, 'norms/sample.md'), '---\nexcept: [cloud]\n---\n');
  183. const args = ['commit-msg', 'path with spaces/COMMIT_EDITMSG'];
  184. const owners = JSON.stringify({ 'cloud/file': 'cloud', 'site/file': 'site', README: null });
  185. const files = 'cloud/file\nsite/file\nREADME';
  186. const result = run('run.ts', args, { SHTUK_FILES: files, SHTUK_OWNERS: owners, SHTUK_ROOT: repo });
  187. requireSuccess(result);
  188. expect(result.stdout.trim().split('\n\n').map((line) => JSON.parse(line))).toEqual([
  189. ['site/file\nREADME', join(repo, args[1])], ['all', files],
  190. ]);
  191. const skipped = run('run.ts', args, { SHTUK_FILES: 'cloud/file', SHTUK_OWNERS: owners });
  192. requireSuccess(skipped);
  193. expect(JSON.parse(skipped.stdout)).toEqual(['all', 'cloud/file']);
  194. });
  195. test('a dispatched Claude event uses the selected project and the original tool payload', () => {
  196. const pkg = join(project, '.shtukbase/packages/sample');
  197. write(join(pkg, 'package.md'), '---\nhooks: [{event: PreToolUse, tools: [Write], run: capture.ts}]\n---\n');
  198. write(join(pkg, 'capture.ts'), `
  199. const payload = await Bun.stdin.json();
  200. console.log(JSON.stringify([process.env.CLAUDE_PROJECT_DIR, payload]));
  201. `);
  202. const payload = { tool_name: 'Write', cwd: repo, tool_input: { file_path: 'note.md' } };
  203. const result = run('run.ts', ['agent:PreToolUse'], { CLAUDE_PROJECT_DIR: repo }, JSON.stringify(payload));
  204. requireSuccess(result);
  205. expect(JSON.parse(result.stdout)).toEqual([project, payload]);
  206. });