Skip to content
Myr

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

authored by Alessandro Arzilli · committed by GitHub · parent 09d5664 · Browse files · 6 files+365 added−61 removed
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

6 files+365 added−61 removed

modified:site/content/user_guide.md+10 added
552 unmodified lines
553```554555The latter two will also apply to any children commands.556557Note that templates specified with `SetHelpTemplate` are evaluated using558`text/template` which can increase the size of the compiled executable.559560## Usage Message561562When the user provides an invalid flag or invalid command, Cobra responds by563showing the user the 'usage'.
24 unmodified lines
588Use "cobra [command] --help" for more information about a command.589```590591### Defining your own usage592593You can provide your own usage function or template for Cobra to use.594Like help, the function and template are overridable through public methods:595596```go597cmd.SetUsageFunc(f func(*Command) error)598cmd.SetUsageTemplate(s string)599```600601Note that templates specified with `SetUsageTemplate` are evaluated using602`text/template` which can increase the size of the compiled executable.603604## Version Flag605606Cobra adds a top-level '--version' flag if the Version field is set on the root command.607Running an application with the '--version' flag will print the version to stdout using608the version template. The template can be customized using the609`cmd.SetVersionTemplate(s string)` function.610611Note that templates specified with `SetVersionTemplate` are evaluated using612`text/template` which can increase the size of the compiled executable.613614## Error Message Prefix615616Cobra prints an error message when receiving a non-nil error value.617The default error message is `Error: <error contents>`.
202 unmodified lines
modified:cobra_test.go+77 added
13 unmodified lines
1415package cobra1617import (18 "os"19 "os/exec"20 "path/filepath"21 "runtime"22 "strings"23 "testing"24 "text/template"25)26
199 unmodified lines
226 }227 })228 }229}230231// 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/1956245func TestDeadcodeElimination(t *testing.T) {246 if runtime.GOOS == "windows" {247 t.Skip("go tool nm fails on windows")248 }249250 // 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 main260261import (262 "fmt"263 "os"264265 "github.com/spf13/cobra"266)267268var 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}278279func 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 lines
175 formattedString := fmt.Sprintf("%%-%ds", padding)176 return fmt.Sprintf(formattedString, s)177}178179func tmpl(text string) *tmplFunc {180 return &tmplFunc{179// tmpl executes the given template text on data, writing the result to w.180func 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}190191// ld compares two strings and returns the levenshtein distance between them.192func ld(s, t string, ignoreCase bool) int {
54 unmodified lines
modified:command_test.go+58 added
1016 unmodified lines
1017 t.Errorf("Expected to contain %q, got %q", expected, got)1018 }1019}10201021func TestSetHelpTemplate(t *testing.T) {1022 rootCmd := &Command{Use: "root", Run: emptyRun}1023 childCmd := &Command{Use: "child", Run: emptyRun}1024 rootCmd.AddCommand(childCmd)10251026 rootCmd.SetHelpTemplate("WORKS {{.UseLine}}")10271028 // 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 }10331034 expected := "WORKS " + rootCmd.UseLine()1035 if got != expected {1036 t.Errorf("Expected %q, got %q", expected, got)1037 }10381039 // 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 }10451046 expected = "WORKS " + childCmd.UseLine()1047 if got != expected {1048 t.Errorf("Expected %q, got %q", expected, got)1049 }1050}10511052func TestHelpFlagExecuted(t *testing.T) {1053 rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}10541055 output, err := executeCommand(rootCmd, "--help")
57 unmodified lines
11131114 checkStringContains(t, output, childCmd.Long)1115}11161117func TestSetUsageTemplate(t *testing.T) {1118 rootCmd := &Command{Use: "root", Run: emptyRun}1119 childCmd := &Command{Use: "child", Run: emptyRun}1120 rootCmd.AddCommand(childCmd)11211122 rootCmd.SetUsageTemplate("WORKS {{.UseLine}}")11231124 // 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 }11291130 expected := "WORKS " + rootCmd.UseLine()1131 checkStringContains(t, got, expected)11321133 // 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 }11391140 expected = "WORKS " + childCmd.UseLine()1141 checkStringContains(t, got, expected)1142}11431144func TestVersionFlagExecuted(t *testing.T) {1145 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}11461147 output, err := executeCommand(rootCmd, "--version", "arg1")
1765 unmodified lines
modified:command.go+209 added-54 removed
30 unmodified lines
3132const (33 FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"34 CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"3536 helpFlagName = "help"37 helpCommandName = "help"38)3940// FParseErrWhitelist configures Flag parse errors to be ignored41type FParseErrWhitelist flag.ParseErrorsWhitelist
127 unmodified lines
169170 // 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 lines
187 // completionCommandGroupID is the group id for the completion command188 completionCommandGroupID string189190 // versionTemplate is the version template defined by user.188 versionTemplate string191 versionTemplate *tmplFunc192193 // errPrefix is the error message prefix defined by user.194 errPrefix string195
118 unmodified lines
314}315316// SetUsageTemplate sets usage template. Can be defined by Application.317func (c *Command) SetUsageTemplate(s string) {315 c.usageTemplate = s318 c.usageTemplate = tmpl(s)319}320321// SetFlagErrorFunc sets a function to generate an error when flag parsing322// fails.
27 unmodified lines
350}351352// SetHelpTemplate sets help template to be used. Application can use it to set custom template.353func (c *Command) SetHelpTemplate(s string) {351 c.helpTemplate = s354 c.helpTemplate = tmpl(s)355}356357// SetVersionTemplate sets version template to be used. Application can use it to set custom template.358func (c *Command) SetVersionTemplate(s string) {356 c.versionTemplate = s359 c.versionTemplate = tmpl(s)360}361362// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.363func (c *Command) SetErrPrefix(s string) {
72 unmodified lines
436 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}448449// getUsageTemplateFunc returns the usage template function for the command450// going up the command tree if necessary.451func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error {452 if c.usageTemplate != nil {453 return c.usageTemplate.fn454 }455456 if c.HasParent() {457 return c.parent.getUsageTemplateFunc()458 }459 return defaultUsageFunc460}461462// 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.465func (c *Command) Usage() error {
10 unmodified lines
476 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}489490// getHelpTemplateFunc returns the help template function for the command491// going up the command tree if necessary.492func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error {493 if c.helpTemplate != nil {494 return c.helpTemplate.fn495 }496497 if c.HasParent() {498 return c.parent.getHelpTemplateFunc()499 }500501 return defaultHelpFunc502}503504// 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.507func (c *Command) Help() error {
66 unmodified lines
574 return c.parent.commandsMaxNameLen575}576577// UsageTemplate returns usage template for the command.578// This function is kept for backwards-compatibility reasons.579func (c *Command) UsageTemplate() string {547 if c.usageTemplate != "" {548 return c.usageTemplate580 if c.usageTemplate != nil {581 return c.usageTemplate.tmpl582 }583584 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}}557558Aliases:559 {{.NameAndAliases}}{{end}}{{if .HasExample}}560561Examples:562{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}563564Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}565 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}566567{{.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}}569570Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}571 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}572573Flags:574{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}575576Global Flags:577{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}578579Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}580 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}581582Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}583`587 return defaultUsageTemplate588}589590// HelpTemplate return help template for the command.591// This function is kept for backwards-compatibility reasons.592func (c *Command) HelpTemplate() string {588 if c.helpTemplate != "" {589 return c.helpTemplate593 if c.helpTemplate != nil {594 return c.helpTemplate.tmpl595 }596597 if c.HasParent() {598 return c.parent.HelpTemplate()599 }595 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}596597{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`600 return defaultHelpTemplate601}602603// VersionTemplate return version template for the command.604// This function is kept for backwards-compatibility reasons.605func (c *Command) VersionTemplate() string {602 if c.versionTemplate != "" {603 return c.versionTemplate606 if c.versionTemplate != nil {607 return c.versionTemplate.tmpl608 }609610 if c.HasParent() {611 return c.parent.VersionTemplate()612 }609 return `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}610`613 return defaultVersionTemplate614}615616// getVersionTemplateFunc returns the version template function for the command617// going up the command tree if necessary.618func (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error {619 if c.versionTemplate != nil {620 return c.versionTemplate.fn621 }622623 if c.HasParent() {624 return c.parent.getVersionTemplateFunc()625 }626 return defaultVersionFunc627}628629// ErrPrefix return error message prefix for the command630func (c *Command) ErrPrefix() string {631 if c.errPrefix != "" {632 return c.errPrefix
276 unmodified lines
909 }910911 // 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 lines
929 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 err
267 unmodified lines
1206// 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.1208func (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}12221223// InitDefaultVersionFlag adds default version flag to c.
691 unmodified lines
1915 }19161917 return s == t1918}19191920// tmplFunc holds a template and a function that will execute said template.1921type tmplFunc struct {1922 tmpl string1923 fn func(io.Writer, interface{}) error1924}19251926var defaultUsageTemplate = `Usage:{{if .Runnable}}1927 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}1928 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}19291930Aliases:1931 {{.NameAndAliases}}{{end}}{{if .HasExample}}19321933Examples:1934{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}19351936Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}1937 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}19381939{{.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}}19411942Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}1943 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}19441945Flags:1946{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}19471948Global Flags:1949{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}19501951Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}1952 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}19531954Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}1955`19561957// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync.1958func 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}20252026var defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}20272028{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`20292030// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync.2031func 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}20472048var defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}2049`20502051// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync.2052func 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 lines
554 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 false
401 unmodified lines