Skip to content

Commit 2d25abd

Browse files
authored
feat: add (*cliz.Command).Next() (#133)
2 parents 14c1cdb + ebec779 commit 2d25abd

File tree

2 files changed

+53
-3
lines changed

2 files changed

+53
-3
lines changed

exp/cli/cli.go

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,30 @@ func Default[T interface{}](v T) *T { return ptr[T](v) }
109109

110110
func ptr[T interface{}](v T) *T { return &v }
111111

112-
// GetSubcommand returns the subcommand if cmd contains the subcommand.
113-
func (cmd *Command) GetSubcommand(arg string) (subcmd *Command) {
112+
func (cmd *Command) GetName() string {
113+
if cmd == nil {
114+
return ""
115+
}
116+
return cmd.Name
117+
}
118+
119+
func (cmd *Command) Next() *Command {
120+
if cmd == nil {
121+
return nil
122+
}
123+
if len(cmd.calledCommands) == 0 {
124+
return nil
125+
}
126+
for _, subcmd := range cmd.SubCommands {
127+
if len(subcmd.calledCommands) > 0 {
128+
return subcmd
129+
}
130+
}
131+
return nil
132+
}
133+
134+
// getSubcommand returns the subcommand if cmd contains the subcommand.
135+
func (cmd *Command) getSubcommand(arg string) (subcmd *Command) {
114136
for _, subcmd := range cmd.SubCommands {
115137
if subcmd.Name == arg {
116138
return subcmd
@@ -243,7 +265,7 @@ argsLoop:
243265
}
244266
return nil, nil, errorz.Errorf("%s: %w", arg, ErrUnknownOption)
245267
default:
246-
subcmd := cmd.GetSubcommand(arg)
268+
subcmd := cmd.getSubcommand(arg)
247269
// If subcmd is nil, it is not a subcommand.
248270
if subcmd == nil {
249271
cmd.remainingArgs = append(cmd.remainingArgs, arg)

exp/cli/cli_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,34 @@ func TestCommand(t *testing.T) {
184184
t.Fatalf("❌: %v: %+v", args, err)
185185
}
186186

187+
if (*Command)(nil).Next() != nil {
188+
t.Errorf("❌: expect != actual: %v != %v", nil, (*Command)(nil).Next())
189+
}
190+
if (&Command{}).Next() != nil {
191+
t.Errorf("❌: expect != actual: %v != %v", nil, (&Command{}).Next())
192+
}
193+
switch c.GetName() {
194+
case "my-cli":
195+
switch c := c.Next(); c.GetName() {
196+
case "sub-cmd":
197+
switch c := c.Next(); c.GetName() {
198+
case "sub-sub-cmd":
199+
switch c := c.Next(); c.GetName() {
200+
case "":
201+
// OK
202+
default:
203+
t.Errorf("❌: expect != actual: %v != %v", "", c.GetName())
204+
}
205+
default:
206+
t.Errorf("❌: expect != actual: %v != %v", "sub-sub-cmd", c.GetName())
207+
}
208+
default:
209+
t.Errorf("❌: expect != actual: %v != %v", "sub-cmd", c.GetName())
210+
}
211+
default:
212+
t.Errorf("❌: expect != actual: %v != %v", "my-cli", c.GetName())
213+
}
214+
187215
if expect, actual := []string{"my-cli", "sub-cmd", "sub-sub-cmd"}, calledCommands; !reflect.DeepEqual(expect, actual) {
188216
t.Errorf("❌: expect != actual: %v != %v", expect, actual)
189217
}

0 commit comments

Comments
 (0)