简介

Cobra既是一个用来创建强大的现代CLI命令行的golang库,也是一个生成程序应用和命令行文件的程序。下面是Cobra使用的一个演示:

Cobra提供的功能

  • 简易的子命令行模式,如 app server, app fetch等等
  • 完全兼容posix命令行模式
  • 嵌套子命令subcommand
  • 支持全局,局部,串联flags
  • 使用Cobra很容易的生成应用程序和命令,使用cobra create appname和cobra add cmdname
  • 如果命令输入错误,将提供智能建议,如 app srver,将提示srver没有,是否是app server
  • 自动生成commands和flags的帮助信息
  • 自动生成详细的help信息,如app help
  • 自动识别-h,--help帮助flag
  • 自动生成应用程序在bash下命令自动完成功能
  • 自动生成应用程序的man手册
  • 命令行别名
  • 自定义help和usage信息
  • 可选的紧密集成的viper apps

如何使用

上面所有列出的功能我没有一一去使用,下面我来简单介绍一下如何使用Cobra,基本能够满足一般命令行程序的需求,如果需要更多功能,可以研究一下源码github

安装cobra

Cobra是非常容易使用的,使用go get来安装最新版本的库。当然这个库还是相对比较大的,可能需要安装它可能需要相当长的时间,这取决于你的速网。安装完成后,打开GOPATH目录,bin目录下应该有已经编译好的cobra.exe程序,当然你也可以使用源代码自己生成一个最新的cobra程序。

> go get -v github.com/spf13/cobra/cobra

使用cobra生成应用程序

假设现在我们要开发一个基于CLIs的命令程序,名字为demo。首先打开CMD,切换到GOPATH的src目录下[1],执行如下指令:

src> ..\bin\cobra.exe init demo
Your Cobra application is ready at
C:\Users\liubo5\Desktop\transcoding_tool\src\demo
Give it a try by going there and running `go run main.go`
Add commands to it by running `cobra add [cmdname]`

在src目录下会生成一个demo的文件夹,如下:

▾ demo
▾ cmd/
root.go
main.go

如果你的demo程序没有subcommands,那么cobra生成应用程序的操作就结束了。

如何实现没有子命令的CLIs程序

接下来就是可以继续demo的功能设计了。例如我在demo下面新建一个包,名称为imp。如下:

▾ demo
▾ cmd/
root.go
▾ imp/
imp.go
imp_test.go
main.go

imp.go文件的代码如下:

package imp

import(
"fmt"
) func Show(name string, age int) {
fmt.Printf("My Name is %s, My age is %d\n", name, age)
}

demo程序成命令行接收两个参数name和age,然后打印出来。打开cobra自动生成的main.go文件查看:

// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License. package main import "demo/cmd" func main() {
cmd.Execute()
}

可以看出main函数执行cmd包,所以我们只需要在cmd包内调用imp包就能实现demo程序的需求。接着打开root.go文件查看:

// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License. package cmd import (
"fmt"
"os" "github.com/spf13/cobra"
"github.com/spf13/viper"
) var cfgFile string // RootCmd represents the base command when called without any subcommands
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.`,
// 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 sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
} func init() {
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/.demo.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.
func initConfig() {
if cfgFile != "" { // enable ability to specify config file via flag
viper.SetConfigFile(cfgFile)
} viper.SetConfigName(".demo") // name of config file (without extension)
viper.AddConfigPath("$HOME") // adding home directory as first search path
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())
}
}

从源代码来看cmd包进行了一些初始化操作并提供了Execute接口。十分简单,其中viper是cobra集成的配置文件读取的库,这里不需要使用,我们可以注释掉(不注释可能生成的应用程序很大约10M,这里没哟用到最好是注释掉)。cobra的所有命令都是通过cobra.Command这个结构体实现的。为了实现demo功能,显然我们需要修改RootCmd。修改后的代码如下:

// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License. package cmd import (
"fmt"
"os" "github.com/spf13/cobra"
// "github.com/spf13/viper"
"demo/imp"
) //var cfgFile string
var name string
var age int // RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "demo",
Short: "A test demo",
Long: `Demo is a test appcation for print things`,
// Uncomment the following line if your bare application
// has an action associated with it:
Run: func(cmd *cobra.Command, args []string) {
if len(name) == 0 {
cmd.Help()
return
}
imp.Show(name, age)
},
} // Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
} func init() {
// 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/.demo.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")
RootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
RootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")
} // initConfig reads in config file and ENV variables if set.
//func initConfig() {
// if cfgFile != "" { // enable ability to specify config file via flag
// viper.SetConfigFile(cfgFile)
// } // viper.SetConfigName(".demo") // name of config file (without extension)
// viper.AddConfigPath("$HOME") // adding home directory as first search path
// 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())
// }
//}

到此demo的功能已经实现了,我们编译运行一下看看实际效果:

>demo.exe
Demo is a test appcation for print things Usage:
demo [flags] Flags:
-a, --age int person's age
-h, --help help for demo
-n, --name string person's name
>demo -n borey --age 26
My Name is borey, My age is 26

如何实现带有子命令的CLIs程序

在执行cobra.exe init demo之后,继续使用cobra为demo添加子命令test:

src\demo>..\..\bin\cobra add test
test created at C:\Users\liubo5\Desktop\transcoding_tool\src\demo\cmd\test.go

在src目录下demo的文件夹下生成了一个cmd\test.go文件,如下:

▾ demo
▾ cmd/
root.go
test.go
main.go

接下来的操作就和上面修改root.go文件一样去配置test子命令。效果如下:

src\demo>demo
Demo is a test appcation for print things Usage:
demo [flags]
demo [command] Available Commands:
test A brief description of your command Flags:
-a, --age int person's age
-h, --help help for demo
-n, --name string person's name Use "demo [command] --help" for more information about a command.

可以看出demo既支持直接使用标记flag,又能使用子命令

src\demo>demo test -h
A longer description that spans multiple lines and likely contains examples
and usage of using your command. 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. Usage:
demo test [flags]

调用test命令输出信息,这里没有对默认信息进行修改。

src\demo>demo tst
Error: unknown command "tst" for "demo" Did you mean this?
test Run 'demo --help' for usage.
unknown command "tst" for "demo" Did you mean this?
test

这是错误命令提示功能

OVER

Cobra的使用就介绍到这里,更新细节可去github详细研究一下。这里只是一个简单的使用入门介绍,如果有错误之处,敬请指出,谢谢~


  1. cobra.exe只能在GOPATH目录下执行 ↩︎

golang命令行库cobra的使用的更多相关文章

  1. golang命令行库cobra使用

    github地址:https://github.com/spf13/cobra Cobra功能 简单子命令cli 如  kubectl verion    kubectl get 自动识别-h,--h ...

  2. Go命令行库Cobra的核心文件root.go

    因为docker及Kubernetes都在用cobra库,所以记录一下. 自定义的地方,高红标出. root.go /* Copyright © 2019 NAME HERE <EMAIL AD ...

  3. Google 开源的 Python 命令行库:深入 fire(一)

    作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

  4. Google 开源的 Python 命令行库:fire 实现 git 命令

    作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

  5. golang 命令行cobra妙用

    为什么使用命令行 大型项目中少不了数据升级,如果采用web服务,一来不够安全,二来数据量大的时候也会出超时的情况.这时使用命令行是比较合适的方式了. 命令行中的MVC web项目一般采用MVC模式,对 ...

  6. gocommand:一个跨平台的golang命令行执行package

    最近在做一个项目的时候,需要使用golang来调用操作系统中的命令行,来执行shell命令或者直接调用第三方程序,这其中自然就用到了golang自带的exec.Command. 但是如果直接使用原生e ...

  7. go语言的命令行库

    命令行应用通常很小,程序猿们也不喜欢为它编写注释.所以一些额外的工作,如解析参数有个合理的库来帮忙做就好了.https://github.com/urfave/cli 这个项目因此而生.安装:go g ...

  8. 大家都说好用的 Python 命令行库:click

    作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

  9. Google 开源的 Python 命令行库:初探 fire

    作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

随机推荐

  1. 利用PowerUpSQL攻击SQL Server实例

    这篇博客简述如何快速识别被第三方应用使用的SQL Server实例,该第三方软件用PowerUpSQL配置默认用户/密码配置.虽然我曾经多次提到过这一话题,但是我认为值得为这一主题写一篇简短的博客,帮 ...

  2. 浅谈.Net异步编程的前世今生----APM篇

    前言 在.Net程序开发过程中,我们经常会遇到如下场景: 编写WinForm程序客户端,需要查询数据库获取数据,于是我们根据需求写好了代码后,点击查询,发现界面卡死,无法响应.经过调试,发现查询数据库 ...

  3. 钉钉开发获取APPKEY, APPSECRET, CorpId和SSOSecret

    首先用自己的钉钉账号注册一个企业: https://oa.dingtalk.com/index.htm 一.获取应用APPKEY及APPSECRET方法: 1.登录钉钉开放平台创建应用: https: ...

  4. Spark学习之数据读取与保存总结(二)

    8.Hadoop输入输出格式 除了 Spark 封装的格式之外,也可以与任何 Hadoop 支持的格式交互.Spark 支持新旧两套Hadoop 文件 API,提供了很大的灵活性. 要使用新版的 Ha ...

  5. 你真的了解ASP.NET Core 部署模型吗?

    ----------------------------   以下内容针对 ASP.NET Core2.1,2.2出现IIS进程内寄宿 暂不展开讨论-------------------------- ...

  6. DataFrameNaFunctions无fill方法

    当我使用 spark2.1 ,为了填补 dataframe 里面的 null 值转换为 0 ,代码如下所示: dataframe.na.fill(0) 出现如下错误 Spark version 2.1 ...

  7. socketserver实现并发

    socketserver实现并发原理:给每一个前来链接的客户端开启一个线程执行通信.也就是给每一个连接“配备”了一个管家. 下面用一个简单的示例来演示socketserver实现并发(一个服务端,两个 ...

  8. 1.JAVA-Hello World

    1.Java开发介绍 J2SE:Java 2 Platform Standard Edition(2005年之后更名为JAVA SE). 包含构成Java语言核心的类.比如:数据库连接.接口定义.数据 ...

  9. Yii2设计模式——静态工厂模式

    应用举例 yii\db\ActiveRecord //获取 Connection 实例 public static function getDb() { return Yii::$app->ge ...

  10. Odoo : 门店订货及在线签名免费开源方案

    引言 Odoo是欧洲开发的,世界排名第一的开源免费ERP系统.该系统从2002开始研发,经过十几年的发展,去年下半年发布了12.0版.该软件因为免费下载,源代码开放,吸引了世界范围很多人参与使用及开发 ...