fix: reject partial numeric CLI options

This commit is contained in:
Peter Steinberger
2026-05-27 03:34:44 -04:00
parent f4e20f806e
commit d2d5010aec
13 changed files with 195 additions and 32 deletions

View File

@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import {
collectOption,
parsePositiveIntOrUndefined,
parseStrictPositiveIntOption,
parseStrictPositiveIntOrUndefined,
resolveActionArgs,
resolveCommandOptionArgs,
@@ -53,6 +54,13 @@ describe("program helpers", () => {
expect(parseStrictPositiveIntOrUndefined(value)).toBe(expected);
});
it("parseStrictPositiveIntOption rejects partial numeric strings", () => {
expect(parseStrictPositiveIntOption("10", "--limit")).toBe(10);
expect(() => parseStrictPositiveIntOption("10ms", "--limit")).toThrow(
"--limit must be a positive integer.",
);
});
it("resolveActionArgs returns args when command has arg array", () => {
const command = new Command();
(command as Command & { args?: string[] }).args = ["one", "two"];

View File

@@ -1,4 +1,4 @@
import type { Command } from "commander";
import { InvalidArgumentError, type Command } from "commander";
import { parseStrictPositiveInteger } from "../../infra/parse-finite-number.js";
export function collectOption(value: string, previous: string[] = []): string[] {
@@ -30,6 +30,14 @@ export function parseStrictPositiveIntOrUndefined(value: unknown): number | unde
return parseStrictPositiveInteger(value);
}
export function parseStrictPositiveIntOption(value: string, flag: string): number {
const parsed = parseStrictPositiveInteger(value);
if (parsed === undefined) {
throw new InvalidArgumentError(`${flag} must be a positive integer.`);
}
return parsed;
}
export function resolveActionArgs(actionCommand?: Command): string[] {
if (!actionCommand) {
return [];