golang urfave/cli 命令包

官方文档 : https://godoc.org/github.com/urfave/cli
提供了一个命令行框架。

go get github.com/urfave/cli
import “github.com/urfave/cli”

导入包
cli.NewApp()创建一个实例
调用Run()方法就实现了一个最基本的命令行程序了
app.Action 指定入口函数

package main

import (
	"os"

	"github.com/urfave/cli"
)

func main() {
	app := cli.NewApp()
	app.Name = "greet"
	app.Usage = "say a greeting"
	app.Action = func(c *cli.Context) error {
		println("Greetings")
		return nil
	}

	app.Run(os.Args)
}

运行1:
go run main.go --help
NAME:
greet - say a greeting

USAGE:
main.exe [global options] command [command options] [arguments…]

VERSION:
0.0.0

COMMANDS:
​ help, h Shows a list of commands or help for one command

GLOBAL OPTIONS:
–help, -h show help
–version, -v print the version

运行2:
go run main.go
Greetings


Flag 使用

package main

import (
	"fmt"
	"os"

	"github.com/urfave/cli"
)

func main() {
	var m_port int
	app := cli.NewApp()
	app.Name = "greet"           // 指定程序名称
	app.Usage = "say a greeting" //  程序功能描述
	app.Flags = []cli.Flag{
		cli.IntFlag{
			Name:        "port, p",        // 配置名称
			Value:       8000,             // 缺省配置值
			Usage:       "listening port", // 配置描述
			Destination: &m_port,          // 保存配置值
		},
	}
	app.Action = func(c *cli.Context) error {
		println("Greetings")
		fmt.Println(c.Int("port"))
		fmt.Println(m_port)
		return nil
	}

	app.Run(os.Args)
}

运行1:
go run main.go --help
NAME:
greet - say a greeting

USAGE:
main.exe [global options] command [command options] [arguments…]

VERSION:
0.0.0

COMMANDS:
​ help, h Shows a list of commands or help for one command

GLOBAL OPTIONS:
–port value, -p value listening port (default: 8000)
–help, -h show help
–version, -v print the version

运行2:
go run main.go
Greetings
8000
8000

运行3:
go run main.go --port=8080
Greetings
8080
8080


Command 使用

package main

import (
	"fmt"
	"os"

	"github.com/urfave/cli"
)

func main() {
	var m_port int
	app := cli.NewApp()
	app.Name = "greet"           // 指定程序名称
	app.Usage = "say a greeting" //  程序功能描述
	app.Flags = []cli.Flag{
		cli.IntFlag{
			Name:        "port, p",        // 配置名称
			Value:       8000,             // 缺省配置值
			Usage:       "listening port", // 配置描述
			Destination: &m_port,          // 保存配置值
		},
	}
	app.Commands = []cli.Command{
		{
			Name:     "add",         //命令名称
			Aliases:  []string{"a"}, // 命令的别名列表
			Usage:    "calc 1+1",    // 命令描述
			Category: "arithmetic",  // 命令所属的类别
			Action: func(c *cli.Context) error { // 函数入口
				fmt.Println("1 + 1 = ", 1+1)
				return nil
			},
		},
		{
			Name:     "sub",
			Aliases:  []string{"s"},
			Usage:    "calc 5-3",
			Category: "arithmetic",
			Action: func(c *cli.Context) error {
				fmt.Println("5 - 3 = ", 5-3)
				return nil
			},
		},
		{
			Name:     "db",
			Usage:    "database operations",
			Category: "database",
			Subcommands: []cli.Command{ // 子命令列表
				{
					Name:  "insert",
					Usage: "insert data",
					Action: func(c *cli.Context) error {
						fmt.Println("insert subcommand")
						return nil
					},
				},
				{
					Name:  "delete",
					Usage: "delete data",
					Action: func(c *cli.Context) error {
						fmt.Println("delete subcommand")
						return nil
					},
				},
			},
		},
	}

	app.Action = func(c *cli.Context) error {
		println("Greetings")
		fmt.Println(c.Int("port"))
		fmt.Println(m_port)
		return nil
	}

	app.Run(os.Args)
}

