package file→ .shtukbase/packages/hooks/lib/git-hooks.ts
lib/git-hooks.ts
71 lines, 3.0 KB.
- import { spawnSync } from 'node:child_process';
- import { existsSync, readFileSync, rmSync, statSync } from 'node:fs';
- import { dirname, join, resolve } from 'node:path';
- import { replaceFile } from './write.ts';
- const EVENTS = ['pre-commit', 'commit-msg'] as const;
- const START = '# >>> shtuk hook >>>';
- const END = '# <<< shtuk hook <<<';
- const HEADER = '#!/bin/sh\n# Generated by shtuk.\n';
- const EXEC = '# shtuk made this hook executable';
- const BLOCKS = /(?:^|\n)# >>> shtuk hook >>>\r?\n[\s\S]*?^# <<< shtuk hook <<<(?:\r?\n|$)/gm;
- export function repoRoot(from: string): string | null {
- for (let dir = from; ; dir = dirname(dir)) {
- if (existsSync(join(dir, '.git'))) return dir;
- if (dir === dirname(dir)) return null;
- }
- }
- function hookDir(root: string): string {
- const r = spawnSync('git', ['rev-parse', '--path-format=absolute', '--git-path', 'hooks'], {
- cwd: root, encoding: 'utf8',
- });
- if (r.error) throw r.error;
- if (r.status !== 0 || !r.stdout) throw new Error(r.stderr?.trim() || 'Git could not locate its hooks folder');
- return resolve(root, r.stdout.replace(/\r?\n$/, ''));
- }
- function block(event: typeof EVENTS[number], madeExecutable: boolean): string {
- return [
- '',
- START,
- ...(madeExecutable ? [EXEC] : []),
- 'shtuk_hook_status=$?',
- '[ "$shtuk_hook_status" -eq 0 ] || exit "$shtuk_hook_status"',
- event === 'commit-msg' ? 'shtuk hook commit-msg "$1"' : 'shtuk hook pre-commit',
- END,
- '',
- ].join('\n');
- }
- export function gitHooks(root: string, mode: 'sync' | 'remove' | 'check'): string[] {
- const dir = hookDir(root);
- const problems: string[] = [];
- for (const event of EVENTS) {
- const file = join(dir, event);
- const present = existsSync(file);
- // Preserve the bytes of existing hooks, including scripts written in another encoding.
- const before = present ? readFileSync(file, 'latin1') : HEADER;
- const permissions = present ? statSync(file).mode & 0o777 : 0o755;
- const blocks = before.match(BLOCKS) ?? [];
- const foreign = before.replace(BLOCKS, '');
- const madeExecutable = blocks.some((b) => b.includes(EXEC));
- const executable = (permissions & 0o111) !== 0;
- if (mode === 'check') {
- if (blocks.length !== 1 || blocks[0] !== block(event, madeExecutable) || !executable)
- problems.push(`Git ${event}: expected one current, executable shtuk hook block → shtuk run hooks sync`);
- } else if (mode === 'sync') {
- const shebang = foreign.split('\n', 1)[0];
- if (shebang.startsWith('#!') && !/(?:\/|\s)(?:sh|bash|dash|zsh|ksh|ash)(?:\s|$)/.test(shebang))
- throw new Error(`Git ${event}: cannot append a shell block to ${shebang}`);
- const after = foreign + block(event, madeExecutable || !executable);
- if (after !== before || !executable) replaceFile(file, after, 'latin1', permissions | 0o100);
- } else if (blocks.length) {
- if (foreign === HEADER) rmSync(file, { force: true });
- else replaceFile(file, foreign, 'latin1', madeExecutable ? permissions & ~0o100 : permissions);
- }
- }
- return problems;
- }