diff --git a/app.go b/app.go index a614236..298e7f1 100644 --- a/app.go +++ b/app.go @@ -64,6 +64,7 @@ func (a *App) Run(arguments []string) error { } //append version/help flags + a.appendFlag(BoolFlag{"generate-bash-completion", ""}) a.appendFlag(BoolFlag{"version, v", "print the version"}) a.appendFlag(BoolFlag{"help, h", "show help"}) @@ -88,6 +89,10 @@ func (a *App) Run(arguments []string) error { return err } + if checkCompletions(context) { + return nil + } + if checkHelp(context) { return nil } diff --git a/command.go b/command.go index d05cdf5..55d5221 100644 --- a/command.go +++ b/command.go @@ -16,6 +16,8 @@ type Command struct { Usage string // A longer explaination of how the command works Description string + // The function to call when checking for bash command completions + BashComplete func(context *Context) // The function to call when this command is invoked Action func(context *Context) // List of flags to parse @@ -27,6 +29,7 @@ func (c Command) Run(ctx *Context) error { // append help to flags c.Flags = append( c.Flags, + BoolFlag{"generate-bash-completion", ""}, BoolFlag{"help, h", "show help"}, ) @@ -67,6 +70,11 @@ func (c Command) Run(ctx *Context) error { return nerr } context := NewContext(ctx.App, set, ctx.globalSet) + + if checkCommandCompletions(context, c.Name) { + return nil + } + if checkCommandHelp(context, c.Name) { return nil } diff --git a/help.go b/help.go index 094d01d..6ac03be 100644 --- a/help.go +++ b/help.go @@ -81,6 +81,24 @@ func ShowVersion(c *Context) { fmt.Printf("%v version %v\n", c.App.Name, c.App.Version) } +// Prints the lists of commands within a given context +func ShowCompletions(c *Context) { + for _, command := range c.App.Commands { + fmt.Println(command.Name) + if command.ShortName != "" { + fmt.Println(command.ShortName) + } + } +} + +// Prints the custom completions for a given command +func ShowCommandCompletions(ctx *Context, command string) { + c := ctx.App.Command(command) + if c != nil && c.BashComplete != nil { + c.BashComplete(ctx) + } +} + func printHelp(templ string, data interface{}) { w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0) t := template.Must(template.New("help").Parse(templ)) @@ -117,3 +135,21 @@ func checkCommandHelp(c *Context, name string) bool { return false } + +func checkCompletions(c *Context) bool { + if c.GlobalBool("generate-bash-completion") { + ShowCompletions(c) + return true + } + + return false +} + +func checkCommandCompletions(c *Context, name string) bool { + if c.Bool("generate-bash-completion") { + ShowCommandCompletions(c, name) + return true + } + + return false +}