Skip to content
Myr

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

2 files+121 added−1 removed

modified:command_test.go+57 added
841 unmodified lines
842843 checkStringContains(t, output, childCmd.Long)844}845846func TestVersionFlagExecuted(t *testing.T) {847 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}848849 output, err := executeCommand(rootCmd, "--version", "arg1")850 if err != nil {851 t.Errorf("Unexpected error: %v", err)852 }853854 checkStringContains(t, output, "root version 1.0.0")855}856857func TestVersionTemplate(t *testing.T) {858 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}859 rootCmd.SetVersionTemplate(`customized version: {{.Version}}`)860861 output, err := executeCommand(rootCmd, "--version", "arg1")862 if err != nil {863 t.Errorf("Unexpected error: %v", err)864 }865866 checkStringContains(t, output, "customized version: 1.0.0")867}868869func TestVersionFlagExecutedOnSubcommand(t *testing.T) {870 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}871 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})872873 output, err := executeCommand(rootCmd, "--version", "sub")874 if err != nil {875 t.Errorf("Unexpected error: %v", err)876 }877878 checkStringContains(t, output, "root version 1.0.0")879}880881func TestVersionFlagOnlyAddedToRoot(t *testing.T) {882 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}883 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})884885 _, err := executeCommand(rootCmd, "sub", "--version")886 if err == nil {887 t.Errorf("Expected error")888 }889890 checkStringContains(t, err.Error(), "unknown flag: --version")891}892893func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {894 rootCmd := &Command{Use: "root", Run: emptyRun}895896 _, err := executeCommand(rootCmd, "--version")897 if err == nil {898 t.Errorf("Expected error")899 }900 checkStringContains(t, err.Error(), "unknown flag: --version")901}902903func TestUsageIsNotPrintedTwice(t *testing.T) {904 var cmd = &Command{Use: "root"}905 var sub = &Command{Use: "sub"}906 cmd.AddCommand(sub)
659 unmodified lines
modified:command.go+64 added-1 removed
73 unmodified lines
74 // Annotations are key/value pairs that can be used by applications to identify or75 // group commands.76 Annotations map[string]string7778 // 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 string8283 // The *Run functions are executed in the following order:84 // * PersistentPreRun()85 // * PreRun()86 // * Run()
94 unmodified lines
181 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}188189// 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 lines
228func (c *Command) SetHelpTemplate(s string) {229 c.helpTemplate = s230}231232// SetVersionTemplate sets version template to be used. Application can use it to set custom template.233func (c *Command) SetVersionTemplate(s string) {234 c.versionTemplate = s235}236237// 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.239func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {240 c.Flags().SetNormalizeFunc(n)
181 unmodified lines
422423{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`424}425426// VersionTemplate return version template for the command.427func (c *Command) VersionTemplate() string {428 if c.versionTemplate != "" {429 return c.versionTemplate430 }431432 if c.HasParent() {433 return c.parent.VersionTemplate()434 }435 return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}436`437}438439func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {440 flag := fs.Lookup(name)441 if flag == nil {442 return false
221 unmodified lines
664 if len(c.Deprecated) > 0 {665 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)666 }667643 // 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()672673 err = c.ParseFlags(a)674 if err != nil {675 return c.FlagErrorFunc()(c, err)
12 unmodified lines
688 if helpVal || !c.Runnable() {689 return flag.ErrHelp690 }691692 // 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 }707708 c.preRun()709710 argWoFlags := c.Flags().Args()711 if c.DisableFlagParsing {
177 unmodified lines
889 c.Flags().BoolP("help", "h", false, usage)890 }891}892893// 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.897func (c *Command) InitDefaultVersionFlag() {898 if c.Version == "" {899 return900 }901902 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}913914// 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.917func (c *Command) InitDefaultHelpCmd() {
560 unmodified lines