Subcommands:子命令
可以为更像git的命令行应用程序定义子命令。
Subcommands: []*cli.Command{ //子命令设置
{
Name: "template",
Aliases: []string{"t"},
Usage: "options for task templates",
Subcommands: []*cli.Command{ //子命令设置
{
Name: "add",
Usage: "add a new template",
Action: func(c *cli.Context) error {
fmt.Println("new task template: ", c.Args().First())
return nil
},
},
{
Name: "remove",
Usage: "remove an existing template",
Action: func(c *cli.Context) error {
fmt.Println("removed task template: ", c.Args().First())
return nil
},
},
},
},
Subcommands categories:子命令分类
For additional organization in apps that have many subcommands, you can associate a category for each command to group them together in the help output.
对于有许多子命令的应用程序中的其他组织,您可以为每个命令关联一个类别,以便在帮助输出中将它们分组在一起。
Category: "template", //归类为template模板中
app := &cli.App{
Commands: []*cli.Command{
{
Name: "noop",
},
{
Name: "add",
Category: "template", //归类为template模板中
},
{
Name: "remove",
Category: "template", //归类为template模板中
},
},
命令行输出:
COMMANDS:
noop
help, h Shows a list of commands or help for one command
template:
add //add和remove为template的子命令
remove
Exit code:退出代码
调用App.Run不会自动调用os.Exit
一个显式的退出码可以通过返回一个满足cli的非nil错误来设置。ExitCoder,或者cli.MultiError。包含一个满足cli.ExitCoder的错误。
Action: func(ctx *cli.Context) error { if !ctx.Bool("ginger-crouton") { return cli.Exit("Ginger croutons are not in the soup", 86) } return nil },
Combining short options:结合短选项
假设您希望用户能够将选项与他们的短名称组合在一起。这可以通过在应用程序配置中使用UseShortOptionHandling bool来完成,或者通过将它附加到命令配置中来完成单个命令。例如:
app := &cli.App{}
app.UseShortOptionHandling = true //设置UseShortOptionHandling 参数为 true
app.Commands = []*cli.Command{
{
Name: "short",
Usage: "complete a task on the list",
Flags: []cli.Flag{
&cli.BoolFlag{Name: "serve", Aliases: []string{"s"}},
&cli.BoolFlag{Name: "option", Aliases: []string{"o"}},
&cli.StringFlag{Name: "message", Aliases: []string{"m"}},
},
Action: func(c *cli.Context) error {
fmt.Println("serve:", c.Bool("serve"))
fmt.Println("option:", c.Bool("option"))
fmt.Println("message:", c.String("message"))
return nil
},
},
}
//他们还可以组合起来使用,例如:
short -som "Some message"
Bash Completion:Bash tab complete
你可以通过设置App中flag EnableBashCompletion为true。 默认情况下,这个设置将允许应用程序的子命令自动完成。但是你也可以为应用程序或它的子命令编写你自己的完成方法。
app := cli.NewApp()
app.EnableBashCompletion = true