内容简介:最近看了几个开源项目,都是基于cobra创建的项目,如果对cobra不了解的话,对整个项目的代码阅读难度都相应的要增加。首先,cobra是什么?cobra既是一个用来创建强大的现代CLI命令行的golang库,也是一个生成程序应用和命令行文件的程序。
最近看了几个开源项目,都是基于cobra创建的项目,如果对cobra不了解的话,对整个项目的代码阅读难度都相应的要增加。
首先,cobra是什么?
cobra既是一个用来创建强大的现代CLI命令行的golang库,也是一个生成程序应用和命令行文件的程序。
Cobra提供的功能
1、简易的子命令行模式,如app server、app get等
2、完全兼容posix命令行模式
3、支持全局、局部、串联flags
4、使用cobra很容易生成应用程序和命令,使用cobra create和cobra cmdname
5、如果命令输入有错误,将提供只能建议,如app gt,将提示gt不存在,是否是app get
6、自动生成详细的help信息,如app help
7、自动识别-h,--help和帮助flag
8、自动生成应用程序在bash下命令自动改完成功能
9、自动生成应用程序的man手册
10、命令行别名
11、自定义help和usage信息
12、可选的紧密集成的viper apps
上面的描述稍微有点抽象,下面结合例子讲下cobra如何做的。
首先,通过go get下载cobra
go get -v github.com/spf13/cobra/cobra
然后安装go install。
至此cobra工具安装完成。
在命令行下运行下cobra命令
看到上述信息,说明cobra安装成功。接下来就可以使用cobra了。
假设我们现在要开发一个基于CLI的命令程序,名字的demo。如下图操作:
创建初始化程序
然后就会在gopath目录下创建一个cobra_demo目录。其内部的目录结构如下:
▾ cobra_demo
▾ cmd/
root.go
main.go
如果此时cobra_demo程序没有subcommands,那么cobra生成应用程序的操作就结束了。
功能基本在root.go文件中,内容如下:
var rootCmd = &cobra.Command{
Use:"demo",
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.`,
// Run: func(cmd *cobra.Command, args []string) { },
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
rootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
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 ".demo" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".demo")
}
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())
}
}
上述的代码是没有经过任何修改的。可以直接运行下看看。下面将上面的代码进行下简单的修改,将 &cobra.Command{}中注释了的代码放开,修改如下:
增加相应的Show方法:
然后运行如下:
至此,cobra的简单介绍完了。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Web Data Mining
Bing Liu / Springer / 2006-12-28 / USD 59.95
Web mining aims to discover useful information and knowledge from the Web hyperlink structure, page contents, and usage data. Although Web mining uses many conventional data mining techniques, it is n......一起来看看 《Web Data Mining》 这本书的介绍吧!