/** Plain-JavaScript text of the hook dispatcher shim, written to `/hooks/dispatch.mjs` at runtime. The program imports only Node built-ins, so nothing new ships in the tarball. It reads `plan.json` beside itself, skips user-disabled events, restores the caller's `GIT_CONFIG_PARAMETERS`, exports the absolute worktree root as `GIT_WORK_TREE` and the preparation lease, takes the hook lock unless the plan skips it, runs `git hook run` with the repository's own hooks path, releases the lock, and propagates the exit status. Its hook lock uses the record format of `src/owner-lock/owner-lock.ts` and the process-birth identities of `commit-transaction-process-identity.ts`, so the shim and the wrapper contend on one lock. The text avoids backticks and template substitutions, so it embeds verbatim. @module */ /** Dispatcher program text. */ export const HOOK_DISPATCH_PROGRAM = `// Generated by cli-git for one commit transaction; removed with it. import { execFile, spawn } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { once } from 'node:events'; import { constants } from 'node:fs'; import { mkdir, open, readFile, rename, rm } from 'node:fs/promises'; const PLAN_URL = new URL('./plan.json', import.meta.url); const RECORD = 'owner.json'; const POLL_MS = 20; const LINUX_START_FIELD = 19; const EXITED_STATES = ['Z', 'X']; function sleep(milliseconds) { return new Promise(function schedule(resolveSleep) { setTimeout(resolveSleep, milliseconds); }); } function processIsAlive(pid) { try { process.kill(pid, 0); return true; } catch (error) { if (error.code === 'ESRCH') return false; if (error.code === 'EPERM') return true; throw error; } } function inspect(command, args) { return new Promise(function run(resolveRun) { execFile(command, args, { env: { ...process.env, LC_ALL: 'C' }, windowsHide: true }, function done(error, stdout) { resolveRun(error ? '' : String(stdout).trim()); }); }); } async function birthIdentity(pid) { if (process.platform === 'linux') { try { const stat = await readFile('/proc/' + String(pid) + '/stat', 'utf8'); const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(' '); // A zombie keeps its PID and start tick until reaped, which a container init may never do; it holds nothing. if (EXITED_STATES.includes(fields[0])) return null; const tick = fields[LINUX_START_FIELD]; return tick ? 'linux:' + tick : null; } catch (error) { if (error.code === 'ENOENT') return null; throw error; } } if (process.platform === 'darwin') { const value = await inspect('ps', ['-o', 'lstart=', '-p', String(pid)]); return value ? 'darwin:' + value : null; } if (process.platform === 'win32') { const value = await inspect('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '(Get-Process -Id ' + String(pid) + ').StartTime.ToUniversalTime().Ticks']); return value ? 'win32:' + value : null; } throw new Error('cli-git hook dispatcher: unsupported platform ' + process.platform); } async function readOwner(lockDirectory) { try { return JSON.parse(await readFile(lockDirectory + '/' + RECORD, 'utf8')); } catch (error) { if ((error.code === 'ENOENT') || (error.code === 'ENOTDIR')) return null; throw error; } } async function holderIsAlive(owner) { if (!processIsAlive(owner.ownerPid)) return false; return (await birthIdentity(owner.ownerPid)) === owner.ownerBirthIdentity; } async function retire(lockDirectory, deadToken) { // The liveness check took time; the owner may have released and a live acquirer published since. const current = await readOwner(lockDirectory); if (!current || (current.token !== deadToken)) return; const staleDirectory = lockDirectory + '.' + randomUUID() + '.stale'; try { await rename(lockDirectory, staleDirectory); } catch (error) { if (error.code === 'ENOENT') return; throw error; } const moved = await readOwner(staleDirectory); if (moved && (moved.token !== deadToken)) { await rename(staleDirectory, lockDirectory).catch(function keep() {}); return; } await rm(staleDirectory, { recursive: true, force: true }); } async function acquire(lockDirectory) { const identity = await birthIdentity(process.pid); if (!identity) throw new Error('cli-git hook dispatcher: current process identity is unavailable'); const record = { schemaVersion: 1, token: randomUUID(), ownerPid: process.pid, ownerBirthIdentity: identity }; for (;;) { const candidate = lockDirectory + '.' + randomUUID() + '.pending'; await mkdir(candidate, { mode: 0o700 }); const handle = await open(candidate + '/' + RECORD, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0), 0o600); await handle.writeFile(JSON.stringify(record) + '\\n', 'utf8'); await handle.sync(); await handle.close(); try { await rename(candidate, lockDirectory); return record; } catch (error) { await rm(candidate, { recursive: true, force: true }); if (!['EEXIST', 'ENOTEMPTY', 'EPERM'].includes(error.code)) throw error; } const owner = await readOwner(lockDirectory); if (owner && !(await holderIsAlive(owner))) { await retire(lockDirectory, owner.token); continue; } await sleep(POLL_MS); } } async function release(lockDirectory, token) { const owner = await readOwner(lockDirectory); if (!owner || (owner.token !== token)) throw new Error('cli-git hook dispatcher: hook lock ownership changed: ' + lockDirectory); // Renaming frees the published name atomically; emptying it in place would let an acquirer's rename replace it mid-removal. const retiredDirectory = lockDirectory + '.' + randomUUID() + '.stale'; await rename(lockDirectory, retiredDirectory); await rm(retiredDirectory, { recursive: true, force: true }); } export async function dispatch(event, args) { const plan = JSON.parse(await readFile(PLAN_URL, 'utf8')); if (plan.disabledEvents.includes(event)) { process.exitCode = 0; return; } const environment = { ...process.env }; if (plan.configParameters.kind === 'absent') delete environment.GIT_CONFIG_PARAMETERS; else environment.GIT_CONFIG_PARAMETERS = plan.configParameters.value; environment.GIT_WORK_TREE = plan.worktreeRoot; environment.CLI_GIT_PREPARATION_LEASE = plan.lease; const lock = plan.skipHookLock ? null : await acquire(plan.hookLockPath); let status = 1; try { const child = spawn(plan.gitPath, [ '-c', 'hook.' + event + '.enabled=true', '-c', 'core.hooksPath=' + plan.hooksPath, 'hook', 'run', '--ignore-missing', event, '--', ...args, ], { stdio: 'inherit', env: environment }); const [code] = await once(child, 'exit'); status = (typeof code === 'number') ? code : 1; } finally { if (lock) await release(plan.hookLockPath, lock.token); } process.exitCode = status; } `; /** Builds one executable hook file that runs the dispatcher for its event. @param nodePath - absolute Node executable for the shebang @param dispatchUrl - absolute file URL of `dispatch.mjs` @param event - hook event name @returns hook file text, with the URL and event encoded through `JSON.stringify` @example ```ts hookEntryProgram({ nodePath: process.execPath, dispatchUrl: 'file:///repo/.git/tx/hooks/dispatch.mjs', event: 'pre-commit' }); ``` */ export function hookEntryProgram({ nodePath, dispatchUrl, event, }: Readonly<{ nodePath: string; dispatchUrl: string; event: string; }>,): string { return [ `#!${nodePath}`, `import { dispatch } from ${JSON.stringify(dispatchUrl,)};`, `await dispatch(${JSON.stringify(event,)}, process.argv.slice(2));`, '', ].join('\n',); }