Skip to content

Commit

Permalink
Add CommandRouter.SubGroup
Browse files Browse the repository at this point in the history
  • Loading branch information
markuswustenberg committed Oct 8, 2024
1 parent bbb02da commit 0925e03
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
7 changes: 7 additions & 0 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ func (c *CommandRouter) SubFunc(pattern string, cmd CommandFunc) {
c.Sub(pattern, cmd)
}

// SubGroup is a convenience method for adding a subcommand with a new router.
func (c *CommandRouter) SubGroup(pattern string, cb func(r *CommandRouter)) {
r := NewCommandRouter()
cb(r)
c.Sub(pattern, r)
}

// Group commands with a new router.
// The middleware from the parent router is copied to the new router.
func (c *CommandRouter) Group(cb func(r *CommandRouter)) {
Expand Down
42 changes: 42 additions & 0 deletions router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,48 @@ func TestCommandRouter_Group(t *testing.T) {
})
}

func TestCommandRouter_SubGroup(t *testing.T) {
t.Run("can group commands with a new middleware stack", func(t *testing.T) {
r := clir.NewCommandRouter()

m1 := newMiddleware(t, "m1")
m2 := newMiddleware(t, "m2")

r.Use(m1)

r.SubGroup("party", func(r *clir.CommandRouter) {
r.Use(m2)

r.SubFunc("", func(ctx clir.Context) error {
ctx.Println("party root")
return nil
})

r.SubFunc("list", func(ctx clir.Context) error {
ctx.Println("party list")
return nil
})
})

var b strings.Builder
err := r.Run(clir.Context{
Args: []string{"party"},
Out: &b,
})
is.NotError(t, err)
is.Equal(t, "m1\nm2\nparty root\n", b.String())

b.Reset()

err = r.Run(clir.Context{
Args: []string{"party", "list"},
Out: &b,
})
is.NotError(t, err)
is.Equal(t, "m1\nm2\nparty list\n", b.String())
})
}

func newMiddleware(t *testing.T, name string) clir.Middleware {
return func(next clir.Command) clir.Command {
return clir.CommandFunc(func(ctx clir.Context) error {
Expand Down

0 comments on commit 0925e03

Please sign in to comment.