Cobra —— CLI 应用程序库

3 minute read

概述

Cobra 是一个库,提供了一个简单的接口来创建功能强大的现代 CLI 工具,类似于 git&go 工具。

Cobra 也是一个应用程序,将生成您的应用程序骨架,以迅速开发基于 Cobra 的应用程序。

本文将简要介绍 Cobra 库的在 Go 环境下的安装和使用。

在 Ubuntu 和 windows 上安装 Go 以及配置 GOPATH 的教程可以参考 这篇文章

本教程使用的完整代码可以在 https://github.com/eftales/Cobra-go-demo 找到。

Go 安装 Cobra

Go 的包管理软件为 go get ,使用以下命令安装。

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

由于 Cobra 库较大,安装可能需要一段时间(没有 VPN 可能会导致下载失败)。安装好之后,在 GOPATH/bin 目录下应该有了已经安装好的 Cobra 程序。

Cobra 库的简单应用

我们先利用 Cobra 生成一个模板。

cd $GOPATH/src
cobra init demo --pkg-name=demo
  • tips

    关于 cobra 的参数可以参考这个 github issue

这样就在 $GOPATH/src 路径下生成一个名为 demo 的文件夹,内部结构如下。

demo/
├── cmd
│   └── root.go
├── LICENSE
└── main.go

命令行一般由三部分组成,commands,flags,arguments。

program-name command flags

例如:git commit -m "init" 中,git 就是程序名,commit 是 command,-m 是 flag,”init” 是 arguments。

接下来,我们将增加识别 flags 和 commands 的程序。

flags

在没有 command 的情况下,主要需要修改两个地方,第一个是 cmd/root.go 的 rootCmd 变量,另一个是 cmd/root.go 的 init 函数。修改后的程序如下。

/*
Copyright © 2020 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 (
	"demo/imp"
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var (
	name string
	age  int
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "demo",
	Short: "A test demo",
	Long:  `A test demo and long.`, // 这句会在运行时输出
	// 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 and 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() {
	rootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
	rootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")

	/*
		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")

	*/

}

commands

使用命令 cobra add server 新建 commands 名称为 server,执行完成之后,会在 commands 文件夹下生成文件 server.go。需要修改的地方和 flags 一样。代码如下。

/*
Copyright © 2020 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"

	"github.com/spf13/cobra"
)

// serverCmd represents the server command
var serverCmd = &cobra.Command{
	Use:   "server",
	Short: "A brief description of your command",
	Long: `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.`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("server called")
	},
}

func init() {
	rootCmd.AddCommand(serverCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// serverCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// serverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}