From c8479e5b33f8ca9071502a6c7b11745898c023a3 Mon Sep 17 00:00:00 2001 From: Wei Fu Date: Thu, 20 Jul 2017 19:56:41 +0800 Subject: [PATCH] Add ability to get available sub commands --- command.go | 12 ++++++++++++ command_test.go | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/command.go b/command.go index c3e16b1d..f7d9709d 100644 --- a/command.go +++ b/command.go @@ -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 diff --git a/command_test.go b/command_test.go index aa6658f8..618adc86 100644 --- a/command_test.go +++ b/command_test.go @@ -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) + } +}