Add ability to get available sub commands

This commit is contained in:
Wei Fu 2017-07-20 19:56:41 +08:00
parent 715f41bd7a
commit c8479e5b33
2 changed files with 31 additions and 0 deletions

View file

@ -1073,6 +1073,18 @@ func (c *Command) HasAvailableSubCommands() bool {
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.
func (c *Command) HasParent() bool {
return c.parent != nil

View file

@ -347,3 +347,22 @@ func TestSetHelpCommand(t *testing.T) {
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)
}
}