Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(types)!: improve type safety and inference of args #132

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 23 additions & 14 deletions src/args.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import { kebabCase, camelCase } from "scule";
import { parseRawArgs } from "./_parser";
import type { Arg, ArgsDef, ParsedArgs } from "./types";
import type { Arg, ArgAlias, ArgDefault, ArgsDef, EnumArgDef, ParsedArgs } from "./types";
import { CLIError, toArray } from "./_utils";

export function parseArgs<T extends ArgsDef = ArgsDef>(
rawArgs: string[],
argsDef: ArgsDef,
): ParsedArgs<T> {
const parseOptions = {
boolean: [] as string[],
string: [] as string[],
number: [] as string[],
enum: [] as (number | string)[],
mixed: [] as string[],
alias: {} as Record<string, string | string[]>,
default: {} as Record<string, boolean | number | string>,
const parseOptions: {
boolean: string[]
string: string[]
number: string[]
enum: Exclude<EnumArgDef['options'], undefined>
alias: Record<string, ArgAlias>
default: Record<string, ArgDefault>
} = {
boolean: [],
string: [],
number: [],
enum: [],
alias: {},
default: {}
};

const args = resolveArgs(argsDef);
Expand All @@ -23,20 +29,22 @@ export function parseArgs<T extends ArgsDef = ArgsDef>(
if (arg.type === "positional") {
continue;
}

// eslint-disable-next-line unicorn/prefer-switch
if (arg.type === "string" || arg.type === "number") {
parseOptions.string.push(arg.name);
} else if (arg.type === "boolean") {
parseOptions.boolean.push(arg.name);
} else if (arg.type === "enum") {
parseOptions.enum.push(...(arg.options || []));
parseOptions.enum.push(...arg.options);
}

if (arg.default !== undefined) {
parseOptions.default[arg.name] = arg.default;
}

if (arg.alias) {
parseOptions.alias[arg.name] = arg.alias;
parseOptions.alias[arg.name] = toArray(arg.alias);
}
}

Expand All @@ -55,7 +63,7 @@ export function parseArgs<T extends ArgsDef = ArgsDef>(
const nextPositionalArgument = positionalArguments.shift();
if (nextPositionalArgument !== undefined) {
parsedArgsProxy[arg.name] = nextPositionalArgument;
} else if (arg.default === undefined && arg.required !== false) {
} else if (arg.required) {
throw new CLIError(
`Missing required positional argument: ${arg.name.toUpperCase()}`,
"EARG",
Expand Down Expand Up @@ -97,12 +105,13 @@ export function parseArgs<T extends ArgsDef = ArgsDef>(

export function resolveArgs(argsDef: ArgsDef): Arg[] {
const args: Arg[] = [];

for (const [name, argDef] of Object.entries(argsDef || {})) {
args.push({
...argDef,
name,
alias: toArray((argDef as any).alias),
name
});
}

return args;
}
2 changes: 1 addition & 1 deletion src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { CommandContext, CommandDef, ArgsDef } from "./types";
import { CLIError, resolveValue } from "./_utils";
import { parseArgs } from "./args";

export function defineCommand<T extends ArgsDef = ArgsDef>(
export function defineCommand<const T extends ArgsDef = ArgsDef>(
def: CommandDef<T>,
): CommandDef<T> {
return def;
Expand Down
117 changes: 64 additions & 53 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,68 +8,79 @@ export type ArgType =
| "positional"
| undefined;

export type _ArgDef<T extends ArgType, VT extends boolean | number | string> = {
type?: T;
description?: string;
valueHint?: string;
alias?: string | string[];
default?: VT;
required?: boolean;
options?: (string | number)[];
};
export type ArgAlias = string | string[]

export type BooleanArgDef = Omit<_ArgDef<"boolean", boolean>, "options"> & {
negativeDescription?: string;
};
export type StringArgDef = Omit<_ArgDef<"string", string>, "options">;
export type NumberArgDef = Omit<_ArgDef<"number", boolean>, "options">;
export type EnumArgDef = _ArgDef<"enum", string>;
export type PositionalArgDef = Omit<
_ArgDef<"positional", string>,
"alias" | "options"
>;
export type ArgDefault = string | number | boolean | (string | number)[]

export type DefaultOrRequiredArgDef<DefaultT extends ArgDefault> = {
default?: DefaultT
required?: false | undefined
} | {
default?: undefined
required?: boolean
}

export type BaseArgDef<TypeT extends ArgType, DefaultT extends ArgDefault> = {
type: TypeT;
description?: string;
valueHint?: string;
} & DefaultOrRequiredArgDef<DefaultT>

export type BooleanArgDef = BaseArgDef<'boolean', boolean> & {
alias?: ArgAlias;
negativeDescription?: string;
}

export type StringArgDef = BaseArgDef<'string', string> & {
alias?: ArgAlias;
}

export type NumberArgDef = BaseArgDef<'number', number> & {
alias?: ArgAlias;
}

export type EnumArgDef = BaseArgDef<'enum', string | number> & {
options: (string | number)[];
alias?: ArgAlias;
}

export type PositionalArgDef = BaseArgDef<'positional', string>

export type ArgDef =
| BooleanArgDef
| StringArgDef
| NumberArgDef
| PositionalArgDef
| EnumArgDef;
| EnumArgDef
| PositionalArgDef;

export type ArgsDef = Record<string, ArgDef>;

export type Arg = ArgDef & { name: string; alias: string[] };

export type ParsedArgs<T extends ArgsDef = ArgsDef> = { _: string[] } & Record<
{ [K in keyof T]: T[K] extends { type: "positional" } ? K : never }[keyof T],
string
> &
Record<
{
[K in keyof T]: T[K] extends { type: "string" } ? K : never;
}[keyof T],
string
> &
Record<
{
[K in keyof T]: T[K] extends { type: "number" } ? K : never;
}[keyof T],
number
> &
Record<
{
[K in keyof T]: T[K] extends { type: "boolean" } ? K : never;
}[keyof T],
boolean
> &
Record<
{
[K in keyof T]: T[K] extends { type: "enum" } ? K : never;
}[keyof T],
{
[K in keyof T]: T[K] extends { options: infer U } ? U : never;
}[keyof T]
> &
export type Arg = ArgDef & { name: string; };

export type ParsedArg<ArgT extends ArgDef, ExtendsArgT extends ArgDef> = ArgT extends ExtendsArgT
? ArgT['required'] extends true
? ArgT extends { options: (infer U)[] }
? U
: Exclude<ExtendsArgT['default'], undefined>
: ArgT['default'] extends Exclude<ExtendsArgT['default'], undefined>
? ArgT extends { options: (infer U)[] }
? U
: Exclude<ExtendsArgT['default'], undefined>
: ArgT extends { options: (infer U)[] }
? U | undefined
: ExtendsArgT['default']
: never

export type ParsedArgs<T extends ArgsDef = ArgsDef> =
{ _: string[] } &
{
[K in keyof T]:
| ParsedArg<T[K], BooleanArgDef>
| ParsedArg<T[K], StringArgDef>
| ParsedArg<T[K], NumberArgDef>
| ParsedArg<T[K], EnumArgDef>
| ParsedArg<T[K], PositionalArgDef>
} &
Record<string, string | number | boolean | string[]>;

// ----- Command -----
Expand Down
13 changes: 7 additions & 6 deletions src/usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,15 @@ export async function renderUsage<T extends ArgsDef = ArgsDef>(
for (const arg of cmdArgs) {
if (arg.type === "positional") {
const name = arg.name.toUpperCase();
const isRequired = arg.required !== false && arg.default === undefined;
// (isRequired ? " (required)" : " (optional)"
const defaultHint = arg.default ? `="${arg.default}"` : "";

posLines.push([
"`" + name + defaultHint + "`",
arg.description || "",
arg.valueHint ? `<${arg.valueHint}>` : "",
]);
usageLine.push(isRequired ? `<${name}>` : `[${name}]`);
usageLine.push(arg.required ? `<${name}>` : `[${name}]`);
} else {
const isRequired = arg.required === true && arg.default === undefined;
const argStr =
(arg.type === "boolean" && arg.default === true
? [
Expand All @@ -67,11 +65,13 @@ export async function renderUsage<T extends ArgsDef = ArgsDef>(
const description = isNegative
? arg.negativeDescription || arg.description
: arg.description;

argLines.push([
"`" + argStr + (isRequired ? " (required)" : "") + "`",
"`" + argStr + (arg.required ? " (required)" : "") + "`",
description || "",
]);
if (isRequired) {

if (arg.required) {
usageLine.push(argStr);
}
}
Expand Down Expand Up @@ -106,6 +106,7 @@ export async function renderUsage<T extends ArgsDef = ArgsDef>(
);

const hasOptions = argLines.length > 0 || posLines.length > 0;

usageLines.push(
`${colors.underline(colors.bold("USAGE"))} \`${commandName}${
hasOptions ? " [OPTIONS]" : ""
Expand Down