1

Is it possible to suppress Aliases to show up in the help screen of a golang cobra app? I basically would like to get rid of the whole "Aliases" section below:

Usage:
  my-app [flags]

Aliases:
 alias1 , alias2

Flags:
  -h, --help              help for this command

I know it's possible to hide flags from showing up in help (cmd.Flags().MarkHidden("myflag")). Is it somehow possible to hide Aliases as well?

Chris
  • 567
  • 6
  • 24

2 Answers2

3

That would mean defining your own Usage function, which is possible using usageFunc
Or using a specific Usage template (command#SetUsageTemplate()), as stated in the "Defining your own usage" README section.

You can see the default template here. It does include an Aliases section:

Aliases:
  {{.NameAndAliases}}{{end}}{{if .HasExample}}

All you would need is define the same temaplate, but exclusing the Aliases part.

You can see an example of such a temmplate for emacski/redact.
And yes, it has no Aliases.

{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}{{end}}
{{if .HasAvailableLocalFlags}}
Options:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableSubCommands}}
Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} COMMAND --help" for more information about a command.{{end}}
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
1

use custom Usage template, just remove alias part

customUsageTpl:=`Usage:{{if .Runnable}}
  {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
  {{.CommandPath}} [command]{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`

Then set custom template

cmd.SetUsageTemplate(customUsageTpl)
Moch Lutfi
  • 552
  • 10
  • 27
  • Yes, I did mention `setUsageTemplate` in my answer. And I did reference the default usage template with https://github.com/spf13/cobra/blob/5155946348eed0f79a76f7743407c0c933e3b5f0/command.go#L468-L501 in my answer. – VonC Jun 02 '20 at 05:49