运行1:
go run main.go --help
NAME:
greet - say a greeting

USAGE:
main.exe [global options] command [command options] [arguments…]

VERSION:
0.0.0

COMMANDS:
help, h Shows a list of commands or help for one command

arithmetic:
add, a calc 1+1
sub, s calc 5-3

database:
db database operations

GLOBAL OPTIONS:
–port value, -p value listening port (default: 8000)
–help, -h show help
–version, -v print the version

运行2:
go run main.go db --help
NAME:
greet db - database operations

USAGE:
greet db command [command options] [arguments…]

COMMANDS:
insert insert data
delete delete data

OPTIONS:
–help, -h show help

运行3:
go run main.go add --help
NAME:
main.exe add - calc 1+1

USAGE:
main.exe add [arguments…]

CATEGORY:
arithmetic

运行4:
go run main.go --port 8080
Greetings
8080
8080

运行5:
go run main.go add
1 + 1 = 2

运行6:
go run main.go db insert
insert subcommand

运行7:
go run main.go --port=8080 add db insert
1 + 1 = 2

运行8:
go run main.go add db insert
1 + 1 = 2

运行9:
go run main.go
Greetings
8000
8000

高级用法

package main

import (
	"fmt"
	"os"

	"github.com/urfave/cli"
)

func main() {
	app := cli.NewApp()
	app.Name = "greet"           // 指定程序名称
	app.Usage = "say a greeting" //  程序功能描述
	app.Flags = []cli.Flag{
		cli.IntFlag{
			Name:  "port, p",        // 配置名称
			Value: 8000,             // 缺省配置值
			Usage: "listening port", // 配置描述
		},
	}
	app.Action = MigrateFlags(print1)

	app.Commands = []cli.Command{
		{
			Name:     "add",         //命令名称
			Aliases:  []string{"a"}, // 命令的别名列表
			Usage:    "calc 1+1",    // 命令描述
			Category: "arithmetic",  // 命令所属的类别
			Action:   MigrateFlags(print2),
		},
	}

	app.Run(os.Args)
}

func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error {
	return func(ctx *cli.Context) error {
		for _, name := range ctx.FlagNames() {
			if ctx.IsSet(name) {
				ctx.GlobalSet(name, ctx.String(name))
			}
		}
		return action(ctx)
	}
}

func print1(ctx *cli.Context) error {
	fmt.Println("hello world!")
	fmt.Println(ctx.Int("port"))
	return nil
}

func print2(ctx *cli.Context) error {
	fmt.Println("1 + 1 = ", 1+1)
	return nil
}

运行1:
go run main.go
hello world!
8000

运行2:
go run main.go add
1 + 1 = 2



type App struct {
    // The name of the program. Defaults to path.Base(os.Args[0])
    Name string	// 程序的名称,缺省值是运行的程序名,可以设置为其名称。
    // Full name of command for help, defaults to Name
    HelpName string 
    // Description of the program.
    Usage string // 程序功能描述
    // Text to override the USAGE section of help
    UsageText string
    // Description of the program argument format.
    ArgsUsage string
    // Version of the program
    Version string
    // Description of the program
    Description string
    // List of commands to execute
    Commands []Command
    // List of flags to parse
    Flags []Flag // Flag是cli中与解析标志相关的公共接口
    // Boolean to enable bash completion commands
    EnableBashCompletion bool
    // Boolean to hide built-in help command
    HideHelp bool
    // Boolean to hide built-in version flag and the VERSION section of help
    HideVersion bool

    // An action to execute when the bash-completion flag is set
    BashComplete BashCompleteFunc
    // An action to execute before any subcommands are run, but after the context is ready
    // If a non-nil error is returned, no subcommands are run
    Before BeforeFunc
    // An action to execute after any subcommands are run, but after the subcommand has finished
    // It is run even if Action() panics
    After AfterFunc

    // The action to execute when no subcommands are specified
    // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}`
    // *Note*: support for the deprecated `Action` signature will be removed in a future version
    Action interface{}

    // Execute this function if the proper command cannot be found
    CommandNotFound CommandNotFoundFunc
    // Execute this function if an usage error occurs
    OnUsageError OnUsageErrorFunc
    // Compilation date
    Compiled time.Time
    // List of all authors who contributed
    Authors []Author
    // Copyright of the binary if any
    Copyright string
    // Name of Author (Note: Use App.Authors, this is deprecated)
    Author string
    // Email of Author (Note: Use App.Authors, this is deprecated)
    Email string
    // Writer writer to write output to
    Writer io.Writer
    // ErrWriter writes error output
    ErrWriter io.Writer
    // Execute this function to handle ExitErrors. If not provided, HandleExitCoder is provided to
    // function as a default, so this is optional.
    ExitErrHandler ExitErrHandlerFunc
    // Other custom info
    Metadata map[string]interface{}
    // Carries a function which returns app specific info.
    ExtraInfo func() map[string]string
    // CustomAppHelpTemplate the text template for app help topic.
    // cli.go uses text/template to render templates. You can
    // render custom help text by setting this variable.
    CustomAppHelpTemplate string
    // contains filtered or unexported fields
}

