当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > golang中命令行库cobra的使用方法示例

golang中命令行库cobra的使用方法示例

2018年08月18日  | 移动技术网IT编程  | 我要评论
简介 cobra既是一个用来创建强大的现代cli命令行的golang库,也是一个生成程序应用和命令行文件的程序。下面是cobra使用的一个演示: cobra

简介

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],执行如下指令:
[^1]:cobra.exe只能在gopath目录下执行

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详细研究一下。这里只是一个简单的使用入门介绍,如果有错误之处,敬请指出,谢谢~

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网