All files / src cli-args.ts

100% Statements 34/34
100% Branches 25/25
100% Functions 2/2
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                                8x 8x           16x             16x 16x 30x 30x 3x 3x 3x   27x 4x 4x 4x   23x 21x 21x 3x   18x 11x 5x 18x 18x   2x   11x 8x 7x 6x   8x    
/**
 * Pure argv → config parser for `bin/ethercalc-migrate`. Extracted from
 * `cli.ts` so tests can stub it via `vi.spyOn` on the module namespace
 * to exercise the non-CliArgError branch in {@link main}.
 */
 
export interface CliArgs {
  input: string;
  d1Name: string;
  kvName: string;
  dryRun: boolean;
  help: boolean;
}
 
export class CliArgError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'CliArgError';
  }
}
 
/** Pure argv parser. Raises {@link CliArgError} on malformed input. */
export function parseArgs(argv: readonly string[]): CliArgs {
  const out: CliArgs = {
    input: '',
    d1Name: '',
    kvName: '',
    dryRun: false,
    help: false,
  };
  let i = 0;
  while (i < argv.length) {
    const a = argv[i] as string;
    if (a === '--help' || a === '-h') {
      out.help = true;
      i += 1;
      continue;
    }
    if (a === '--dry-run') {
      out.dryRun = true;
      i += 1;
      continue;
    }
    if (a === '--input' || a === '--d1-name' || a === '--kv-name') {
      const v = argv[i + 1];
      if (v === undefined) {
        throw new CliArgError(`${a} requires a value`);
      }
      if (a === '--input') out.input = v;
      else if (a === '--d1-name') out.d1Name = v;
      else out.kvName = v;
      i += 2;
      continue;
    }
    throw new CliArgError(`Unknown flag: ${a}`);
  }
  if (!out.help) {
    if (out.input === '') throw new CliArgError('--input is required');
    if (out.d1Name === '') throw new CliArgError('--d1-name is required');
    if (out.kvName === '') throw new CliArgError('--kv-name is required');
  }
  return out;
}