golang cobra 命令行库

官方文档:https://godoc.org/github.com/spf13/cobra
go get -v github.com/spf13/cobra/cobra

cobra既是一个用来创建强大的现代CLI命令行的golang库,也是一个生成程序应用和命令行文件的程序。

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生成应用程序

执行下面命令会在src目录下生成demo文件夹
F:\work\goCode\src>cobra.exe init demo
Your Cobra application is ready at
F:\work\goCode\src\demo

Give it a try by going there and running go run main.go.
Add commands to it by running cobra add [cmdname].

demo目录结构
| LICENSE
| main.go
|
—cmd
​ root.go

cat mian.go 生成代码

// Copyright © 2018 NAME HERE 
//
// 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()
}

cat root.go 生成代码

// Copyright © 2018 NAME HERE 
//
// 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"

	homedir "github.com/mitchellh/go-homedir"
	"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 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() {
	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 != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		// Search config in home directory with name ".demo" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".demo")
	}

	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())
	}
}

增加imp目录
F:.
| LICENSE
| main.go
|
±–cmd
| root.go
|
—imp
​ imp.go

cat 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)
}

修改root.go 文件

package cmd

import (
	"fmt"
	"os"

	"demo/imp"

	"github.com/spf13/cobra"
)

//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`,
	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() {
	RootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
	RootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")
}

编译
F:\work\goCode\src\demo>go build

执行demo
F:\work\goCode\src\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
F:\work\goCode\src\demo>demo.exe -n zhangsan --age 18
My Name is zhangsan, My age is 18

你可能感兴趣的:(go)