Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/Aquaticat/Monochromatic. TypeScript and Rust monorepo: Claude Code and Pi coding-agent plugins, a m
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529/** Real index computed at landing against the then-current real index, never against the invocation-time copy, so a landing never erases another invocation's staging and never stages a revert of landed content.
@module */import { tagged, } from '@monochromatic-dev/module-logger/ts';import { snapshotFilesEqual, } from './commit-transaction-candidate-snapshot.ts';import { runTransactionGit, } from './commit-transaction-git.ts';import type { TransactionMode, } from './commit-transaction-journal-states.ts';import { copyIndexFile, } from './index-file-timestamps.ts';
/** Module logger. */const l = tagged({ tag: 'cli-git', },);
/** Strict Git output decoder. */const DECODER = new TextDecoder( 'utf-8', { fatal: true, },);
/** UTF-8 encoder for index-info input. */const ENCODER = new TextEncoder();
/** Keeps pathspec magic active, so `:(top,literal)` names concrete paths even when the caller disabled magic. */const MAGIC_PATHSPECS = { GIT_LITERAL_PATHSPECS: '0', } as const;
/** Splits NUL-terminated records.
@param bytes - Git output
@returns nonempty records */function records(bytes: Uint8Array,): readonly string[] { return DECODER.decode(bytes,) .split('\0',) .filter(function nonempty(record,): boolean { return record.length > 0; },);}
/** Groups `ls-files --stage` records by path.
@param stageRecords - `mode oid stage<TAB>path` records
@returns records per path, in stage order */function stagesByPath(stageRecords: readonly string[],): ReadonlyMap<string, readonly string[]> { /** Records per path. */ const grouped = new Map<string, string[]>(); for (const record of stageRecords) { /** Metadata and path separator. */ const tab = record.indexOf('\t',); /** Record path. */ const path = record.slice(tab + 1,); grouped.set( path, [ ...(grouped.get(path,) ?? []), record, ], ); } return grouped;}
/** Lists stage records of one index for concrete paths.
@param gitPath - real Git executable
@param cwd - owning worktree directory
@param indexPath - index to read
@param paths - concrete paths
@returns stage records grouped by path */async function listStages({ gitPath, cwd, indexPath, paths,}: Readonly<{ gitPath: string; cwd: string; indexPath: string; paths: readonly string[];}>,): Promise<ReadonlyMap<string, readonly string[]>> { if (paths.length === 0) return new Map(); return stagesByPath(records((await runTransactionGit({ gitPath, cwd, indexPath, args: [ 'ls-files', '--stage', '-z', '--full-name', '--', ...paths.map(function fromRoot(path,): string { return `:(top,literal)${path}`; },), ], environment: MAGIC_PATHSPECS, },)).stdout,),);}
/** Lists paths two tree-ishes differ in.
@param gitPath - real Git executable
@param cwd - owning worktree directory
@param from - first tree-ish
@param to - second tree-ish
@returns changed paths without rename pairing */async function changedPaths({ gitPath, cwd, from, to,}: Readonly<{ gitPath: string; cwd: string; from: string; to: string;}>,): Promise<readonly string[]> { return records((await runTransactionGit({ gitPath, cwd, args: [ 'diff-tree', '-r', '--no-renames', '--name-only', '-z', from, to, ], },)).stdout,);}
/** Lists paths the landed tree changes relative to what was staged at invocation; nothing when the invocation-time index cannot form a tree.
@param gitPath - real Git executable
@param cwd - owning worktree directory
@param capturedIndexPath - invocation-time index copy
@param landedTreeOid - landed tree
@returns changed paths */async function changedSinceCaptured({ gitPath, cwd, capturedIndexPath, landedTreeOid,}: Readonly<{ gitPath: string; cwd: string; capturedIndexPath: string; landedTreeOid: string;}>,): Promise<readonly string[]> { /** Tree write that fails on unmerged entries. */ const result = await runTransactionGit({ gitPath, cwd, indexPath: capturedIndexPath, args: ['write-tree',], allowFailure: true, },); if (result.exitCode !== 0) return []; return changedPaths({ gitPath, cwd, from: DECODER.decode(result.stdout,) .trim(), to: landedTreeOid, },);}
/** Index-mode post-index: landed entries only for paths whose current entry still equals the captured one.
@param gitPath - real Git executable
@param cwd - owning worktree directory
@param capturedIndexPath - invocation-time index copy
@param landedIndexPath - private index the commit was made from
@param postIndexPath - post-index being written, already a copy of the current real index
@param changed - paths the commit changed
@param zeroOid - all-zero object ID of the repository's hash */async function mergeLandedEntries({ gitPath, cwd, capturedIndexPath, landedIndexPath, postIndexPath, changed, zeroOid,}: Readonly<{ gitPath: string; cwd: string; capturedIndexPath: string; landedIndexPath: string; postIndexPath: string; changed: readonly string[]; zeroOid: string;}>,): Promise<void> { /** Captured, current, and landed entries for every changed path. */ const [captured, current, landed,] = await Promise.all([ listStages({ gitPath, cwd, indexPath: capturedIndexPath, paths: changed, },), listStages({ gitPath, cwd, indexPath: postIndexPath, paths: changed, },), listStages({ gitPath, cwd, indexPath: landedIndexPath, paths: changed, },), ],); /** Paths nobody restaged since invocation. */ const untouched = changed.filter(function stillCaptured(path,): boolean { return JSON.stringify(captured.get(path,) ?? [],) === JSON.stringify(current.get(path,) ?? [],); },); if (untouched.length === 0) return; /** `--index-info` lines: landed entries, or removal of paths the commit deleted. */ const lines = untouched.flatMap(function landedLines(path,): readonly string[] { return landed.get(path,) ?? [`0 ${zeroOid}\t${path}`,]; },); await runTransactionGit({ gitPath, cwd, indexPath: postIndexPath, args: [ 'update-index', '-z', '--index-info', ], input: ENCODER.encode(lines .map(function terminated(line,): string { return `${line}\0`; },) .join('',),), },);}
/** Explicit-path post-index for paths a hook changed: each takes the landed entry only while the real index still holds the entry captured at invocation; an entry restaged since then is kept and reported.
@param gitPath - real Git executable
@param cwd - owning worktree directory
@param capturedIndexPath - invocation-time index copy
@param postIndexPath - post-index being written, already a copy of the current real index
@param landedTreeOid - landed tree
@param guardedPaths - hook-changed paths outside the selection */async function resetGuardedPaths({ gitPath, cwd, capturedIndexPath, postIndexPath, landedTreeOid, guardedPaths,}: Readonly<{ gitPath: string; cwd: string; capturedIndexPath: string; postIndexPath: string; landedTreeOid: string; guardedPaths: readonly string[];}>,): Promise<void> { if (guardedPaths.length === 0) return; /** Captured and current entries of every guarded path. */ const [captured, current,] = await Promise.all([ listStages({ gitPath, cwd, indexPath: capturedIndexPath, paths: guardedPaths, },), listStages({ gitPath, cwd, indexPath: postIndexPath, paths: guardedPaths, },), ],); /** Paths still holding their pre-hook entry. */ const untouched = guardedPaths.filter(function stillCaptured(path,): boolean { /** Whether the entry is unchanged since invocation. */ const same = JSON.stringify(captured.get(path,) ?? [],) === JSON.stringify(current.get(path,) ?? [],); if (!same) l.warn(`A commit hook changed ${path}, but it was staged again while the commit ran; the committed bytes are in HEAD and your staged entry was kept. Compare them with git diff --cached -- ${path}.`,); return same; },); if (untouched.length > 0) await runTransactionGit({ gitPath, cwd, indexPath: postIndexPath, args: [ 'reset', '--quiet', landedTreeOid, '--', ...untouched.map(function fromRoot(path,): string { return `:(top,literal)${path}`; },), ], environment: MAGIC_PATHSPECS, },);}
/** Computes the post-index a landing installs.
@param gitPath - real Git executable
@param cwd - owning worktree directory
@param mode - commit selection mode
@param preLandingIndexPath - exact copy of the current real index
@param capturedIndexPath - invocation-time index copy
@param landedIndexPath - private index the commit was made from
@param postIndexPath - post-index to write
@param landedTreeOid - tree the landing installs
@param baseRevision - preparation base commit, or the empty tree when unborn
@param committedPaths - paths an explicit-path commit carries, including policy-added paths
@param guardedPaths - paths a commit hook changed, reset in an explicit-path commit only while their real index entry still holds the captured one
@param exactPrivateIndex - whether `landedIndexPath` is the exact index the landed commit was prepared from, false after a replay
@example ```ts await computeLandingPostIndex({ gitPath: '/usr/bin/git', cwd: '/repo', mode: 'index', preLandingIndexPath, capturedIndexPath, landedIndexPath, postIndexPath, landedTreeOid, baseRevision, committedPaths: [] }); ``` */export async function computeLandingPostIndex({ gitPath, cwd, mode, preLandingIndexPath, capturedIndexPath, landedIndexPath, postIndexPath, landedTreeOid, baseRevision, committedPaths, guardedPaths = [], exactPrivateIndex = true,}: Readonly<{ gitPath: string; cwd: string; mode: TransactionMode; preLandingIndexPath: string; capturedIndexPath: string; landedIndexPath: string; postIndexPath: string; landedTreeOid: string; baseRevision: string; committedPaths: readonly string[]; guardedPaths?: readonly string[]; exactPrivateIndex?: boolean;}>,): Promise<void> { /** Tagged post-index logger. */ const rl = tagged({ tag: computeLandingPostIndex.name, l, },); if (mode === 'explicit-path') { await copyIndexFile({ sourcePath: preLandingIndexPath, destinationPath: postIndexPath, },); if (committedPaths.length > 0) await runTransactionGit({ gitPath, cwd, indexPath: postIndexPath, args: [ 'reset', '--quiet', landedTreeOid, '--', ...committedPaths.map(function fromRoot(path,): string { return `:(top,literal)${path}`; },), ], environment: MAGIC_PATHSPECS, },); await resetGuardedPaths({ gitPath, cwd, capturedIndexPath, postIndexPath, landedTreeOid, guardedPaths: guardedPaths.filter(function outsideSelection(path,): boolean { return !committedPaths.includes(path,); },), },); return; } // A replayed commit's private index holds the replayed tree without the real index's stat data and flags, // so only the exact prepared index may replace the real index wholesale. if (exactPrivateIndex && (await snapshotFilesEqual({ leftPath: preLandingIndexPath, rightPath: capturedIndexPath, },))) { // Nothing restaged since invocation: the private index is exactly what native Git would leave. await copyIndexFile({ sourcePath: landedIndexPath, destinationPath: postIndexPath, },); return; } rl.debug('real index changed since invocation; merging landed entries per path',); await copyIndexFile({ sourcePath: preLandingIndexPath, destinationPath: postIndexPath, },); /** Paths the commit changed relative to its base or to what was staged at invocation. */ const changed = [ ...new Set([ ...(await changedPaths({ gitPath, cwd, from: baseRevision, to: landedTreeOid, },)), ...(await changedSinceCaptured({ gitPath, cwd, capturedIndexPath, landedTreeOid, },)), ],), ]; await mergeLandedEntries({ gitPath, cwd, capturedIndexPath, landedIndexPath, postIndexPath, changed, zeroOid: '0'.repeat(landedTreeOid.length,), },);}