Allow linker to perform deadcode elimination for program using Cobra (#1956)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Restructure code to let linker perform deadcode elimination step Cobra, in its default configuration, will execute a template to generate help, usage and version outputs. Text/template execution calls MethodByName and MethodByName disables dead code elimination in the Go linker, therefore all programs that make use of cobra will be linked with dead code elimination disabled, even if they end up replacing the default usage, help and version formatters with a custom function and no actual text/template evaluations are ever made at runtime. Dead code elimination in the linker helps reduce disk space and memory utilization of programs. For example, for the simple example program used by TestDeadcodeElimination 40% of the final executable size is dead code. For a more realistic example, 12% of the size of Delve's executable is deadcode. This PR changes Cobra so that, in its default configuration, it does not automatically inhibit deadcode elimination by: 1. changing Cobra's default behavior to emit output for usage and help using simple Go functions instead of template execution 2. quarantining all calls to template execution into SetUsageTemplate, SetHelpTemplate and SetVersionTemplate so that the linker can statically determine if they are reachable
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Marc Khouzam <marc.khouzam@gmail.com>
Diff stats
6 files+365 added−61 removed
- other:+365 added−61 removed
Provenance
- Commit
611e16c- Tree
9fd0caa- Author
Alessandro Arzilli <alessandro.arzilli@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
09d5664
6 files changed+365 added−61 removed
modified:site/content/user_guide.md+10 added
552 unmodified lines553 ```554 555 The latter two will also apply to any children commands.556 557+Note that templates specified with `SetHelpTemplate` are evaluated using558+`text/template` which can increase the size of the compiled executable.559+560 ## Usage Message561 562 When the user provides an invalid flag or invalid command, Cobra responds by563 showing the user the 'usage'.24 unmodified lines588 Use "cobra [command] --help" for more information about a command.589 ```590 591 ### Defining your own usage592+593 You can provide your own usage function or template for Cobra to use.594 Like help, the function and template are overridable through public methods:595 596 ```go597 cmd.SetUsageFunc(f func(*Command) error)598 cmd.SetUsageTemplate(s string)599 ```600 601+Note that templates specified with `SetUsageTemplate` are evaluated using602+`text/template` which can increase the size of the compiled executable.603+604 ## Version Flag605 606 Cobra adds a top-level '--version' flag if the Version field is set on the root command.607 Running an application with the '--version' flag will print the version to stdout using608 the version template. The template can be customized using the609 `cmd.SetVersionTemplate(s string)` function.610 611+Note that templates specified with `SetVersionTemplate` are evaluated using612+`text/template` which can increase the size of the compiled executable.613+614 ## Error Message Prefix615 616 Cobra prints an error message when receiving a non-nil error value.617 The default error message is `Error: <error contents>`.202 unmodified linesmodified:cobra_test.go+77 added
13 unmodified lines14 15 package cobra16 17 import (18+ "os"19+ "os/exec"20+ "path/filepath"21+ "runtime"22+ "strings"23 "testing"24 "text/template"25 )26 199 unmodified lines226 }227 })228 }229 }230+231+// TestDeadcodeElimination checks that a simple program using cobra in its232+// default configuration is linked taking full advantage of the linker's233+// deadcode elimination step.234+//235+// If reflect.Value.MethodByName/reflect.Value.Method are reachable the236+// linker will not always be able to prove that exported methods are237+// unreachable, making deadcode elimination less effective. Using238+// text/template and html/template makes reflect.Value.MethodByName239+// reachable.240+// Since cobra can use text/template templates this test checks that in its241+// default configuration that code path can be proven to be unreachable by242+// the linker.243+//244+// See also: https://github.com/spf13/cobra/pull/1956245+func TestDeadcodeElimination(t *testing.T) {246+ if runtime.GOOS == "windows" {247+ t.Skip("go tool nm fails on windows")248+ }249+250+ // check that a simple program using cobra in its default configuration is251+ // linked with deadcode elimination enabled.252+ const (253+ dirname = "test_deadcode"254+ progname = "test_deadcode_elimination"255+ )256+ _ = os.Mkdir(dirname, 0770)257+ defer os.RemoveAll(dirname)258+ filename := filepath.Join(dirname, progname+".go")259+ err := os.WriteFile(filename, []byte(`package main260+261+import (262+ "fmt"263+ "os"264+265+ "github.com/spf13/cobra"266+)267+268+var rootCmd = &cobra.Command{269+ Version: "1.0",270+ Use: "example_program",271+ Short: "example_program - test fixture to check that deadcode elimination is allowed",272+ Run: func(cmd *cobra.Command, args []string) {273+ fmt.Println("hello world")274+ },275+ Aliases: []string{"alias1", "alias2"},276+ Example: "stringer --help",277+}278+279+func main() {280+ if err := rootCmd.Execute(); err != nil {281+ fmt.Fprintf(os.Stderr, "Whoops. There was an error while executing your CLI '%s'", err)282+ os.Exit(1)283+ }284+}285+`), 0600)286+ if err != nil {287+ t.Fatalf("could not write test program: %v", err)288+ }289+ buf, err := exec.Command("go", "build", filename).CombinedOutput()290+ if err != nil {291+ t.Fatalf("could not compile test program: %s", string(buf))292+ }293+ defer os.Remove(progname)294+ buf, err = exec.Command("go", "tool", "nm", progname).CombinedOutput()295+ if err != nil {296+ t.Fatalf("could not run go tool nm: %v", err)297+ }298+ if strings.Contains(string(buf), "MethodByName") {299+ t.Error("compiled programs contains MethodByName symbol")300+ }301+}modified:cobra.go+10 added-6 removed
174 unmodified lines175 formattedString := fmt.Sprintf("%%-%ds", padding)176 return fmt.Sprintf(formattedString, s)177 }178 179+func tmpl(text string) *tmplFunc {180+ return &tmplFunc{179-// tmpl executes the given template text on data, writing the result to w.180-func tmpl(w io.Writer, text string, data interface{}) error {181- t := template.New("top")182- t.Funcs(templateFuncs)183- template.Must(t.Parse(text))184- return t.Execute(w, data)181+ tmpl: text,182+ fn: func(w io.Writer, data interface{}) error {183+ t := template.New("top")184+ t.Funcs(templateFuncs)185+ template.Must(t.Parse(text))186+ return t.Execute(w, data)187+ },188+ }189 }190 191 // ld compares two strings and returns the levenshtein distance between them.192 func ld(s, t string, ignoreCase bool) int {54 unmodified linesmodified:command_test.go+58 added
1016 unmodified lines1017 t.Errorf("Expected to contain %q, got %q", expected, got)1018 }1019 }1020 1021+func TestSetHelpTemplate(t *testing.T) {1022+ rootCmd := &Command{Use: "root", Run: emptyRun}1023+ childCmd := &Command{Use: "child", Run: emptyRun}1024+ rootCmd.AddCommand(childCmd)1025+1026+ rootCmd.SetHelpTemplate("WORKS {{.UseLine}}")1027+1028+ // Call the help on the root command and check the new template is used1029+ got, err := executeCommand(rootCmd, "--help")1030+ if err != nil {1031+ t.Errorf("Unexpected error: %v", err)1032+ }1033+1034+ expected := "WORKS " + rootCmd.UseLine()1035+ if got != expected {1036+ t.Errorf("Expected %q, got %q", expected, got)1037+ }1038+1039+ // Call the help on the child command and check1040+ // the new template is inherited from the parent1041+ got, err = executeCommand(rootCmd, "child", "--help")1042+ if err != nil {1043+ t.Errorf("Unexpected error: %v", err)1044+ }1045+1046+ expected = "WORKS " + childCmd.UseLine()1047+ if got != expected {1048+ t.Errorf("Expected %q, got %q", expected, got)1049+ }1050+}1051+1052 func TestHelpFlagExecuted(t *testing.T) {1053 rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}1054 1055 output, err := executeCommand(rootCmd, "--help")57 unmodified lines1113 1114 checkStringContains(t, output, childCmd.Long)1115 }1116 1117+func TestSetUsageTemplate(t *testing.T) {1118+ rootCmd := &Command{Use: "root", Run: emptyRun}1119+ childCmd := &Command{Use: "child", Run: emptyRun}1120+ rootCmd.AddCommand(childCmd)1121+1122+ rootCmd.SetUsageTemplate("WORKS {{.UseLine}}")1123+1124+ // Trigger the usage on the root command and check the new template is used1125+ got, err := executeCommand(rootCmd, "--invalid")1126+ if err == nil {1127+ t.Errorf("Expected error but did not get one")1128+ }1129+1130+ expected := "WORKS " + rootCmd.UseLine()1131+ checkStringContains(t, got, expected)1132+1133+ // Trigger the usage on the child command and check1134+ // the new template is inherited from the parent1135+ got, err = executeCommand(rootCmd, "child", "--invalid")1136+ if err == nil {1137+ t.Errorf("Expected error but did not get one")1138+ }1139+1140+ expected = "WORKS " + childCmd.UseLine()1141+ checkStringContains(t, got, expected)1142+}1143+1144 func TestVersionFlagExecuted(t *testing.T) {1145 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1146 1147 output, err := executeCommand(rootCmd, "--version", "arg1")1765 unmodified linesmodified:command.go+209 added-54 removed
30 unmodified lines31 32 const (33 FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"34 CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"35+36+ helpFlagName = "help"37+ helpCommandName = "help"38 )39 40 // FParseErrWhitelist configures Flag parse errors to be ignored41 type FParseErrWhitelist flag.ParseErrorsWhitelist127 unmodified lines169 170 // usageFunc is usage func defined by user.171 usageFunc func(*Command) error172 // usageTemplate is usage template defined by user.170- usageTemplate string173+ usageTemplate *tmplFunc174 // flagErrorFunc is func defined by user and it's called when the parsing of175 // flags returns an error.176 flagErrorFunc func(*Command, error) error177 // helpTemplate is help template defined by user.175- helpTemplate string178+ helpTemplate *tmplFunc179 // helpFunc is help func defined by user.180 helpFunc func(*Command, []string)181 // helpCommand is command with usage 'help'. If it's not defined by user,182 // cobra uses default help command.4 unmodified lines187 // completionCommandGroupID is the group id for the completion command188 completionCommandGroupID string189 190 // versionTemplate is the version template defined by user.188- versionTemplate string191+ versionTemplate *tmplFunc192 193 // errPrefix is the error message prefix defined by user.194 errPrefix string195 118 unmodified lines314 }315 316 // SetUsageTemplate sets usage template. Can be defined by Application.317 func (c *Command) SetUsageTemplate(s string) {315- c.usageTemplate = s318+ c.usageTemplate = tmpl(s)319 }320 321 // SetFlagErrorFunc sets a function to generate an error when flag parsing322 // fails.27 unmodified lines350 }351 352 // SetHelpTemplate sets help template to be used. Application can use it to set custom template.353 func (c *Command) SetHelpTemplate(s string) {351- c.helpTemplate = s354+ c.helpTemplate = tmpl(s)355 }356 357 // SetVersionTemplate sets version template to be used. Application can use it to set custom template.358 func (c *Command) SetVersionTemplate(s string) {356- c.versionTemplate = s359+ c.versionTemplate = tmpl(s)360 }361 362 // SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.363 func (c *Command) SetErrPrefix(s string) {72 unmodified lines436 return c.Parent().UsageFunc()437 }438 return func(c *Command) error {439 c.mergePersistentFlags()437- err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)440+ fn := c.getUsageTemplateFunc()441+ err := fn(c.OutOrStderr(), c)442 if err != nil {443 c.PrintErrln(err)444 }445 return err446 }447 }448 449+// getUsageTemplateFunc returns the usage template function for the command450+// going up the command tree if necessary.451+func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error {452+ if c.usageTemplate != nil {453+ return c.usageTemplate.fn454+ }455+456+ if c.HasParent() {457+ return c.parent.getUsageTemplateFunc()458+ }459+ return defaultUsageFunc460+}461+462 // Usage puts out the usage for the command.463 // Used when a user provides invalid input.464 // Can be defined by user by overriding UsageFunc.465 func (c *Command) Usage() error {10 unmodified lines476 return c.Parent().HelpFunc()477 }478 return func(c *Command, a []string) {479 c.mergePersistentFlags()480+ fn := c.getHelpTemplateFunc()481 // The help should be sent to stdout482 // See https://github.com/spf13/cobra/issues/1002465- err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)483+ err := fn(c.OutOrStdout(), c)484 if err != nil {485 c.PrintErrln(err)486 }487 }488 }489 490+// getHelpTemplateFunc returns the help template function for the command491+// going up the command tree if necessary.492+func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error {493+ if c.helpTemplate != nil {494+ return c.helpTemplate.fn495+ }496+497+ if c.HasParent() {498+ return c.parent.getHelpTemplateFunc()499+ }500+501+ return defaultHelpFunc502+}503+504 // Help puts out the help for the command.505 // Used when a user calls help [command].506 // Can be defined by user by overriding HelpFunc.507 func (c *Command) Help() error {66 unmodified lines574 return c.parent.commandsMaxNameLen575 }576 577 // UsageTemplate returns usage template for the command.578+// This function is kept for backwards-compatibility reasons.579 func (c *Command) UsageTemplate() string {547- if c.usageTemplate != "" {548- return c.usageTemplate580+ if c.usageTemplate != nil {581+ return c.usageTemplate.tmpl582 }583 584 if c.HasParent() {585 return c.parent.UsageTemplate()586 }554- return `Usage:{{if .Runnable}}555- {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}556- {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}557-558-Aliases:559- {{.NameAndAliases}}{{end}}{{if .HasExample}}560-561-Examples:562-{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}563-564-Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}565- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}566-567-{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}568- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}569-570-Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}571- {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}572-573-Flags:574-{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}575-576-Global Flags:577-{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}578-579-Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}580- {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}581-582-Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}583-`587+ return defaultUsageTemplate588 }589 590 // HelpTemplate return help template for the command.591+// This function is kept for backwards-compatibility reasons.592 func (c *Command) HelpTemplate() string {588- if c.helpTemplate != "" {589- return c.helpTemplate593+ if c.helpTemplate != nil {594+ return c.helpTemplate.tmpl595 }596 597 if c.HasParent() {598 return c.parent.HelpTemplate()599 }595- return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}596-597-{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`600+ return defaultHelpTemplate601 }602 603 // VersionTemplate return version template for the command.604+// This function is kept for backwards-compatibility reasons.605 func (c *Command) VersionTemplate() string {602- if c.versionTemplate != "" {603- return c.versionTemplate606+ if c.versionTemplate != nil {607+ return c.versionTemplate.tmpl608 }609 610 if c.HasParent() {611 return c.parent.VersionTemplate()612 }609- return `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}610-`613+ return defaultVersionTemplate614 }615 616+// getVersionTemplateFunc returns the version template function for the command617+// going up the command tree if necessary.618+func (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error {619+ if c.versionTemplate != nil {620+ return c.versionTemplate.fn621+ }622+623+ if c.HasParent() {624+ return c.parent.getVersionTemplateFunc()625+ }626+ return defaultVersionFunc627+}628+629 // ErrPrefix return error message prefix for the command630 func (c *Command) ErrPrefix() string {631 if c.errPrefix != "" {632 return c.errPrefix276 unmodified lines909 }910 911 // If help is called, regardless of other flags, return we want help.912 // Also say we need help if the command isn't runnable.897- helpVal, err := c.Flags().GetBool("help")913+ helpVal, err := c.Flags().GetBool(helpFlagName)914 if err != nil {915 // should be impossible to get here as we always declare a help916 // flag in InitDefaultHelpFlag()917 c.Println("\"help\" flag declared as non-bool. Please correct your code")11 unmodified lines929 c.Println("\"version\" flag declared as non-bool. Please correct your code")930 return err931 }932 if versionVal {917- err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)933+ fn := c.getVersionTemplateFunc()934+ err := fn(c.OutOrStdout(), c)935 if err != nil {936 c.Println(err)937 }938 return err267 unmodified lines1206 // It is called automatically by executing the c or by calling help and usage.1207 // If c already has help flag, it will do nothing.1208 func (c *Command) InitDefaultHelpFlag() {1209 c.mergePersistentFlags()1193- if c.Flags().Lookup("help") == nil {1210+ if c.Flags().Lookup(helpFlagName) == nil {1211 usage := "help for "1212 name := c.DisplayName()1213 if name == "" {1214 usage += "this command"1215 } else {1216 usage += name1217 }1201- c.Flags().BoolP("help", "h", false, usage)1202- _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})1218+ c.Flags().BoolP(helpFlagName, "h", false, usage)1219+ _ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"})1220 }1221 }1222 1223 // InitDefaultVersionFlag adds default version flag to c.691 unmodified lines1915 }1916 1917 return s == t1918 }1919+1920+// tmplFunc holds a template and a function that will execute said template.1921+type tmplFunc struct {1922+ tmpl string1923+ fn func(io.Writer, interface{}) error1924+}1925+1926+var defaultUsageTemplate = `Usage:{{if .Runnable}}1927+ {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}1928+ {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}1929+1930+Aliases:1931+ {{.NameAndAliases}}{{end}}{{if .HasExample}}1932+1933+Examples:1934+{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}1935+1936+Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}1937+ {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}1938+1939+{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}1940+ {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}1941+1942+Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}1943+ {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}1944+1945+Flags:1946+{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}1947+1948+Global Flags:1949+{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}1950+1951+Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}1952+ {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}1953+1954+Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}1955+`1956+1957+// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync.1958+func defaultUsageFunc(w io.Writer, in interface{}) error {1959+ c := in.(*Command)1960+ fmt.Fprint(w, "Usage:")1961+ if c.Runnable() {1962+ fmt.Fprintf(w, "\n %s", c.UseLine())1963+ }1964+ if c.HasAvailableSubCommands() {1965+ fmt.Fprintf(w, "\n %s [command]", c.CommandPath())1966+ }1967+ if len(c.Aliases) > 0 {1968+ fmt.Fprintf(w, "\n\nAliases:\n")1969+ fmt.Fprintf(w, " %s", c.NameAndAliases())1970+ }1971+ if c.HasExample() {1972+ fmt.Fprintf(w, "\n\nExamples:\n")1973+ fmt.Fprintf(w, "%s", c.Example)1974+ }1975+ if c.HasAvailableSubCommands() {1976+ cmds := c.Commands()1977+ if len(c.Groups()) == 0 {1978+ fmt.Fprintf(w, "\n\nAvailable Commands:")1979+ for _, subcmd := range cmds {1980+ if subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName {1981+ fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)1982+ }1983+ }1984+ } else {1985+ for _, group := range c.Groups() {1986+ fmt.Fprintf(w, "\n\n%s", group.Title)1987+ for _, subcmd := range cmds {1988+ if subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {1989+ fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)1990+ }1991+ }1992+ }1993+ if !c.AllChildCommandsHaveGroup() {1994+ fmt.Fprintf(w, "\n\nAdditional Commands:")1995+ for _, subcmd := range cmds {1996+ if subcmd.GroupID == "" && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {1997+ fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)1998+ }1999+ }2000+ }2001+ }2002+ }2003+ if c.HasAvailableLocalFlags() {2004+ fmt.Fprintf(w, "\n\nFlags:\n")2005+ fmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages()))2006+ }2007+ if c.HasAvailableInheritedFlags() {2008+ fmt.Fprintf(w, "\n\nGlobal Flags:\n")2009+ fmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages()))2010+ }2011+ if c.HasHelpSubCommands() {2012+ fmt.Fprintf(w, "\n\nAdditional help topcis:")2013+ for _, subcmd := range c.Commands() {2014+ if subcmd.IsAdditionalHelpTopicCommand() {2015+ fmt.Fprintf(w, "\n %s %s", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short)2016+ }2017+ }2018+ }2019+ if c.HasAvailableSubCommands() {2020+ fmt.Fprintf(w, "\n\nUse \"%s [command] --help\" for more information about a command.", c.CommandPath())2021+ }2022+ fmt.Fprintln(w)2023+ return nil2024+}2025+2026+var defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}2027+2028+{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`2029+2030+// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync.2031+func defaultHelpFunc(w io.Writer, in interface{}) error {2032+ c := in.(*Command)2033+ usage := c.Long2034+ if usage == "" {2035+ usage = c.Short2036+ }2037+ usage = trimRightSpace(usage)2038+ if usage != "" {2039+ fmt.Fprintln(w, usage)2040+ fmt.Fprintln(w)2041+ }2042+ if c.Runnable() || c.HasSubCommands() {2043+ fmt.Fprint(w, c.UsageString())2044+ }2045+ return nil2046+}2047+2048+var defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}2049+`2050+2051+// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync.2052+func defaultVersionFunc(w io.Writer, in interface{}) error {2053+ c := in.(*Command)2054+ _, err := fmt.Fprintf(w, "%s version %s\n", c.DisplayName(), c.Version)2055+ return err2056+}modified:completions.go+1 added-1 removed
553 unmodified lines554 if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil &&555 len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {556 return true557 }558- if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil &&558+ if helpFlag := cmd.Flags().Lookup(helpFlagName); helpFlag != nil &&559 len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {560 return true561 }562 return false401 unmodified lines