Skip to content

Cobra won't show help if cmd is not Runnable #790

Closed
@retpolanne

Description

@retpolanne

I have a subcommand that has no Run function.

var containerCmd = &cobra.Command{
	Use:   "container",
	Short: "Global settings for running containers",
}

func init() {
	configCmd.AddCommand(containerCmd)
	containerCmd.PersistentFlags().String("networkEndpoint", "", "Specify a network endpoint (in case you need to network between containers)")
	viper.BindPFlag("networkEndpoint", containerCmd.PersistentFlags().Lookup("networkEndpoint"))
}
...

It only shows the usage when it's added to the rootCmd. When it is not, it only shows the short description. It won't show the help even if I pass the --help flag. It should show the usage when I pass the help flag or no arguments.

I noticed two things:

  1. Cobra returns "help requested" if the command is not runnable

    cobra/command.go

    Lines 724 to 726 in fe5e611

    if !c.Runnable() {
    return flag.ErrHelp
    }
  2. Cobra only renders the Usage if the command is runnable

    cobra/command.go

    Lines 432 to 434 in fe5e611

    return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
    {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`

I added HasFlags to this template and it always displays the usage.

It might be related to #206 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions