1- import type { CommandContext , CommandDef , ArgsDef } from "./types" ;
1+ import type {
2+ CommandContext ,
3+ CommandDef ,
4+ ArgsDef ,
5+ SubCommandsDef ,
6+ } from "./types" ;
27import { CLIError , resolveValue } from "./_utils" ;
38import { parseArgs } from "./args" ;
49
@@ -14,6 +19,27 @@ export interface RunCommandOptions {
1419 showUsage ?: boolean ;
1520}
1621
22+ async function getSubCommand (
23+ subCommandsList : SubCommandsDef ,
24+ subCommandName : string ,
25+ ) : Promise < CommandDef < any > | undefined > {
26+ const subCommand = await resolveValue ( subCommandsList [ subCommandName ] ) ;
27+
28+ if ( subCommand ) {
29+ return subCommand ;
30+ }
31+
32+ for ( const _subCmd of Object . values ( subCommandsList ) ) {
33+ const subCmd = await resolveValue ( _subCmd ) ;
34+ const subCmdMeta = await resolveValue ( subCmd . meta ) ;
35+ if ( ( subCmdMeta ?. aliases || [ ] ) . includes ( subCommandName ) ) {
36+ return subCmd ;
37+ }
38+ }
39+
40+ return undefined ;
41+ }
42+
1743export async function runCommand < T extends ArgsDef = ArgsDef > (
1844 cmd : CommandDef < T > ,
1945 opts : RunCommandOptions ,
@@ -43,20 +69,7 @@ export async function runCommand<T extends ArgsDef = ArgsDef>(
4369 ) ;
4470 const subCommandName = opts . rawArgs [ subCommandArgIndex ] ;
4571 if ( subCommandName ) {
46- let subCommand = await resolveValue ( subCommands [ subCommandName ] ) ;
47-
48- if ( ! subCommand ) {
49- for ( const _subCmd of Object . values ( subCommands ) ) {
50- const subCmd = await resolveValue ( _subCmd ) ;
51- const subCmdMeta = await resolveValue ( subCmd . meta ) ;
52- for ( const alias of subCmdMeta ?. aliases || [ ] ) {
53- if ( alias === subCommandName ) {
54- subCommand = subCmd ;
55- break ;
56- }
57- }
58- }
59- }
72+ const subCommand = await getSubCommand ( subCommands , subCommandName ) ;
6073
6174 if ( ! subCommand ) {
6275 throw new CLIError (
@@ -95,20 +108,7 @@ export async function resolveSubCommand<T extends ArgsDef = ArgsDef>(
95108 if ( subCommands && Object . keys ( subCommands ) . length > 0 ) {
96109 const subCommandArgIndex = rawArgs . findIndex ( ( arg ) => ! arg . startsWith ( "-" ) ) ;
97110 const subCommandName = rawArgs [ subCommandArgIndex ] ;
98- let subCommand = await resolveValue ( subCommands [ subCommandName ] ) ;
99-
100- if ( ! subCommand ) {
101- for ( const _subCmd of Object . values ( subCommands ) ) {
102- const subCmd = await resolveValue ( _subCmd ) ;
103- const subCmdMeta = await resolveValue ( subCmd . meta ) ;
104- for ( const alias of subCmdMeta ?. aliases || [ ] ) {
105- if ( alias === subCommandName ) {
106- subCommand = subCmd ;
107- break ;
108- }
109- }
110- }
111- }
111+ const subCommand = await getSubCommand ( subCommands , subCommandName ) ;
112112
113113 if ( subCommand ) {
114114 return resolveSubCommand (
0 commit comments