/** * Choosing the variant of a patch that fits the game files at hand. Every variant is tried; the * patch applies only when exactly one of them does. None applying means the build differs from * every build a variant was written for; two applying means the variants do not tell builds * apart, which is a definition bug, so the patch is refused rather than guessed. * * Used for exe patches here and for GUI script patches in @wto/patcher. */ import { LocateError, PatchError } from './errors.ts'; export interface Variant { readonly writtenFor: string; } export interface Chosen { readonly variant: V; readonly value: T; } /** `attempt` returns the variant's result, or throws a PatchError saying why it does not apply. */ export function chooseVariant(variants: readonly V[], attempt: (variant: V) => T): Chosen { const applied: Chosen[] = []; const reasons: string[] = []; for (const variant of variants) { try { applied.push({ variant, value: attempt(variant) }); } catch (error) { if (!(error instanceof PatchError)) throw error; reasons.push(variants.length === 1 ? error.message : `variant ${variant.writtenFor}: ${error.message}`); } } if (applied.length > 1) { throw new LocateError(`variants ${applied.map((item) => item.variant.writtenFor).join(' and ')} all apply, so the choice is ambiguous`); } if (!applied.length) throw new LocateError(reasons.join('; ')); return applied[0]!; }