IF Commons GitHub

args

Written to: 1 requirement: 1 proved, 0 partly, 0 failing, 0 with no test recorded. 0001-terminal FR-001

A typed command-line parser (commons 0001-terminal FR-001): a command's options are declared once as data (flag, value, many), the type of what parseArgs gives is inferred from that declaration, and a command line that does not fit is a UsageError, a union told apart by kind that formatUsageError says in one sentence; helpText writes the help from the same declaration. It unifies the parsers of two harnesses: erga's @erga/agent args.ts (declared options, an undeclared option refused with a "did you mean", help that wins over everything and runs nothing: erga 247-ergactl FR-006 and FR-007) and Stolos's parseArgs (short letters, required options, defaults, repeatable options). It is pure: the caller passes the words, proc.args from runtime/proc.ts.

The grammar: --name VALUE and --name=VALUE; -x VALUE; bundled short flags -abc, whose last letter may take the next word as its value; --no-name for a flag declared negatable; -- ends the options, and the words after it are kept apart as rest; - and a word such as -5 are arguments, since no option is a digit. A short option's value is never attached (-ofile, -o=file), which other parsers read differently. A value-taking option takes the next word whatever it is, as getopt does. Every option is given at most once (a many option as often as wanted): a second value would otherwise silently replace the first. --help, or a short word with the letter h, anywhere before -- asks for help, which wins over every other word and every error, so -h and the name help are reserved.

import { flag, integerText, many, parseArgs, value } from "./args.ts";
const spec = {
  verbose: flag({ short: "v", help: "Say more." }),
  out: value({ short: "o", help: "Where to write.", valueName: "FILE" }),
  tag: many({ help: "A tag." }),
  jobs: value({ help: "How many at once.", parse: integerText, default: 4 }),
};
parseArgs(["-v", "--tag", "a", "--tag=b", "--jobs", "8", "--", "x"], spec);
// { kind: "ok", value: { kind: "args", options: { verbose: true, out: undefined, tag: ["a", "b"], jobs: 8 }, positionals: [], rest: ["x"] } }

Source: commons/terminal/src/args.ts

15 of 54 exports are imported by a test of the run. A test that imports an export may not call it or check what it returns.

argsnamespace
namespace args
args.ShortNametypeno test imports it
type ShortName = | "a" | "b" | "c" | "d" | "e" | "f" | "g" | "i" | "j" | "k" | "l" | "m" | "n"… (425 characters)
type ShortName =
  | "a"
  | "b"
  | "c"
  | "d"
  | "e"
  | "f"
  | "g"
  | "i"
  | "j"
  | "k"
  | "l"
  | "m"
  | "n"
  | "o"
  | "p"
  | "q"
  | "r"
  | "s"
  | "t"
  | "u"
  | "v"
  | "w"
  | "x"
  | "y"
  | "z"
  | "A"
  | "B"
  | "C"
  | "D"
  | "E"
  | "F"
  | "G"
  | "H"
  | "I"
  | "J"
  | "K"
  | "L"
  | "M"
  | "N"
  | "O"
  | "P"
  | "Q"
  | "R"
  | "S"
  | "T"
  | "U"
  | "V"
  | "W"
  | "X"
  | "Y"
  | "Z";

A short option's letter: any ASCII letter but h, which is help's.

args.Parsertypeno test imports it
type Parser<T> = (text: string) => Result<T, string | DecodeError>;

What turns an option's text into its value: a function of the text, or any of the kernel's decoders (./decode.ts), which take it as unknown.

args.Presencetypeno test imports it
type Presence = "none" | "required" | "default";

What an option is when the command line does not give it: nothing (undefined), a usage error, or a default.

args.Fallbacktypeno test imports it
type Fallback<T, P extends Presence> = P extends "none"
  ? { readonly kind: "none" }
  : P extends "required"
    ? { readonly kind: "required" }
    : { readonly kind: "default"; readonly value: T };

The fallback of an option of presence P: the default's value is kept with it.

args.FlagOptiontypeno test imports it
type FlagOption<P extends "none" | "default" = "none" | "default", L extends ShortName = ShortName> = {
  readonly kind: "flag";
  readonly short: L | undefined;
  readonly help: string;
  readonly negatable: boolean;
  readonly fallback: Fallback<boolean, P>;
};

A switch that takes no value: true when given, false with --no-name where it is negatable, else its fallback.

