From 14ceb07016ef12cf18386ba2c3a288ae9bd01e92 Mon Sep 17 00:00:00 2001 From: Benjamin Stewart Date: Mon, 10 Jun 2024 18:44:40 -0700 Subject: [PATCH] feat: add version flag to root command --- cmd/root.go | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/cmd/root.go b/cmd/root.go index 9e21668..d9b40da 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -21,6 +21,7 @@ import ( ) var cfgFile string +var version string // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ @@ -29,7 +30,15 @@ var rootCmd = &cobra.Command{ Long: ``, // Uncomment the following line if your bare application // has an action associated with it: - // Run: func(cmd *cobra.Command, args []string) { }, + Run: func(cmd *cobra.Command, args []string) { + flag, _ := cmd.Flags().GetBool("version") + if flag { + fmt.Println(version) + os.Exit(0) + } + + cmd.Help() + }, } // Execute adds all child commands to the root command and sets flags appropriately. @@ -45,6 +54,8 @@ func setDefaults() { viper.SetDefault("stewsPath", util.GetHomeDir()+"/.stews.json") viper.SetDefault("timeFormat", "2006-01-02 15:04:05") viper.SetDefault("allowFileCreation", false) + + version = "v1.2.1" } func addSubCommands() { @@ -58,6 +69,11 @@ func addSubCommands() { } +func flags() { + // -v, --version flag to print the version + rootCmd.PersistentFlags().BoolP("version", "v", false, "Print the version") +} + func init() { cobra.OnInitialize(initConfig) @@ -73,6 +89,8 @@ func init() { // add sub commands addSubCommands() + + flags() } // initConfig reads in config file and ENV variables if set.