Flag是cli中与解析标志相关的公共接口

type Flag interface {
    fmt.Stringer
    // Apply Flag settings to the given flag set
    Apply(*flag.FlagSet)
    GetName() string
}

IntFlag 是 Flag 的一个整型类型,实现了Flag接口。

type IntFlag struct {
    Name        string	// 配置名称
    Usage       string	// 描述该配置的功能
    EnvVar      string	
    FilePath    string
    Hidden      bool	
    Value       int		// 配置的默认值
    Destination *int	// 可以保存配置值
}

Command 命令

type Command struct {
    // The name of the command
    Name string
    // short name of the command. Typically one character (deprecated, use `Aliases`)
    ShortName string
    // A list of aliases for the command
    Aliases []string
    // A short description of the usage of this command
    Usage string
    // Custom text to show on USAGE section of help
    UsageText string
    // A longer explanation of how the command works
    Description string
    // A short description of the arguments of this command
    ArgsUsage string
    // The category the command is part of
    Category string	// 命令所属的类别
    // The function to call when checking for bash command completions
    BashComplete BashCompleteFunc
    // An action to execute before any sub-subcommands are run, but after the context is ready
    // If a non-nil error is returned, no sub-subcommands are run
    Before BeforeFunc
    // An action to execute after any subcommands are run, but after the subcommand has finished
    // It is run even if Action() panics
    After AfterFunc
    // The function to call when this command is invoked
    Action interface{}

    // Execute this function if a usage error occurs.
    OnUsageError OnUsageErrorFunc
    // List of child commands
    Subcommands Commands
    // List of flags to parse
    Flags []Flag
    // Treat all flags as normal arguments if true
    SkipFlagParsing bool
    // Skip argument reordering which attempts to move flags before arguments,
    // but only works if all flags appear after all arguments. This behavior was
    // removed n version 2 since it only works under specific conditions so we
    // backport here by exposing it as an option for compatibility.
    SkipArgReorder bool
    // Boolean to hide built-in help command
    HideHelp bool
    // Boolean to hide this command from help or completion
    Hidden bool
    // Boolean to enable short-option handling so user can combine several
    // single-character bool arguments into one
    // i.e. foobar -o -v -> foobar -ov
    UseShortOptionHandling bool

    // Full name of command for help, defaults to full command name, including parent commands.
    HelpName string

    // CustomHelpTemplate the text template for the command help topic.
    // cli.go uses text/template to render templates. You can
    // render custom help text by setting this variable.
    CustomHelpTemplate string
    // contains filtered or unexported fields
}
// Context is a type that is passed through to
// each Handler action in a cli application. Context
// can be used to retrieve context-specific Args and
// parsed command-line options.
type Context struct {
	App           *App
	Command       Command
	shellComplete bool
	flagSet       *flag.FlagSet
	setFlags      map[string]bool
	parentContext *Context
}

你可能感兴趣的:(go)