args.ValueOptiontypeno test imports it
type ValueOption<T, P extends Presence = Presence, L extends ShortName = ShortName> = {
  readonly kind: "value";
  readonly short: L | undefined;
  readonly help: string;
  readonly valueName: string;
  readonly parse: Parser<T>;
  readonly fallback: Fallback<T, P>;
};

An option given at most once with one value, parsed into a T.

args.ManyOptiontypeno test imports it
type ManyOption<T, L extends ShortName = ShortName> = {
  readonly kind: "many";
  readonly short: L | undefined;
  readonly help: string;
  readonly valueName: string;
  readonly parse: Parser<T>;
};

An option given any number of times, each value parsed into a T, kept in the order given.

args.Optiontypeno test imports it
type Option = FlagOption | ValueOption<unknown> | ManyOption<unknown>;

One declared option.

args.Spectypeno test imports it
type Spec = { readonly [name: string]: Option };

A command's options, by name: the key dryRun is the option --dry-run.

args.OptionValuetypeno test imports it
type OptionValue<O> = O extends { readonly kind: "flag"; readonly fallback: infer F } ? [F] extends [{ readonly kind: … (464 characters)
type OptionValue<O> = O extends { readonly kind: "flag"; readonly fallback: infer F }
  ? [F] extends [{ readonly kind: "none" }]
    ? boolean | undefined
    : boolean
  : O extends { readonly kind: "many"; readonly parse: Parser<infer T> }
    ? readonly T[]
    : O extends { readonly kind: "value"; readonly parse: Parser<infer T>; readonly fallback: infer F }
      ? [F] extends [{ readonly kind: "none" }]
        ? T | undefined
        : T
      : never;

The value an option gives, as its declaration says.

args.OptionValuestypeno test imports it
type OptionValues<S extends Spec> = { readonly [K in keyof S]: OptionValue<S[K]> };

The values of a spec's options, by the same names.

args.SpecChecktypeno test imports it
type SpecCheck<S> = [RepeatedShorts<S>] extends [never]
  ? [Extract<keyof S, `${string}-${string}`>] extends [never]
    ? ["help"] extends [keyof S]
      ? { readonly "help is reserved": never }
      : unknown
    : { readonly "option names are camelCase keys": Extract<keyof S, `${string}-${string}`> }
  : { readonly "a short letter is declared twice": RepeatedShorts<S> };

unknown where a spec is well formed, else a type naming what is wrong, which the spec then does not satisfy: a short letter declared twice, a name written with a dash (names are camelCase keys), or the name help, which is reserved.

args.Operandtypeno test imports it
type Operand = { readonly name: string; readonly help: string; readonly arity: "one" | "optional" | "many" };

A word, or words, that a command takes after its options: exactly one, at most one, or any number.

args.Argstypeno test imports it
type Args<S extends Spec> = {
  readonly kind: "args";
  readonly options: OptionValues<S>;
  readonly positionals: readonly string[];
  readonly rest: readonly string[];
};

A command line that fits its spec: the options' values, the arguments, and the words after --.

args.Parsedtypeno test imports it
type Parsed<S extends Spec> = { readonly kind: "help" } | Args<S>;

What a command line asks: help, which runs nothing else (erga 247-ergactl FR-006), or the command with its arguments.

args.UsageErrortypeno test imports it
type UsageError = | { readonly kind: "unknown-option"; readonly option: string; readonly suggestion: string | undefine… (787 characters)
type UsageError =
  | { readonly kind: "unknown-option"; readonly option: string; readonly suggestion: string | undefined }
  | { readonly kind: "missing-value"; readonly option: string }
  | { readonly kind: "unexpected-value"; readonly option: string; readonly value: string }
  | { readonly kind: "attached-value"; readonly option: string; readonly word: string }
  | { readonly kind: "invalid-value"; readonly option: string; readonly value: string; readonly reason: string }
  | { readonly kind: "repeated-option"; readonly option: string }
  | { readonly kind: "missing-option"; readonly option: string }
  | { readonly kind: "missing-argument"; readonly argument: string }
  | { readonly kind: "unexpected-argument"; readonly argument: string; readonly takes: readonly string[] };

Why a command line does not fit its spec. option is the option as it was written, or its long name where it was given twice or not at all.

args.flagfunctionno test imports it
function flag: { <L extends ShortName = never>(o: Common<L> & { readonly negatable: true; readonly default: boolean; }): FlagOption<"default", L>; <L extends ShortName = never>(o: Common<L> & { readonly negatable: true; }): FlagOption<"none", L>; <L extends ShortName = never>(o: Common<L>): FlagOption<"default", L>; }

A flag: false when not given; with negatable, --no-name gives false and an absent flag gives undefined, or the default. A negatable flag with no default. A flag that cannot be negated. The implementation of flag.

args.valuefunctionno test imports it
function value: { <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { reado… (941 characters)
function value: { <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly parse: Parser<T>; readonly required: true; }): ValueOption<T, "required", L>; <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly parse: Parser<T>; readonly default: NoInfer<T>; }): ValueOption<T, "default", L>; <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly parse: Parser<T>; }): ValueOption<T, "none", L>; <L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly required: true; }): ValueOption<string, "required", L>; <L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly default: string; }): ValueOption<string, "default", L>; <L extends ShortName = never>(o: Valued<L>): ValueOption<string, "none", L>; }

