From faf2a3d4a3371d302c16b4a751571d95ea732679 Mon Sep 17 00:00:00 2001 From: Summer Mousa Date: Wed, 16 Apr 2014 15:26:28 -0500 Subject: [PATCH] Added Before method to command. If set, or if command.Subcommands is set, then the command is treated as a recursive subcommand --- app.go | 7 +++++++ command.go | 12 ++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/app.go b/app.go index f9342d7..a4a76ef 100644 --- a/app.go +++ b/app.go @@ -171,6 +171,13 @@ func (a *App) RunAsSubcommand(c *Context) error { return nil } + if a.Before != nil { + err := a.Before(context) + if err != nil { + return err + } + } + args := context.Args() if args.Present() { name := args.First() diff --git a/command.go b/command.go index 2d5c662..735505b 100644 --- a/command.go +++ b/command.go @@ -18,17 +18,20 @@ type Command struct { Description string // The function to call when checking for bash command completions BashComplete func(context *Context) + // 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 func(context *Context) error // The function to call when this command is invoked Action func(context *Context) - // List of flags to parse - Flags []Flag // List of child commands Subcommands []Command + // List of flags to parse + Flags []Flag } // Invokes the command given the context, parses ctx.Args() to generate command-specific flags func (c Command) Run(ctx *Context) error { - if len(c.Subcommands) > 0 { + if (c.Subcommands != nil && len(c.Subcommands) > 0) || c.Before != nil { return c.startApp(ctx) } @@ -117,7 +120,8 @@ func (c Command) startApp(ctx *Context) error { app.BashComplete = c.BashComplete } - // set the action + // set the actions + app.Before = c.Before if c.Action != nil { app.Action = c.Action } else {