Skip to content

Commit

Permalink
Hard-code the original Cobra help template (#8)
Browse files Browse the repository at this point in the history
Cobra 1.6 has modified the default help template to support grouping.
This breaks the logic in cobrautils which manipulates that help string.

This commit hard-codes the original cobra help string instead of
obtaining it from Cobra.  This allows cobrautils to continue working as
before for older versions of Cobra or newer ones.

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>

Signed-off-by: Marc Khouzam <marc.khouzam@gmail.com>
  • Loading branch information
marckhouzam authored Nov 30, 2022
1 parent d607119 commit acdfead
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions help_sections.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,36 @@ type HelpSection struct {
}

func HelpSectionsUsageTemplate(sections []HelpSection) string {
unmodifiedCmd := &cobra.Command{}
usageTemplate := unmodifiedCmd.UsageTemplate()
usageTemplate := `Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{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}}
`

const defaultTpl = `{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}`

if !strings.Contains(usageTemplate, defaultTpl) {
panic("Expected to find available commands section in spf13/cobra default usage template")
}

newTpl := "{{if .HasAvailableSubCommands}}"

for _, section := range sections {
Expand Down

0 comments on commit acdfead

Please sign in to comment.