ShtukbaseStandard
package file→ .shtukbase/packages/hooks/lib/git-hooks.ts

lib/git-hooks.ts

71 lines, 3.0 KB.

  1. import { spawnSync } from 'node:child_process';
  2. import { existsSync, readFileSync, rmSync, statSync } from 'node:fs';
  3. import { dirname, join, resolve } from 'node:path';
  4. import { replaceFile } from './write.ts';
  5. const EVENTS = ['pre-commit', 'commit-msg'] as const;
  6. const START = '# >>> shtuk hook >>>';
  7. const END = '# <<< shtuk hook <<<';
  8. const HEADER = '#!/bin/sh\n# Generated by shtuk.\n';
  9. const EXEC = '# shtuk made this hook executable';
  10. const BLOCKS = /(?:^|\n)# >>> shtuk hook >>>\r?\n[\s\S]*?^# <<< shtuk hook <<<(?:\r?\n|$)/gm;
  11. export function repoRoot(from: string): string | null {
  12. for (let dir = from; ; dir = dirname(dir)) {
  13. if (existsSync(join(dir, '.git'))) return dir;
  14. if (dir === dirname(dir)) return null;
  15. }
  16. }
  17. function hookDir(root: string): string {
  18. const r = spawnSync('git', ['rev-parse', '--path-format=absolute', '--git-path', 'hooks'], {
  19. cwd: root, encoding: 'utf8',
  20. });
  21. if (r.error) throw r.error;
  22. if (r.status !== 0 || !r.stdout) throw new Error(r.stderr?.trim() || 'Git could not locate its hooks folder');
  23. return resolve(root, r.stdout.replace(/\r?\n$/, ''));
  24. }
  25. function block(event: typeof EVENTS[number], madeExecutable: boolean): string {
  26. return [
  27. '',
  28. START,
  29. ...(madeExecutable ? [EXEC] : []),
  30. 'shtuk_hook_status=$?',
  31. '[ "$shtuk_hook_status" -eq 0 ] || exit "$shtuk_hook_status"',
  32. event === 'commit-msg' ? 'shtuk hook commit-msg "$1"' : 'shtuk hook pre-commit',
  33. END,
  34. '',
  35. ].join('\n');
  36. }
  37. export function gitHooks(root: string, mode: 'sync' | 'remove' | 'check'): string[] {
  38. const dir = hookDir(root);
  39. const problems: string[] = [];
  40. for (const event of EVENTS) {
  41. const file = join(dir, event);
  42. const present = existsSync(file);
  43. // Preserve the bytes of existing hooks, including scripts written in another encoding.
  44. const before = present ? readFileSync(file, 'latin1') : HEADER;
  45. const permissions = present ? statSync(file).mode & 0o777 : 0o755;
  46. const blocks = before.match(BLOCKS) ?? [];
  47. const foreign = before.replace(BLOCKS, '');
  48. const madeExecutable = blocks.some((b) => b.includes(EXEC));
  49. const executable = (permissions & 0o111) !== 0;
  50. if (mode === 'check') {
  51. if (blocks.length !== 1 || blocks[0] !== block(event, madeExecutable) || !executable)
  52. problems.push(`Git ${event}: expected one current, executable shtuk hook block → shtuk run hooks sync`);
  53. } else if (mode === 'sync') {
  54. const shebang = foreign.split('\n', 1)[0];
  55. if (shebang.startsWith('#!') && !/(?:\/|\s)(?:sh|bash|dash|zsh|ksh|ash)(?:\s|$)/.test(shebang))
  56. throw new Error(`Git ${event}: cannot append a shell block to ${shebang}`);
  57. const after = foreign + block(event, madeExecutable || !executable);
  58. if (after !== before || !executable) replaceFile(file, after, 'latin1', permissions | 0o100);
  59. } else if (blocks.length) {
  60. if (foreign === HEADER) rmSync(file, { force: true });
  61. else replaceFile(file, foreign, 'latin1', madeExecutable ? permissions & ~0o100 : permissions);
  62. }
  63. }
  64. return problems;
  65. }