Add support for --version flag (#584)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Nick Miyake · committed by Albert Nigmatzianov · parent 1be1d28 · Browse files · 2 files·+121 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+121 added−1 removed
- other:+121 added−1 removed
Provenance
- Commit
b1ec2ce- Tree
7a5404d- Author
Nick Miyake <nmiyake@users.noreply.github.com>- Committer
Albert Nigmatzianov <albertnigma@gmail.com>- Parent
1be1d28
2 files changed+121 added−1 removed
modified:command_test.go+57 added
841 unmodified lines842 843 checkStringContains(t, output, childCmd.Long)844 }845 846+func TestVersionFlagExecuted(t *testing.T) {847+ rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}848+849+ output, err := executeCommand(rootCmd, "--version", "arg1")850+ if err != nil {851+ t.Errorf("Unexpected error: %v", err)852+ }853+854+ checkStringContains(t, output, "root version 1.0.0")855+}856+857+func TestVersionTemplate(t *testing.T) {858+ rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}859+ rootCmd.SetVersionTemplate(`customized version: {{.Version}}`)860+861+ output, err := executeCommand(rootCmd, "--version", "arg1")862+ if err != nil {863+ t.Errorf("Unexpected error: %v", err)864+ }865+866+ checkStringContains(t, output, "customized version: 1.0.0")867+}868+869+func TestVersionFlagExecutedOnSubcommand(t *testing.T) {870+ rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}871+ rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})872+873+ output, err := executeCommand(rootCmd, "--version", "sub")874+ if err != nil {875+ t.Errorf("Unexpected error: %v", err)876+ }877+878+ checkStringContains(t, output, "root version 1.0.0")879+}880+881+func TestVersionFlagOnlyAddedToRoot(t *testing.T) {882+ rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}883+ rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})884+885+ _, err := executeCommand(rootCmd, "sub", "--version")886+ if err == nil {887+ t.Errorf("Expected error")888+ }889+890+ checkStringContains(t, err.Error(), "unknown flag: --version")891+}892+893+func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {894+ rootCmd := &Command{Use: "root", Run: emptyRun}895+896+ _, err := executeCommand(rootCmd, "--version")897+ if err == nil {898+ t.Errorf("Expected error")899+ }900+ checkStringContains(t, err.Error(), "unknown flag: --version")901+}902+903 func TestUsageIsNotPrintedTwice(t *testing.T) {904 var cmd = &Command{Use: "root"}905 var sub = &Command{Use: "sub"}906 cmd.AddCommand(sub)659 unmodified linesmodified:command.go+64 added-1 removed
73 unmodified lines74 // Annotations are key/value pairs that can be used by applications to identify or75 // group commands.76 Annotations map[string]string77 78+ // Version defines the version for this command. If this value is non-empty and the command does not79+ // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,80+ // will print content of the "Version" variable.81+ Version string82+83 // The *Run functions are executed in the following order:84 // * PersistentPreRun()85 // * PreRun()86 // * Run()94 unmodified lines181 helpFunc func(*Command, []string)182 // helpCommand is command with usage 'help'. If it's not defined by user,183 // cobra uses default help command.184 helpCommand *Command185+ // versionTemplate is the version template defined by user.186+ versionTemplate string187 }188 189 // SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden190 // particularly useful when testing.37 unmodified lines228 func (c *Command) SetHelpTemplate(s string) {229 c.helpTemplate = s230 }231 232+// SetVersionTemplate sets version template to be used. Application can use it to set custom template.233+func (c *Command) SetVersionTemplate(s string) {234+ c.versionTemplate = s235+}236+237 // SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.238 // The user should not have a cyclic dependency on commands.239 func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {240 c.Flags().SetNormalizeFunc(n)181 unmodified lines422 423 {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`424 }425 426+// VersionTemplate return version template for the command.427+func (c *Command) VersionTemplate() string {428+ if c.versionTemplate != "" {429+ return c.versionTemplate430+ }431+432+ if c.HasParent() {433+ return c.parent.VersionTemplate()434+ }435+ return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}436+`437+}438+439 func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {440 flag := fs.Lookup(name)441 if flag == nil {442 return false221 unmodified lines664 if len(c.Deprecated) > 0 {665 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)666 }667 643- // initialize help flag as the last point possible to allow for user668+ // initialize help and version flag at the last point possible to allow for user669 // overriding670 c.InitDefaultHelpFlag()671+ c.InitDefaultVersionFlag()672 673 err = c.ParseFlags(a)674 if err != nil {675 return c.FlagErrorFunc()(c, err)12 unmodified lines688 if helpVal || !c.Runnable() {689 return flag.ErrHelp690 }691 692+ // for back-compat, only add version flag behavior if version is defined693+ if c.Version != "" {694+ versionVal, err := c.Flags().GetBool("version")695+ if err != nil {696+ c.Println("\"version\" flag declared as non-bool. Please correct your code")697+ return err698+ }699+ if versionVal {700+ err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)701+ if err != nil {702+ c.Println(err)703+ }704+ return err705+ }706+ }707+708 c.preRun()709 710 argWoFlags := c.Flags().Args()711 if c.DisableFlagParsing {177 unmodified lines889 c.Flags().BoolP("help", "h", false, usage)890 }891 }892 893+// InitDefaultVersionFlag adds default version flag to c.894+// It is called automatically by executing the c.895+// If c already has a version flag, it will do nothing.896+// If c.Version is empty, it will do nothing.897+func (c *Command) InitDefaultVersionFlag() {898+ if c.Version == "" {899+ return900+ }901+902+ c.mergePersistentFlags()903+ if c.Flags().Lookup("version") == nil {904+ usage := "version for "905+ if c.Name() == "" {906+ usage += "this command"907+ } else {908+ usage += c.Name()909+ }910+ c.Flags().Bool("version", false, usage)911+ }912+}913+914 // InitDefaultHelpCmd adds default help command to c.915 // It is called automatically by executing the c or by calling help and usage.916 // If c already has help command or c has no subcommands, it will do nothing.917 func (c *Command) InitDefaultHelpCmd() {560 unmodified lines