Golang Command line library Cobra usage

Source: Internet
Author: User
Tags configuration settings
This is a creation in Article, where the information may have evolved or changed.

Brief introduction

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

Features provided by Cobra

    • Easy sub-command line mode, such as App server, app fetch, etc.
    • Fully compatible with POSIX command-line mode
    • Nested subcommand subcommand
    • Support Global, local, inline flags
    • Use Cobra to easily build applications and commands, using the Cobra create appname and COBRA add CmdName
    • If the command input error, will provide smart suggestions, such as app Srver, will prompt Srver No, is the app server
    • Automatic generation of commands and flags help information
    • Automatically generate detailed help information, such as app
    • Auto-Identify-H,--HELP help flag
    • Auto-build application under bash Command Auto-complete function
    • Manual for automatic generation of applications
    • Command line aliases
    • customizing Help and usage information
    • Optional tightly integrated Viper apps

How to use

All the features listed above I do not use each, the following I will briefly describe how to use the Cobra, basically to meet the General Command line program requirements, if more functions are needed, you can study the source GitHub.

Installing Cobra

Cobra is very easy to use and uses go get to install the latest version of the library. Of course, this library is still relatively large, it may take a long time to install it, depending on your speed network. After the installation is complete, open the Gopath directory, the bin directory should have a compiled Cobra.exe program, of course you can use the source code to generate a new Cobra program yourself.

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

Using the Cobra Build application

Suppose now we are going to develop a command program based on CLIs, named demo. First open cmd, switch to Gopath's SRC directory [^1], execute the following command:
[^1]:cobra.exe can only be executed in the Gopath directory

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

A demo folder will be generated under the SRC directory, as follows:

▾ demo    ▾ cmd/        root.go    main.go

If your demo program is not subcommands, then the operation of the Cobra build application is over.

How to implement a CLIs program without subcommands

The next step is to continue with the demo's feature design. For example, I create a new package under the demo named Imp. As follows:

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

The code for the Imp.go file is as follows:

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

The demo program receives two parameters, name and age, into the command line and prints them out. Open the Cobra Auto-generated main.go file to view:

// 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 mainimport "demo/cmd"func main() {    cmd.Execute()}

You can see that the main function executes the CMD package, so we only need to call the IMP package within the CMD package to achieve the demo program requirements. Then open the Root.go file to view:

Copyright: Here <email address>////Licensed under the Apache License, Version 2.0 (the "License");//Y OU May is not use this file except in compliance with the license.//obtain a copy of the License at////http://w ww.apache.org/licenses/license-2.0////unless required by applicable law or agreed to in writing, software//distributed u NDEr the License is distributed on a "as is" basis,//without warranties OR CONDITIONS of any KIND, either express or Imp lied.//See the License for the specific language governing permissions and//limitations under the License.package cmdimp  ORT ("FMT" "OS" "Github.com/spf13/cobra" "Github.com/spf13/viper") var cfgfile string//Rootcmd represents the Base command when called without any subcommandsvar Rootcmd = &cobra. command{use: "Demo", Short: "A brief description of your application", Long: ' A longer description that spans Multiple lines and likely containsexamples and usage of using your application. For Example:cobra are a CLI library for Go empowers applications. This application are a tool to generate the needed FilesTo quickly create a Cobra application. ',//uncomment the following Line if your bare application//have 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 CA Lled by Main.main (). It is 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'll define your flags and configuration settings.    Cobra supports persistent Flags, which, if defined here,//would be is global for your application. Rootcmd.persistentflags (). Stringvar (&cfgfile, "config", "", "Config file (default is $HOME/.demo.yaml)")//Cobra also supports local flags, Which would only run//if this actionis called directly. Rootcmd.flags (). Boolp ("Toggle", "T", false, "help message for toggle")}//initconfig reads in config file and ENV variables if set.func in Itconfig () {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 this match//If a config file is found, read it in. If err: = Viper. Readinconfig (); Err = = Nil {fmt. Println ("Using config file:", Viper. Configfileused ())}}

The

looks at the cmd package from the source code for some initialization operations and provides the Execute interface. Quite simply, where Viper is a library read by the Cobra integrated profile, which is not needed here, we can comment out (without commenting the potentially generated application is about 10M, here is no use of the best comment out). All of Cobra's commands are implemented by Cobra.command this structure. To achieve the demo function, obviously we need to modify the rootcmd. The modified code is as follows:

Copyright: Here <email address>////Licensed under the Apache License, Version 2.0 (the "License");//Y OU May is not use this file except in compliance with the license.//obtain a copy of the License at////http://w ww.apache.org/licenses/license-2.0////unless required by applicable law or agreed to in writing, software//distributed u NDEr the License is distributed on a "as is" basis,//without warranties OR CONDITIONS of any KIND, either express or Imp lied.//See the License for the specific language governing permissions and//limitations under the License.package cmdimp ORT ("FMT" "OS" "Github.com/spf13/cobra"//"Github.com/spf13/viper" "Demo/imp")//var cfgfile stringvar N Ame Stringvar Age int//rootcmd represents the base command, called without any subcommandsvar Rootcmd = &cobra.  command{use: "Demo", Short: "A Test Demo", Long: ' demo was A test appcation for print things ',//Uncomment The following line if youR Bare application//has a 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 is 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'll define your flags and configuration settings.    Cobra supports persistent Flags, which, if defined here,//would be is global for your application. Rootcmd.persistentflags (). Stringvar (&cfgfile, "config", "", "Config file (default is $HOME/.demo.yaml)")//Cobra also supports local flags,    Which would only run//if 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 Initco Nfig () {//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 the match////If a config file is found, read it in.//If err : = Viper. Readinconfig (); Err = = Nil {//FMT. Println ("Using config file:", Viper. Configfileused ())//}//}

To this demo function has been implemented, we compile and run a look at the actual effect:

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

How to implement a CLIs program with sub-commands

After execution cobra.exe init demo , continue to use Cobra to add the subcommand test to the demo:

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

In the SRC directory under the Demo folder generated a Cmd\test.go file, as follows:

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

The next action is to configure the test subcommand as in the above modification of the Root.go file. The effect is as follows:

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

You can see that the demo supports both the direct use of flag flag and the ability to use subcommands

src\demo>demo test -hA longer description that spans multiple lines and likely contains examplesand 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 filesto quickly create a Cobra application.Usage:  demo test [flags]

The test command output information is called, and the default information is not modified here.

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

This is the error command prompt function

Over

The use of Cobra is introduced here, the update details can go to GitHub for a detailed study. Here is just a simple introduction to use, if there are errors, please point out, thank you ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.