Golang Command line library Cobra usage

Source: Internet
Author: User
Tags configuration settings

Brief introduction

Cobra is both a golang library for creating powerful modern CLI command lines and a program for generating application applications and command line files.

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 usesgo getto 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 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]

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 imp

import(
    "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 main
import "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 © 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())
    }
}

Looking 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 © 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())
//  }
//}

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

>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

How to implement a CLIs program with sub-commands

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

src\demo>..\..\bin\cobra add test
test 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>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.

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

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]

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

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

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.