mirror of
https://github.com/spf13/cobra
synced 2024-11-25 07:07:15 +00:00
Add ability to get available sub commands
This commit is contained in:
parent
715f41bd7a
commit
c8479e5b33
2 changed files with 31 additions and 0 deletions
12
command.go
12
command.go
|
@ -1073,6 +1073,18 @@ func (c *Command) HasAvailableSubCommands() bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AvailableSubCommands returns available sub commands.
|
||||||
|
func (c *Command) AvailableSubCommands() []*Command {
|
||||||
|
subCmds := []*Command{}
|
||||||
|
|
||||||
|
for _, sub := range c.commands {
|
||||||
|
if sub.IsAvailableCommand() {
|
||||||
|
subCmds = append(subCmds, sub)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return subCmds
|
||||||
|
}
|
||||||
|
|
||||||
// HasParent determines if the command is a child command.
|
// HasParent determines if the command is a child command.
|
||||||
func (c *Command) HasParent() bool {
|
func (c *Command) HasParent() bool {
|
||||||
return c.parent != nil
|
return c.parent != nil
|
||||||
|
|
|
@ -347,3 +347,22 @@ func TestSetHelpCommand(t *testing.T) {
|
||||||
t.Errorf("Expected to contain %q message, but got %q", correctMessage, output.String())
|
t.Errorf("Expected to contain %q message, but got %q", correctMessage, output.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestAvailableSubCommands checks, if AvailableSubCommands works correctly
|
||||||
|
func TestAvailableSubCommands(t *testing.T) {
|
||||||
|
doNothing := func(*Command, []string) {}
|
||||||
|
|
||||||
|
rootCmd := &Command{Run: doNothing}
|
||||||
|
|
||||||
|
helpSubCmd := &Command{Use: "H", Run: doNothing}
|
||||||
|
deprecatedSubCmd := &Command{Use: "D", Deprecated: "no reason", Run: doNothing}
|
||||||
|
availableSubCmd := &Command{Use: "A", Run: doNothing}
|
||||||
|
|
||||||
|
rootCmd.AddCommand(helpSubCmd, deprecatedSubCmd, availableSubCmd)
|
||||||
|
rootCmd.SetHelpCommand(helpSubCmd)
|
||||||
|
|
||||||
|
res, expect := rootCmd.AvailableSubCommands(), []*Command{availableSubCmd}
|
||||||
|
if !reflect.DeepEqual(res, expect) {
|
||||||
|
t.Errorf("Expected %v, but got %v", expect, res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue