1 minute read

urfave/cli能快速使用Go语言构建命令行APP,采用urfave/cli构建命令行APP。

创建一个Greet目录,新建greet.go,示例代码如下,使用go install之后便可使用greet相关命令了。更多的API使用方法可以参考官网。

package main

import (
	"fmt"
	"log"
	"os"
	"sort"

	"github.com/urfave/cli/v2"
)

func main() {
	var language string
	var count int
	app := &cli.App{
		Name:  "greet",
		Usage: "fight the loneliness!",
		// 自动补全命令行
		EnableBashCompletion: true,
		// 参数--lang --config
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:  "lang",
				Value: "english",
				// 参数的别名--lang也可用-l
				Aliases: []string{"l"},
				Usage:   "language for the greeting",
				// 提示的默认值(实际默认值为Value指定)
				DefaultText: "English",
				Destination: &language,
				// 环境变量
				EnvVars: []string{"LEGACY_COMPAT_LANG", "APP_LANG", "LANG"},
			},
			&cli.BoolFlag{
				Name:  "foo",
				Usage: "foo greeting",
				Count: &count,
				// 必须
				Required: true,
			},
			&cli.StringFlag{
				Name:    "config",
				Aliases: []string{"c"},
				Usage:   "Load configuration from `FILE`",
			},
			&cli.StringFlag{
				Name:    "password",
				Aliases: []string{"p"},
				Usage:   "password for the mysql database",
				//来自文件的变量,优先级高于环境变量
				FilePath: "/etc/mysql/password",
			},
			&cli.IntFlag{
				Name:        "port",
				Usage:       "Use a randomized port",
				Value:       0,
				DefaultText: "random",
				Action: func(ctx *cli.Context, v int) error {
					if v >= 65536 {
						return fmt.Errorf("flag port value %v out of range[0-65535]", v)
					}
					return nil
				},
			},
			&cli.BoolFlag{
				Name:  "ginger-crouton",
				Usage: "is it in the soup?",
			},
		},
		Commands: []*cli.Command{
			{
				// greet complete
				Name: "complete",
				// 分类
				Category: "template",
				Aliases:  []string{"c"},
				Usage:    "complete a task on the list",
				Action: func(*cli.Context) error {
					return nil
				},
			},
			{
				// greet add
				Name:     "add",
				Category: "template",
				Aliases:  []string{"a"},
				Usage:    "add a task to the list",
				Action: func(*cli.Context) error {
					return nil
				},
			},
			{
				Name:    "template",
				Aliases: []string{"t"},
				Usage:   "options for task templates",
				Subcommands: []*cli.Command{
					{
						// greet t add
						Name:  "add",
						Usage: "add a new template",
						Action: func(cCtx *cli.Context) error {
							fmt.Println("new task template: ", cCtx.Args().First())
							return nil
						},
					},
					{
						// greet t remove
						Name:  "remove",
						Usage: "remove an existing template",
						Action: func(cCtx *cli.Context) error {
							fmt.Println("removed task template: ", cCtx.Args().First())
							return nil
						},
					},
				},
			},
		},
		Action: func(ctx *cli.Context) error {
			name := "Nefertiti"
			if ctx.NArg() > 0 {
				name = ctx.Args().Get(0)
			}
			if language == "spanish" {
				fmt.Println("Hola", name)
			} else {
				fmt.Println("Hello", name)
			}
			fmt.Println("count", count)
			if !ctx.Bool("ginger-crouton") {
				return cli.Exit("Ginger croutons are not in the soup", 86)
			}
			return nil
		},
	}

	sort.Sort(cli.FlagsByName(app.Flags))
	sort.Sort(cli.CommandsByName(app.Commands))

	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}

Tags:

Categories:

Updated: