当前位置: 首页 > news >正文

golang中一个优雅的开发和使用命令行工具的库 cobra

在go语言的命令行工具开发中,我们可以使用go官方的flags来解析用户输入参数实现命令行的开发, 但是如果是有涉及二级命令这类的开发用官方的这个flags就比较麻烦了, 今天给大家介绍一个可用帮助我们快速优雅的开发和使用命令行工具的库cobra, 他可以很轻松的实现二级命令的开发, 还可以帮我们自动生成使用帮助文档, 轻松定义命令执行前后的钩子等。 废话不多说,看示例:

package mainimport ("os""fmt""github.com/spf13/cobra" // 安装依赖 go get -u github.com/spf13/cobra/cobra
)// 这个是根命令定义
var rootCmd = &cobra.Command{Use:   "hugo",// 这个就是你的自己定义的根命令Short: "命令的简短说明",Long: `这里详细的说明你的命令的作用,更多信息 http://dev.tekin.cn`,Run: func(cmd *cobra.Command, args []string) {// Do Stuff Here},
}//定义一个参数
var Verbose bool// 子命令定义 运行方法 go run main.go version 编译后 ./hugo version
var versionCmd = &cobra.Command{Use:   "version", // Use这里定义的就是命令的名称Short: "Print the version number of Hugo",Long:  `All software has versions. This is Hugo's`,Run: func(cmd *cobra.Command, args []string) { //这里是命令的执行方法fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")},PreRun: func(cmd *Command, args []string){ //这个在命令执行前执行},PostRun: func(cmd *Command, args []string){ //这个在命令执行后执行},// 还有其他钩子函数 
}// 命令执行方法
func Execute() {//给我们定义的命令绑定参数 可以给我们定义的任何命令绑定参数rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")//将我们 定义的子命令添加到根命令中 使用方式  ./根命令 子命令rootCmd.AddCommand(versionCmd)// 1表示没有参数 ,设置一个默认的命令,这在你有多个命令,需要再没有任何参数的情况下设置一个默认的命令时非常有用if len(os.Args) == 1 { rootCmd.SetArgs([]string{"version"})}// 执行命令 如果异常会返回错误信息if err := rootCmd.Execute(); err != nil {fmt.Println(err)os.Exit(1)}
}//入口函数
func main() {Execute()
}

怎么样,用这个库来开发命令行工具是不是很惬意?   

github仓库地址 https://github.com/tekintian/go-cli-cobra

自定义命令Command结构体定义参考

这个里面定义了所有我们可以使用的属性和“方法”(类型为函数的属性)

// Command is just that, a command for your application.
// E.g.  'go run ...' - 'run' is the command. Cobra requires
// you to define the usage and description as part of your command
// definition to ensure usability.
type Command struct {// Use is the one-line usage message.Use string// Aliases is an array of aliases that can be used instead of the first word in Use.Aliases []string// SuggestFor is an array of command names for which this command will be suggested -// similar to aliases but only suggests.SuggestFor []string// Short is the short description shown in the 'help' output.Short string// Long is the long message shown in the 'help <this-command>' output.Long string// Example is examples of how to use the command.Example string// ValidArgs is list of all valid non-flag arguments that are accepted in bash completionsValidArgs []string// Expected argumentsArgs PositionalArgs// ArgAliases is List of aliases for ValidArgs.// These are not suggested to the user in the bash completion,// but accepted if entered manually.ArgAliases []string// BashCompletionFunction is custom functions used by the bash autocompletion generator.BashCompletionFunction string// Deprecated defines, if this command is deprecated and should print this string when used.Deprecated string// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.Hidden bool// Annotations are key/value pairs that can be used by applications to identify or// group commands.Annotations map[string]string// Version defines the version for this command. If this value is non-empty and the command does not// define a "version" flag, a "version" boolean flag will be added to the command and, if specified,// will print content of the "Version" variable.Version string// The *Run functions are executed in the following order://   * PersistentPreRun()//   * PreRun()//   * Run()//   * PostRun()//   * PersistentPostRun()// All functions get the same args, the arguments after the command name.//// PersistentPreRun: children of this command will inherit and execute.PersistentPreRun func(cmd *Command, args []string)// PersistentPreRunE: PersistentPreRun but returns an error.PersistentPreRunE func(cmd *Command, args []string) error// PreRun: children of this command will not inherit.PreRun func(cmd *Command, args []string)// PreRunE: PreRun but returns an error.PreRunE func(cmd *Command, args []string) error// Run: Typically the actual work function. Most commands will only implement this.Run func(cmd *Command, args []string)// RunE: Run but returns an error.RunE func(cmd *Command, args []string) error// PostRun: run after the Run command.PostRun func(cmd *Command, args []string)// PostRunE: PostRun but returns an error.PostRunE func(cmd *Command, args []string) error// PersistentPostRun: children of this command will inherit and execute after PostRun.PersistentPostRun func(cmd *Command, args []string)// PersistentPostRunE: PersistentPostRun but returns an error.PersistentPostRunE func(cmd *Command, args []string) error// SilenceErrors is an option to quiet errors down stream.SilenceErrors bool// SilenceUsage is an option to silence usage when an error occurs.SilenceUsage bool// DisableFlagParsing disables the flag parsing.// If this is true all flags will be passed to the command as arguments.DisableFlagParsing bool// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")// will be printed by generating docs for this command.DisableAutoGenTag bool// DisableFlagsInUseLine will disable the addition of [flags] to the usage// line of a command when printing help or generating docsDisableFlagsInUseLine bool// DisableSuggestions disables the suggestions based on Levenshtein distance// that go along with 'unknown command' messages.DisableSuggestions bool// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.// Must be > 0.SuggestionsMinimumDistance int// TraverseChildren parses flags on all parents before executing child command.TraverseChildren bool//FParseErrWhitelist flag parse errors to be ignoredFParseErrWhitelist FParseErrWhitelist// commands is the list of commands supported by this program.commands []*Command// parent is a parent command for this command.parent *Command// Max lengths of commands' string lengths for use in padding.commandsMaxUseLen         intcommandsMaxCommandPathLen intcommandsMaxNameLen        int// commandsAreSorted defines, if command slice are sorted or not.commandsAreSorted bool// commandCalledAs is the name or alias value used to call this command.commandCalledAs struct {name   stringcalled bool}// args is actual args parsed from flags.args []string// flagErrorBuf contains all error messages from pflag.flagErrorBuf *bytes.Buffer// flags is full set of flags.flags *flag.FlagSet// pflags contains persistent flags.pflags *flag.FlagSet// lflags contains local flags.lflags *flag.FlagSet// iflags contains inherited flags.iflags *flag.FlagSet// parentsPflags is all persistent flags of cmd's parents.parentsPflags *flag.FlagSet// globNormFunc is the global normalization function// that we can use on every pflag set and children commandsglobNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName// usageFunc is usage func defined by user.usageFunc func(*Command) error// usageTemplate is usage template defined by user.usageTemplate string// flagErrorFunc is func defined by user and it's called when the parsing of// flags returns an error.flagErrorFunc func(*Command, error) error// helpTemplate is help template defined by user.helpTemplate string// helpFunc is help func defined by user.helpFunc func(*Command, []string)// helpCommand is command with usage 'help'. If it's not defined by user,// cobra uses default help command.helpCommand *Command// versionTemplate is the version template defined by user.versionTemplate string// inReader is a reader defined by the user that replaces stdininReader io.Reader// outWriter is a writer defined by the user that replaces stdoutoutWriter io.Writer// errWriter is a writer defined by the user that replaces stderrerrWriter io.Writer
}

相关文章:

  • CraftCMS ConditionsController.php 代码执行漏洞(CVE-2023-41892)
  • 【算法训练 day44 分割等和子集】
  • Mysql 插入或者更新 踩坑
  • QT系列教程(6) 几种标准对话框
  • ReactNative集成到已有iOS项目
  • 大模型日报2024-05-31
  • C++:vector的模拟实现
  • Maven 中的 classifier 属性用过没?
  • chrome 浏览器历史版本下载
  • 从openstack环境中将服务器镜像导出的简单办法
  • 分享 ASP.NET Core Web Api 中间件获取 Request Body 两个方法
  • html+CSS部分基础运用9
  • 大数据系统架构师的论文如何写
  • 【排序算法】选择排序
  • 浅谈线性化
  • [ JavaScript ] 数据结构与算法 —— 链表
  • Computed property XXX was assigned to but it has no setter
  • MySQL主从复制读写分离及奇怪的问题
  • Netty源码解析1-Buffer
  • OpenStack安装流程(juno版)- 添加网络服务(neutron)- controller节点
  • seaborn 安装成功 + ImportError: DLL load failed: 找不到指定的模块 问题解决
  • Vue源码解析(二)Vue的双向绑定讲解及实现
  • 多线程事务回滚
  • 分享一份非常强势的Android面试题
  • 前端
  • 让你成为前端,后端或全栈开发程序员的进阶指南,一门学到老的技术
  • 使用Maven插件构建SpringBoot项目,生成Docker镜像push到DockerHub上
  • 我与Jetbrains的这些年
  • 移动端 h5开发相关内容总结(三)
  • Nginx实现动静分离
  • 继 XDL 之后,阿里妈妈开源大规模分布式图表征学习框架 Euler ...
  • ​iOS实时查看App运行日志
  • #162 (Div. 2)
  • #DBA杂记1
  • #laravel 通过手动安装依赖PHPExcel#
  • $ is not function   和JQUERY 命名 冲突的解说 Jquer问题 (
  • (1)Nginx简介和安装教程
  • (10)STL算法之搜索(二) 二分查找
  • (1综述)从零开始的嵌入式图像图像处理(PI+QT+OpenCV)实战演练
  • (27)4.8 习题课
  • (Git) gitignore基础使用
  • (Redis使用系列) Springboot 实现Redis 同数据源动态切换db 八
  • (草履虫都可以看懂的)PyQt子窗口向主窗口传递参数,主窗口接收子窗口信号、参数。
  • (附源码)springboot家庭装修管理系统 毕业设计 613205
  • (免费领源码)Java#Springboot#mysql农产品销售管理系统47627-计算机毕业设计项目选题推荐
  • (未解决)macOS matplotlib 中文是方框
  • (一) storm的集群安装与配置
  • (一)、软硬件全开源智能手表,与手机互联,标配多表盘,功能丰富(ZSWatch-Zephyr)
  • (一)SpringBoot3---尚硅谷总结
  • (已更新)关于Visual Studio 2019安装时VS installer无法下载文件,进度条为0,显示网络有问题的解决办法
  • (转)PlayerPrefs在Windows下存到哪里去了?
  • ***微信公众号支付+微信H5支付+微信扫码支付+小程序支付+APP微信支付解决方案总结...
  • ./configure、make、make install 命令
  • .NET Core 控制台程序读 appsettings.json 、注依赖、配日志、设 IOptions
  • .Net Core中的内存缓存实现——Redis及MemoryCache(2个可选)方案的实现