// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "cobrademo", Short: "A brief description of your application", Long: `A longer description that spans multiple lines and likely contains examples and usage of using your application. For example: Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, // Uncomment the following line if your bare application // has an action associated with it: // Run: func(cmd *cobra.Command, args []string) { }, }
// Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. funcExecute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }
funcinit() { cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings. // Cobra supports persistent flags, which, if defined here, // will be global for your application.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobrademo.yaml)")
// Cobra also supports local flags, which will only run // when this action is called directly. rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }
// initConfig reads in config file and ENV variables if set. funcinitConfig() { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) }
// Search config in home directory with name ".cobrademo" (without extension). viper.AddConfigPath(home) viper.SetConfigName(".cobrademo") }
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } }
编译程序并运行,可以看到:
1 2 3 4 5 6 7
$ ./main A longer description that spans multiple lines and likely contains examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.
下面依次分析创建命令的每个部分。
创建 rootCmd
Cobra 不需要额外的创建特殊的构造函数,只需要简单的创建你自己的命令。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var rootCmd = &cobra.Command{ Use: "hugo", Short: "Hugo is a very fast static site generator", Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at http://hugo.spf13.com`, Run: func(cmd *cobra.Command, args []string) { // Do Stuff Here }, }
var ( // Used for flags. cfgFile string userLicense string
rootCmd = &cobra.Command{ Use: "cobra", Short: "A generator for Cobra based Applications", Long: `Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, } )
var versionCmd = &cobra.Command{ Use: "version", Short: "Print the version number of crddemo", Long: `All software has versions. This is crddemo's`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("cobrademo version is v0.1") }, }
// imageCmd represents the image command var imageCmd = &cobra.Command{ Use: "image [argument]", Short: "Print images information", Long: "Print all images information", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { for i := 0; i < echoTimes; i++ { fmt.Println("Echo: " + strings.Join(args, " ")) } }, }
funcinit() { rootCmd.AddCommand(imageCmd)
// Here you will define your flags and configuration settings.
// Cobra supports local flags which will only run when this command // is called directly, e.g.: imageCmd.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") }
╭─ ~/go/src/github.com/SimpCosm/cobrademo $ ╰─ ./main image Error: requires at least 1 arg(s), only received 0 Usage: cobrademo image [argument] [flags]
Flags: -h, --helphelpfor image -t, --times int times to echo the input (default 1)
Global Flags: --config string config file (default is $HOME/.cobrademo.yaml)
╭─ ~/go/src/github.com/SimpCosm/cobrademo $ ╰─ ./main --help long description shows how to use cobra package
Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.
Usage: cobrademo [flags] cobrademo [command]
Available Commands: help Help about any command image Print images information version Print the version number of crddemo
Flags: --config string config file (default is $HOME/.cobrademo.yaml) -h, --helphelpfor cobrademo -t, --toggle Help message for toggle
Use "cobrademo [command] --help"for more information about a command.