An option with one value, parsed by parse, that must be given. An option with one value, parsed by parse, and a default. An option with one value, parsed by parse, undefined when not given. An option with one text value that must be given. An option with one text value and a default. An option with one text value, undefined when not given. The implementation of value.

args.manyfunctionno test imports it
function many: { <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly parse: Parser<T>; }): ManyOption<T, L>; <L extends ShortName = never>(o: Valued<L>): ManyOption<string, L>; }

An option given any number of times, each value parsed by parse. An option given any number of times, each value its text. The implementation of many.

args.integerTextfunctionno test imports it
function integerText(t: string): Result<number, string>

A parser of an integer written in decimal, with an optional -, within the safe integers.

args.longNamefunctionno test imports it
function longName(key: string): string

The long option of a spec's key: dryRun is --dry-run.

args.editDistancefunctionno test imports it
function editDistance(a: string, b: string): number

The number of insertions, deletions and substitutions that turn a into b (Levenshtein).

args.suggestfunctionno test imports it
function suggest(word: string, candidates: readonly string[]): string | undefined

The candidate nearest word by edit distance, the first of equals, if it is within two edits or half the word's length; else nothing.

args.parseArgsfunctionno test imports it
function parseArgs<S extends Spec>(argv: readonly string[], spec: S & SpecCheck<S>, operands?: readonly Operand[]): Result<Parsed<S>, UsageError>

Parses argv against spec, and the arguments against operands (none by default): help where it is asked for, else every option's value with the arguments and the words after --, or the first thing that does not fit.

args.formatUsageErrorfunctionno test imports it
function formatUsageError(e: UsageError, command?: string): string

A usage error as one sentence; command names the command (ergactl toolchain list), "this command" by default.

args.helpTextfunctionno test imports it
function helpText<S extends Spec>(program: string, summary: string, spec: S & SpecCheck<S>, operands?: readonly Operand[]): string

The help of a command: its summary, its usage, its options aligned with their defaults, and its arguments.

args.helpOffunctionno test imports it
function helpOf(program: string, summary: string, spec: Spec, operands?: readonly Operand[]): string

The help of a command whose spec was checked where it was declared (a verb of ./commands.ts), as helpText gives it.

ShortNametypeno test imports it
type ShortName = | "a" | "b" | "c" | "d" | "e" | "f" | "g" | "i" | "j" | "k" | "l" | "m" | "n"… (425 characters)
type ShortName =
  | "a"
  | "b"
  | "c"
  | "d"
  | "e"
  | "f"
  | "g"
  | "i"
  | "j"
  | "k"
  | "l"
  | "m"
  | "n"
  | "o"
  | "p"
  | "q"
  | "r"
  | "s"
  | "t"
  | "u"
  | "v"
  | "w"
  | "x"
  | "y"
  | "z"
  | "A"
  | "B"
  | "C"
  | "D"
  | "E"
  | "F"
  | "G"
  | "H"
  | "I"
  | "J"
  | "K"
  | "L"
  | "M"
  | "N"
  | "O"
  | "P"
  | "Q"
  | "R"
  | "S"
  | "T"
  | "U"
  | "V"
  | "W"
  | "X"
  | "Y"
  | "Z";

A short option's letter: any ASCII letter but h, which is help's.

