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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358import { tagged, } from '@monochromatic-dev/module-logger/ts';
import { l, } from '../logger.ts';import { setWriteTimestamp, trackDest,} from '../tracker.ts';import { readCached, updateCache,} from './cache.ts';import type { GlobResults, } from './cat.ts';import { caughtErrorHasCode,} from './error.ts';import { resolveManifestPath, } from './staleness.ts';import { writeFileAtomically, } from './write-atomic.ts';import { destinationsForFiles, writeGlobDestinations,} from './write-each-destinations.ts';import { FILE_ALREADY_EXISTS, writeFileIfAbsentAtomically,} from './write-if-absent-atomic.ts';import { isContentBuilder, isGlobResultsBuilder, type OverwriteContent, type OverwriteEachFiles, type WriteIfChanged, writeLazyEach, writeLazyIfChanged,} from './write-lazy.ts';import { rememberEagerEach, rememberEagerWrite,} from './write-staleness.ts';
/** Sentinel for "file does not exist" returned by {@link readExisting}. A unique `Symbol` keeps the absent case out of a banned `string | undefined` union and stays distinguishable from real file content, including the empty string (a present but empty file is content, not absence). */export const ABSENT_FILE_CONTENT: unique symbol = Symbol('file-enforcer/io/write: absent file content, returned by readExisting when a file does not exist',);
/** Reads the current content of a file via the read cache, returning {@link ABSENT_FILE_CONTENT} if the file does not exist. Used for content-based write skipping. @param filePath - Path to check @returns File content as string, or {@link ABSENT_FILE_CONTENT} if absent @throws Non-absence read failures so permissions, directories, and transient I/O errors are not mistaken for a missing destination. @example ```ts const existing = await readExisting('./dist/config.json'); if (existing === ABSENT_FILE_CONTENT) { // file did not exist; safe to create } ``` */export async function readExisting(filePath: string,): Promise<string | typeof ABSENT_FILE_CONTENT> { try { return await readCached(filePath,); } catch (readError: unknown) { if (caughtErrorHasCode({ error: readError, code: 'ENOENT', },)) return ABSENT_FILE_CONTENT;
throw readError; }}
/** Core write logic shared by {@link overwrite} and {@link overwriteEach}. Compares content against existing file, skipping when identical. Handles directory creation, cache update, and write-time tracking. @param dest - Destination file path @param content - Content string to write @param sourcePath - Optional source path for log messages (used by overwriteEach) @param manifestPath - Resolved staleness manifest path @param recordStaleness - Whether reconciliation should record eager staleness metadata */async function writeIfChanged( { dest, content, sourcePath, manifestPath, recordStaleness, }: { readonly dest: string; readonly content: string; readonly manifestPath: string; readonly sourcePath?: string; readonly recordStaleness?: boolean; },): Promise<void> { /** Function-scoped logger tagged with the call site for traceable write logs. */ const rl = tagged({ tag: writeIfChanged.name, l, },); trackDest(dest,); /** Current file content, or ABSENT_FILE_CONTENT if file doesn't exist yet */ const existing = await readExisting(dest,); if (existing === content) { rl.debug( `skip (unchanged): ${sourcePath !== undefined ? `${sourcePath} -> ` : ''}${dest}`, ); if (recordStaleness !== false) { await rememberEagerWrite({ dest, content, manifestPath, },); } return; } /** Actual post-rename destination timestamp used for watch echo suppression. */ const writeTimestamp = await writeFileAtomically({ filePath: dest, content, },); updateCache({ filePath: dest, content, },); setWriteTimestamp({ filePath: dest, timestamp: writeTimestamp, },); if (recordStaleness !== false) { await rememberEagerWrite({ dest, content, manifestPath, },); } rl.info(`${sourcePath !== undefined ? `${sourcePath} -> ` : '-> '}${dest}`,);}
/** Public write function passed into lazy helpers without exposing `writeIfChanged`. */const writeIfChangedForLazy: WriteIfChanged = writeIfChanged;
/** Writes content to dest, skipping the write when existing content is identical. Always registers the path as a managed destination for watch-mode protection. Lazy content builders are skipped entirely when the staleness manifest proves that previous sources and destination metadata are unchanged. @param dest - Destination file path @param content - Content string to write, or lazy builder that returns it @param manifestPath - Optional staleness manifest path override @mutates content through sourceCaptureStorage.run callback invocation @example ```ts await overwrite({ dest: './dist/config.json', content: async function buildConfig(): Promise<string> { return JSON.stringify(config, null, 2); }, }); ``` */export async function overwrite( { dest, content, manifestPath, }: { readonly dest: string; readonly content: OverwriteContent; readonly manifestPath?: string; },): Promise<void> { /** Manifest path resolved once so internal staleness helpers receive a concrete path. */ const resolvedManifestPath = await resolveManifestPath(manifestPath === undefined ? {} : { manifestPath, },); if (isContentBuilder(content,)) { await writeLazyIfChanged({ manifestPath: resolvedManifestPath, dest, content, writeIfChanged: writeIfChangedForLazy, },); return; }
await writeIfChanged({ dest, content, manifestPath: resolvedManifestPath, },);}
/** Writes content to dest only if the file does not already exist. Uses {@link readExisting} to check for the file rather than a separate `exists()` call, avoiding a TOCTOU race gap. Uses no-clobber final-path creation via {@link writeFileIfAbsentAtomically} (returning the {@link FILE_ALREADY_EXISTS} sentinel when another writer wins) after the absence check so a path that appears before create time is preserved instead of replaced. @param dest - Destination file path @param content - Content string to write @example ```ts await overwriteIfNotExists({ dest: './config/defaults.json', content: '{}', }); ``` */export async function overwriteIfNotExists( { dest, content, }: { readonly dest: string; readonly content: string; },): Promise<void> { /** Existing content, or ABSENT_FILE_CONTENT if file doesn't exist */ const existing = await readExisting(dest,); if (existing !== ABSENT_FILE_CONTENT) { trackDest(dest,); l.debug(`skip (exists): ${dest}`,); return; } trackDest(dest,); /** Actual post-create destination timestamp used for watch echo suppression, or a sentinel when another directory entry won the final path first. */ const writeTimestamp = await writeFileIfAbsentAtomically({ filePath: dest, content, },); if (writeTimestamp === FILE_ALREADY_EXISTS) { l.debug(`skip (exists): ${dest}`,); return; } updateCache({ filePath: dest, content, },); setWriteTimestamp({ filePath: dest, timestamp: writeTimestamp, },); await rememberEagerWrite({ dest, content, manifestPath: await resolveManifestPath({},), },); l.info(`-> ${dest}`,);}
/** Writes each glob-matched file to its mirrored destination, skipping files whose content is already identical. Source glob is read from the {@link GlobResults} array produced by `cat()`. @param destGlob - Destination glob pattern with positional wildcards @param files - Glob results carrying the source pattern and file contents @mutates files through sourceCaptureStorage.run callback invocation @example ```ts await overwriteEach({ destGlob: './dest/*/*.md', files: await cat('./src/*/*.md'), }); ``` */export async function overwriteEach( { destGlob, files, manifestPath, }: { readonly destGlob: string; readonly files: OverwriteEachFiles; readonly manifestPath?: string; },): Promise<void> { /** Manifest path resolved once so internal staleness helpers receive a concrete path. */ const resolvedManifestPath = await resolveManifestPath(manifestPath === undefined ? {} : { manifestPath, },); if (isGlobResultsBuilder(files,)) { await writeLazyEach({ manifestPath: resolvedManifestPath, destGlob, files, writeIfChanged: writeIfChangedForLazy, },); return; }
l.info(`overwriteEach: ${String(files.length,)} files`,); /** Concrete destinations for the eager glob mirror rule. */ const destinations = destinationsForFiles({ destGlob, files, },); await writeGlobDestinations({ destinations, writeIfChanged: writeIfChangedForLazy, manifestPath: resolvedManifestPath, },); await rememberEagerEach({ destGlob, destinations, manifestPath: resolvedManifestPath, },);}