Skip to content

Commit

Permalink
feat(default): support default sub command (unjs#153)
Browse files Browse the repository at this point in the history
  • Loading branch information
fu050409 committed Jul 5, 2024
1 parent 53cd585 commit 274cd07
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ export async function runCommand<T extends ArgsDef = ArgsDef>(
await cmd.setup(context);
}

// Checkout default sub command
const defaultSubCommand = await resolveValue(cmd.default);
if (defaultSubCommand && cmd.run) {
throw new CLIError(
`Command has a handler specified and a default sub command.`,
"E_DUPLICATE_COMMAND",
);
}

// Handle sub command
let result: unknown;
try {
Expand All @@ -41,7 +50,8 @@ export async function runCommand<T extends ArgsDef = ArgsDef>(
const subCommandArgIndex = opts.rawArgs.findIndex(
(arg) => !arg.startsWith("-"),
);
const subCommandName = opts.rawArgs[subCommandArgIndex];
const subCommandName =
opts.rawArgs[subCommandArgIndex] || defaultSubCommand;
if (subCommandName) {
if (!subCommands[subCommandName]) {
throw new CLIError(
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export type SubCommandsDef = Record<string, Resolvable<CommandDef<any>>>;
export type CommandDef<T extends ArgsDef = ArgsDef> = {
meta?: Resolvable<CommandMeta>;
args?: Resolvable<T>;
default?: Resolvable<keyof ArgsDef | string>;
subCommands?: Resolvable<SubCommandsDef>;
setup?: (context: CommandContext<T>) => any | Promise<any>;
cleanup?: (context: CommandContext<T>) => any | Promise<any>;
Expand Down

0 comments on commit 274cd07

Please sign in to comment.