Parsertypeno test imports it
type Parser<T> = (text: string) => Result<T, string | DecodeError>;

What turns an option's text into its value: a function of the text, or any of the kernel's decoders (./decode.ts), which take it as unknown.

Presencetypeno test imports it
type Presence = "none" | "required" | "default";

What an option is when the command line does not give it: nothing (undefined), a usage error, or a default.

Fallbacktypeno test imports it
type Fallback<T, P extends Presence> = P extends "none"
  ? { readonly kind: "none" }
  : P extends "required"
    ? { readonly kind: "required" }
    : { readonly kind: "default"; readonly value: T };

The fallback of an option of presence P: the default's value is kept with it.

FlagOptiontypeno test imports it
type FlagOption<P extends "none" | "default" = "none" | "default", L extends ShortName = ShortName> = {
  readonly kind: "flag";
  readonly short: L | undefined;
  readonly help: string;
  readonly negatable: boolean;
  readonly fallback: Fallback<boolean, P>;
};

A switch that takes no value: true when given, false with --no-name where it is negatable, else its fallback.

ValueOptiontypeno test imports it
type ValueOption<T, P extends Presence = Presence, L extends ShortName = ShortName> = {
  readonly kind: "value";
  readonly short: L | undefined;
  readonly help: string;
  readonly valueName: string;
  readonly parse: Parser<T>;
  readonly fallback: Fallback<T, P>;
};

An option given at most once with one value, parsed into a T.

ManyOptiontypeno test imports it
type ManyOption<T, L extends ShortName = ShortName> = {
  readonly kind: "many";
  readonly short: L | undefined;
  readonly help: string;
  readonly valueName: string;
  readonly parse: Parser<T>;
};

An option given any number of times, each value parsed into a T, kept in the order given.

Optiontypeno test imports it
type Option = FlagOption | ValueOption<unknown> | ManyOption<unknown>;

One declared option.

Spectype
type Spec = { readonly [name: string]: Option };

A command's options, by name: the key dryRun is the option --dry-run.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

OptionValuetypeno test imports it
type OptionValue<O> = O extends { readonly kind: "flag"; readonly fallback: infer F } ? [F] extends [{ readonly kind: … (464 characters)
type OptionValue<O> = O extends { readonly kind: "flag"; readonly fallback: infer F }
  ? [F] extends [{ readonly kind: "none" }]
    ? boolean | undefined
    : boolean
  : O extends { readonly kind: "many"; readonly parse: Parser<infer T> }
    ? readonly T[]
    : O extends { readonly kind: "value"; readonly parse: Parser<infer T>; readonly fallback: infer F }
      ? [F] extends [{ readonly kind: "none" }]
        ? T | undefined
        : T
      : never;

The value an option gives, as its declaration says.

OptionValuestypeno test imports it
type OptionValues<S extends Spec> = { readonly [K in keyof S]: OptionValue<S[K]> };

The values of a spec's options, by the same names.

SpecChecktypeno test imports it
type SpecCheck<S> = [RepeatedShorts<S>] extends [never]
  ? [Extract<keyof S, `${string}-${string}`>] extends [never]
    ? ["help"] extends [keyof S]
      ? { readonly "help is reserved": never }
      : unknown
    : { readonly "option names are camelCase keys": Extract<keyof S, `${string}-${string}`> }
  : { readonly "a short letter is declared twice": RepeatedShorts<S> };

unknown where a spec is well formed, else a type naming what is wrong, which the spec then does not satisfy: a short letter declared twice, a name written with a dash (names are camelCase keys), or the name help, which is reserved.

Operandtype
type Operand = { readonly name: string; readonly help: string; readonly arity: "one" | "optional" | "many" };

A word, or words, that a command takes after its options: exactly one, at most one, or any number.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

Argstype
type Args<S extends Spec> = {
  readonly kind: "args";
  readonly options: OptionValues<S>;
  readonly positionals: readonly string[];
  readonly rest: readonly string[];
};

A command line that fits its spec: the options' values, the arguments, and the words after --.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

Parsedtype
type Parsed<S extends Spec> = { readonly kind: "help" } | Args<S>;

What a command line asks: help, which runs nothing else (erga 247-ergactl FR-006), or the command with its arguments.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

UsageErrortype
type UsageError = | { readonly kind: "unknown-option"; readonly option: string; readonly suggestion: string | undefine… (787 characters)
type UsageError =
  | { readonly kind: "unknown-option"; readonly option: string; readonly suggestion: string | undefined }
  | { readonly kind: "missing-value"; readonly option: string }
  | { readonly kind: "unexpected-value"; readonly option: string; readonly value: string }
  | { readonly kind: "attached-value"; readonly option: string; readonly word: string }
  | { readonly kind: "invalid-value"; readonly option: string; readonly value: string; readonly reason: string }
  | { readonly kind: "repeated-option"; readonly option: string }
  | { readonly kind: "missing-option"; readonly option: string }
  | { readonly kind: "missing-argument"; readonly argument: string }
  | { readonly kind: "unexpected-argument"; readonly argument: string; readonly takes: readonly string[] };

Why a command line does not fit its spec. option is the option as it was written, or its long name where it was given twice or not at all.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

flagfunction
function flag: { <L extends ShortName = never>(o: Common<L> & { readonly negatable: true; readonly default: boolean; }): FlagOption<"default", L>; <L extends ShortName = never>(o: Common<L> & { readonly negatable: true; }): FlagOption<"none", L>; <L extends ShortName = never>(o: Common<L>): FlagOption<"default", L>; }

A flag: false when not given; with negatable, --no-name gives false and an absent flag gives undefined, or the default. A negatable flag with no default. A flag that cannot be negated. The implementation of flag.

Imported by 26 tests of the run (26 passed, 0 failed): the library's results

valuefunction
function value: { <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { reado… (941 characters)
function value: { <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly parse: Parser<T>; readonly required: true; }): ValueOption<T, "required", L>; <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly parse: Parser<T>; readonly default: NoInfer<T>; }): ValueOption<T, "default", L>; <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly parse: Parser<T>; }): ValueOption<T, "none", L>; <L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly required: true; }): ValueOption<string, "required", L>; <L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly default: string; }): ValueOption<string, "default", L>; <L extends ShortName = never>(o: Valued<L>): ValueOption<string, "none", L>; }

