import * as fs from 'node:fs'; export interface Patch { /** * A human-readable representation of the patch. */ name: string; /** * The file to patch. */ target: string; /** * A regexp matching some text preceding the patch location. * THE REGEXP MUST HAVE THE GLOBAL (g) FLAG SET! */ anchor: RegExp; /** * The payload to add to the file. It must be unique within the file. */ payload: string; } /** * Applies a patch to a given file. * * @param patch * @returns true if the patch was applied, false if it was skipped. * @throws Error if there was a problem applying the patch */ export function applyPatch(patch: Patch): boolean { const fileContents = readTarget(patch.target); if (fileContents.includes(patch.payload)) { console.log( `Skipping patch "${patch.name}" because it is already applied.`, ); return false; } const injectionLocation = indexOfInjection(fileContents, patch.anchor); if (injectionLocation === undefined) { throw new Error(`Could not locate patch anchor for ${patch.name}!`); } const updated = fileContents.slice(0, Math.max(0, injectionLocation)) + patch.payload + fileContents.slice(injectionLocation); writeTarget(patch.target, updated); return true; } /** * * @param patch */ export function undoPatch(patch: Patch) { const fileContents = readTarget(patch.target); const index = fileContents.indexOf(patch.payload); if (index < 0) { throw new Error(`Could not find the patch of ${patch.name}!`); } const updated = fileContents.slice(0, Math.max(0, index)) + fileContents.slice(index + patch.payload.length); writeTarget(patch.target, updated); } /** * * @param target */ function readTarget(target: string): string { return fs.readFileSync(target).toString(); } /** * * @param target * @param newContents */ function writeTarget(target: string, newContents: string): void { return fs.writeFileSync(target, newContents); } /** * Finds the index at which to insert the patch. * * @param haystack * @param anchor * @returns The string index where to insert the patch, or undefined if it failed to find the location. */ function indexOfInjection( haystack: string, anchor: RegExp, ): number | undefined { const result = anchor.exec(haystack); if (result !== undefined) { return anchor.lastIndex; } return undefined; }