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

feat(default): support default sub command #156

Open
wants to merge 1 commit 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
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