mirror of
https://github.com/spf13/cobra
synced 2025-05-05 04:47:22 +00:00
Check if a command is 'hidden' before adding length to usage
This commit is contained in:
parent
4f0facbcee
commit
6e6f85e119
2 changed files with 47 additions and 23 deletions
|
@ -1162,6 +1162,7 @@ func (c *Command) AddCommand(cmds ...*Command) {
|
|||
panic("Command can't be a child of itself")
|
||||
}
|
||||
cmds[i].parent = c
|
||||
if !cmds[i].Hidden {
|
||||
// update max lengths
|
||||
usageLen := len(x.Use)
|
||||
if usageLen > c.commandsMaxUseLen {
|
||||
|
@ -1175,6 +1176,7 @@ func (c *Command) AddCommand(cmds ...*Command) {
|
|||
if nameLen > c.commandsMaxNameLen {
|
||||
c.commandsMaxNameLen = nameLen
|
||||
}
|
||||
}
|
||||
// If global normalization function exists, update all children
|
||||
if c.globNormFunc != nil {
|
||||
x.SetGlobalNormalizationFunc(c.globNormFunc)
|
||||
|
@ -1203,6 +1205,7 @@ main:
|
|||
c.commandsMaxCommandPathLen = 0
|
||||
c.commandsMaxNameLen = 0
|
||||
for _, command := range c.commands {
|
||||
if !command.Hidden {
|
||||
usageLen := len(command.Use)
|
||||
if usageLen > c.commandsMaxUseLen {
|
||||
c.commandsMaxUseLen = usageLen
|
||||
|
@ -1216,6 +1219,7 @@ main:
|
|||
c.commandsMaxNameLen = nameLen
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
|
||||
|
|
|
@ -2161,3 +2161,23 @@ func TestSetContextPersistentPreRun(t *testing.T) {
|
|||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandsLengthWithoutHiddenCommands(t *testing.T) {
|
||||
rootCmd := &Command{Use: "root", TraverseChildren: true}
|
||||
rootCmd.Flags().String("foo", "", "foo things")
|
||||
// add a normal command
|
||||
childCmd := &Command{Use: "child"}
|
||||
childCmd.Flags().String("str", "", "")
|
||||
rootCmd.AddCommand(childCmd)
|
||||
//add a hidden command
|
||||
child2Cmd := &Command{Use: "reallyLongCommand"}
|
||||
child2Cmd.Flags().String("str", "", "")
|
||||
child2Cmd.Hidden = true
|
||||
rootCmd.AddCommand(child2Cmd)
|
||||
//hidden commands should not be taken into account for usage length
|
||||
expectedmaxLen := 5
|
||||
fmt.Println(rootCmd.commandsMaxUseLen)
|
||||
if rootCmd.commandsMaxUseLen != expectedmaxLen {
|
||||
t.Errorf("Expected value: \n %v\nGot:\n %v\n", expectedmaxLen, rootCmd.commandsMaxUseLen)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue