import { log } from "./logging";

export async function wrapSigInt<T>(
  body: (throwIfAborted: () => void) => Promise<T>,
): Promise<T> {
  let aborted = false;

  const onSigInt = (): void => {
    log("SIGINT received.");
    aborted = true;
  };

  const throwIfAborted = (): void => {
    if (aborted) {
      throw "Aborted due to SIGINT";
    }
  };

  process.on("SIGINT", onSigInt);
  try {
    return await body(throwIfAborted);
  } finally {
    process.off("SIGINT", onSigInt);
  }
}
