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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534import { randomUUID, } from 'node:crypto';import { constants, } from 'node:fs';import { mkdir, open, readFile, readdir, rename, rm,} from 'node:fs/promises';import { basename, dirname, join,} from 'node:path';
import { WorktreeCopyError, } from './errors.ts';import { prepareStageRemoval, } from './journal-cleanup.ts';import { validateJournalValue, } from './journal-validation.ts';import type { StagedWorktreeSnapshot, WorktreeCopyJournal,} from './model.ts';import { assertPrivateWorktreeCopyPath, } from './private-path.ts';
/** Worktree-copy journal parent beneath common Git directory. */const JOURNAL_PARENT_NAME = 'cli-git-worktree-copy';
/** Worktree-copy journal schema directory. */const JOURNAL_VERSION_NAME = 'v1';
/** Private journal directory mode. */const PRIVATE_DIRECTORY_MODE = 0o700;
/** Private journal root does not exist. */export const JOURNAL_ROOT_ABSENT: unique symbol = Symbol('worktree-copy journal root is absent',);
/** Private journal file mode. */const PRIVATE_FILE_MODE = 0o600;
/** Journal filename suffix. */const JOURNAL_SUFFIX = '.json';
/** Suffix of an unpublished temporary journal write. */const TEMPORARY_SUFFIX = '.tmp';
/** Resolves private journal root beneath canonical common Git directory. @param commonDir - canonical common Git directory @returns private versioned journal root @example ```ts worktreeCopyJournalRoot('/repo/.git'); // => '/repo/.git/cli-git-worktree-copy/v1' ``` */export function worktreeCopyJournalRoot(commonDir: string,): string { return join( commonDir, JOURNAL_PARENT_NAME, JOURNAL_VERSION_NAME, );}
/** Creates one private journal directory or validates exact existing directory. @param path - exact journal directory path @example ```ts await ensurePrivateJournalDirectory('/repo/.git/cli-git-worktree-copy'); ``` */async function ensurePrivateJournalDirectory(path: string,): Promise<void> { try { await mkdir( path, { mode: PRIVATE_DIRECTORY_MODE, }, ); } catch (error: unknown) { if (!(Error.isError(error,) && ('code' in error) && (error.code === 'EEXIST'))) throw error; } await assertPrivateWorktreeCopyPath({ path, role: 'journal directory', },);}
/** Creates and validates complete private journal root component by component. @param commonDir - canonical common Git directory @returns validated private journal root @example ```ts await ensureWorktreeCopyJournalRoot('/repo/.git'); ``` */export async function ensureWorktreeCopyJournalRoot( commonDir: string,): Promise<string> { /** Private journal parent. */ const parent = join( commonDir, JOURNAL_PARENT_NAME, ); await ensurePrivateJournalDirectory(parent,); /** Versioned private journal root. */ const root = worktreeCopyJournalRoot(commonDir,); await ensurePrivateJournalDirectory(root,); return root;}
/** Validates existing private journal root without creating state. @param commonDir - canonical common Git directory @returns validated root or absence sentinel @example ```ts await existingWorktreeCopyJournalRoot('/repo/.git'); ``` */export async function existingWorktreeCopyJournalRoot( commonDir: string,): Promise<string | typeof JOURNAL_ROOT_ABSENT> { /** Expected private journal parent. */ const parent = join( commonDir, JOURNAL_PARENT_NAME, ); /** Expected versioned journal root. */ const root = worktreeCopyJournalRoot(commonDir,); try { await Promise.all([ assertPrivateWorktreeCopyPath({ path: parent, role: 'journal directory', },), assertPrivateWorktreeCopyPath({ path: root, role: 'journal directory', },), ],); return root; } catch (error: unknown) { if (Error.isError(error,) && ('code' in error) && (error.code === 'ENOENT')) return JOURNAL_ROOT_ABSENT; throw error; }}
/** Durable journal file paired with validated record. @example ```ts const pending: PendingWorktreeCopyJournal = { path: '/repo/.git/cli-git-worktree-copy/v1/id.json', record }; ``` */export type PendingWorktreeCopyJournal = Readonly<{ /** Absolute durable journal path. */ path: string; /** Validated journal record. */ record: WorktreeCopyJournal;}>;
/** Flushes directory metadata where host supports directory handles. @param path - directory containing durable journal mutation @example ```ts await syncDirectory('/repo/.git/cli-git-worktree-copy/v1'); ``` */async function syncDirectory(path: string,): Promise<void> { if (process.platform === 'win32') return; /** Read-only directory handle used for metadata fsync. */ await using handle = await open( path, constants.O_RDONLY, ); await handle.sync();}
/** Atomically writes complete private journal record. @param path - final journal path @param record - complete durable record @example ```ts await writeJournal({ path: '/journal.json', record }); ``` */export async function writeJournal({ path, record,}: Readonly<{ path: string; record: WorktreeCopyJournal;}>,): Promise<void> { /** Unique sibling temporary journal path. */ const temporaryPath = `${path}.${randomUUID()}${TEMPORARY_SUFFIX}`; /** Plain immutable journal value detached from caller-owned arrays. */ const serializedRecord: WorktreeCopyJournal = { ...record, createdEntries: record.createdEntries .map(function createdEntry(entry,) { return { ...entry, }; },), intendedEntries: [...record.intendedEntries,], selectedRoots: [...record.selectedRoots,], }; try { { /** Exclusive no-follow temporary journal handle. */ await using handle = await open( temporaryPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, PRIVATE_FILE_MODE, ); await handle.writeFile( `${JSON.stringify(serializedRecord,)}\n`, 'utf8', ); await handle.sync(); } await rename( temporaryPath, path, ); await syncDirectory(dirname(path,),); } catch (error: unknown) { await rm( temporaryPath, { force: true, }, ); throw new WorktreeCopyError( `cli-git: could not persist worktree-copy journal ${JSON.stringify(path,)}.`, error, ); }}
/** Creates staged transaction journal beneath common Git directory. @param commonDir - canonical common Git directory @param destinationRoot - created worktree root @param snapshot - validated private ignored-state snapshot @returns durable journal path and record @example ```ts await createWorktreeCopyJournal({ commonDir: '/repo/.git', destinationRoot: '/wt', snapshot }); ``` */export async function createWorktreeCopyJournal({ commonDir, destinationRoot, snapshot,}: Readonly<{ commonDir: string; destinationRoot: string; snapshot: StagedWorktreeSnapshot;}>,): Promise<PendingWorktreeCopyJournal> { /** Private journal directory. */ const root = await ensureWorktreeCopyJournalRoot(commonDir,); /** Unique final journal path. */ const path = join( root, `${randomUUID()}${JOURNAL_SUFFIX}`, ); /** Initial staged journal record. */ const record: WorktreeCopyJournal = { createdEntries: [], intendedEntries: [], destinationRoot, phase: 'staged', selectedRoots: snapshot.selectedRoots, sourceRoot: snapshot.sourceRoot, stageContainer: snapshot.stageContainer, stageRoot: snapshot.stageRoot, version: 1, }; await writeJournal({ path, record, },); return { path, record, };}
/** Reads sorted journal filenames or journal-directory absence. @param root - private journal directory @returns sorted JSON journal filenames @example ```ts await readJournalNames('/repo/.git/cli-git-worktree-copy/v1'); ``` */async function readJournalNames(root: string,): Promise<readonly string[]> { try { return (await readdir(root,)) .filter(function journalName(name,): boolean { return name.endsWith(JOURNAL_SUFFIX,); },) .toSorted(); } catch (error: unknown) { if (Error.isError(error,) && ('code' in error) && (error.code === 'ENOENT')) { return []; } throw new WorktreeCopyError( `cli-git: could not inspect worktree-copy journals under ${JSON.stringify(root,)}.`, error, ); }}
/** Reads every incomplete durable worktree-copy journal. @param commonDir - canonical common Git directory @returns validated pending journals sorted by filename @example ```ts await readPendingWorktreeCopyJournals('/repo/.git'); ``` */export async function readPendingWorktreeCopyJournals( commonDir: string,): Promise<readonly PendingWorktreeCopyJournal[]> { /** Private journal directory. */ const root = await existingWorktreeCopyJournalRoot(commonDir,); if ((typeof root) === 'symbol') return []; /** Existing final journal filenames. */ const names = await readJournalNames(root,); return Promise.all(names.map(async function readJournal(name,): Promise<PendingWorktreeCopyJournal> { /** Absolute final journal path. */ const path = join( root, name, ); try { await assertPrivateWorktreeCopyPath({ path, role: 'journal file', },); /** Untrusted parsed journal JSON. */ const parsed: unknown = JSON.parse(await readFile( path, 'utf8', ),); return { path, record: validateJournalValue({ value: parsed, path, journalRoot: root, },), }; } catch (error: unknown) { if (error instanceof WorktreeCopyError) throw error; throw new WorktreeCopyError( `cli-git: could not read worktree-copy journal ${JSON.stringify(path,)}.`, error, ); } },),);}
/** Removes temporary journal files an interrupted {@link writeJournal} of this journal left beside it.
@param path - final journal path whose temporary siblings carry its name as prefix
@example ```ts await removeUnfinishedJournalWrites('/repo/.git/cli-git-worktree-copy/v1/id.json'); ``` */async function removeUnfinishedJournalWrites(path: string,): Promise<void> { /** Temporary-name prefix owned by this journal. */ const prefix = `${basename(path,)}.`; /** Unfinished temporary writes of this journal. */ const unfinished = (await readdir(dirname(path,),)).filter(function isOwnTemporary(name,): boolean { return name.startsWith(prefix,) && name.endsWith(TEMPORARY_SUFFIX,); },); await Promise.all(unfinished.map(function removeTemporary(name,): Promise<void> { return rm( join( dirname(path,), name, ), { force: true, }, ); },),);}
/** Removes completed journal and private stage. @param pending - completed durable transaction @example ```ts await removeWorktreeCopyJournal(pending); ``` */export async function removeWorktreeCopyJournal( pending: PendingWorktreeCopyJournal,): Promise<void> { /** Durable completion marker making stage cleanup resumable. */ const completeRecord: WorktreeCopyJournal = { ...pending.record, phase: 'complete', }; if (pending.record .phase !== 'complete') { await writeJournal({ path: pending.path, record: completeRecord, },); } await prepareStageRemoval(completeRecord.stageContainer,); await rm( completeRecord.stageContainer, { recursive: true, force: true, }, ); await rm( pending.path, { force: true, }, ); await removeUnfinishedJournalWrites(pending.path,); await syncDirectory(dirname(pending.path,),);}