An option with one value, parsed by parse, that must be given. An option with one value, parsed by parse, and a default. An option with one value, parsed by parse, undefined when not given. An option with one text value that must be given. An option with one text value and a default. An option with one text value, undefined when not given. The implementation of value.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

manyfunction
function many: { <T, L extends ShortName = never>(o: Common<L> & { readonly valueName?: string | undefined; } & { readonly parse: Parser<T>; }): ManyOption<T, L>; <L extends ShortName = never>(o: Valued<L>): ManyOption<string, L>; }

An option given any number of times, each value parsed by parse. An option given any number of times, each value its text. The implementation of many.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

integerTextfunction
function integerText(t: string): Result<number, string>

A parser of an integer written in decimal, with an optional -, within the safe integers.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

longNamefunction
function longName(key: string): string

The long option of a spec's key: dryRun is --dry-run.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

editDistancefunction
function editDistance(a: string, b: string): number

The number of insertions, deletions and substitutions that turn a into b (Levenshtein).

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

suggestfunction
function suggest(word: string, candidates: readonly string[]): string | undefined

The candidate nearest word by edit distance, the first of equals, if it is within two edits or half the word's length; else nothing.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

parseArgsfunction
function parseArgs<S extends Spec>(argv: readonly string[], spec: S & SpecCheck<S>, operands?: readonly Operand[]): Result<Parsed<S>, UsageError>

Parses argv against spec, and the arguments against operands (none by default): help where it is asked for, else every option's value with the arguments and the words after --, or the first thing that does not fit.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

formatUsageErrorfunction
function formatUsageError(e: UsageError, command?: string): string

A usage error as one sentence; command names the command (ergactl toolchain list), "this command" by default.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

helpTextfunction
function helpText<S extends Spec>(program: string, summary: string, spec: S & SpecCheck<S>, operands?: readonly Operand[]): string

The help of a command: its summary, its usage, its options aligned with their defaults, and its arguments.

Imported by 21 tests of the run (21 passed, 0 failed): the library's results

helpOffunctionno test imports it
function helpOf(program: string, summary: string, spec: Spec, operands?: readonly Operand[]): string

The help of a command whose spec was checked where it was declared (a verb of ./commands.ts), as helpText gives it.

Titles, headings, exports, tables, columns and requirements. Esc closes.