Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V1: Issue #800: Adding Prepare directive which runs after Before but before Action #802

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1334,6 +1334,10 @@ func main() {
fmt.Fprintf(c.App.Writer, "brace for impact\n")
return nil
},
Prepare: func(c *cli.Context) error {
fmt.Fprintf(c.App.Writer, "we've almost made it!\n")
return nil
},
After: func(c *cli.Context) error {
fmt.Fprintf(c.App.Writer, "did we lose anyone?\n")
return nil
Expand Down Expand Up @@ -1380,6 +1384,10 @@ func main() {
fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n")
return nil
}
app.Prepare = func(c *cli.Context) error {
fmt.Fprintf(c.App.Writer, "JUST ONE LAST BIT\n")
return nil
}
app.After = func(c *cli.Context) error {
fmt.Fprintf(c.App.Writer, "Phew!\n")
return nil
Expand Down
23 changes: 23 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ type App struct {
// 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 Before is run, any subcommands are run, and after the context is ready
// It is run even if Before() panics, and if a non-nil error is returned, no subcommands are run
Prepare PrepareFunc
// An action to execute after any subcommands are run, but after the subcommand has finished
// It is run even if Action() panics
After AfterFunc
Expand Down Expand Up @@ -251,6 +254,17 @@ func (a *App) Run(arguments []string) (err error) {
}
}

if a.Prepare != nil {
prepareErr := a.Prepare(context)
if prepareErr != nil {
fmt.Fprintf(a.Writer, "%v\n\n", prepareErr)
ShowAppHelp(context)
a.handleExitCoder(context, prepareErr)
err = prepareErr
return err
}
}

args := context.Args()
if args.Present() {
name := args.First()
Expand Down Expand Up @@ -375,6 +389,15 @@ func (a *App) RunAsSubcommand(ctx *Context) (err error) {
}
}

if a.Prepare != nil {
prepareErr := a.Prepare(context)
if prepareErr != nil {
a.handleExitCoder(context, prepareErr)
err = prepareErr
return err
}
}

args := context.Args()
if args.Present() {
name := args.First()
Expand Down
170 changes: 152 additions & 18 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func init() {
}

type opCounts struct {
Total, BashComplete, OnUsageError, Before, CommandNotFound, Action, After, SubCommand int
Total, BashComplete, OnUsageError, Before, Prepare, CommandNotFound, Action, After, SubCommand int
}

func ExampleApp_Run() {
Expand Down Expand Up @@ -418,7 +418,8 @@ func TestApp_RunAsSubcommandParseFlags(t *testing.T) {
Usage: "language for the greeting",
},
},
Before: func(_ *Context) error { return nil },
Before: func(_ *Context) error { return nil },
Prepare: func(_ *Context) error { return nil },
},
}
a.Run([]string{"", "foo", "--lang", "spanish", "abcd"})
Expand Down Expand Up @@ -792,6 +793,98 @@ func TestApp_BeforeFunc(t *testing.T) {
}
}

func TestApp_PrepareFunc(t *testing.T) {
counts := &opCounts{}
prepareError := fmt.Errorf("fail")
var err error

app := NewApp()

app.Prepare = func(c *Context) error {
counts.Total++
counts.Prepare = counts.Total
s := c.String("opt")
if s == "fail" {
return prepareError
}

return nil
}

app.Commands = []Command{
{
Name: "sub",
Action: func(c *Context) error {
counts.Total++
counts.SubCommand = counts.Total
return nil
},
},
}

app.Flags = []Flag{
StringFlag{Name: "opt"},
}

// run with the Prepare() func succeeding
err = app.Run([]string{"command", "--opt", "succeed", "sub"})

if err != nil {
t.Fatalf("Run error: %s", err)
}

if counts.Prepare != 1 {
t.Errorf("Prepare() not executed when expected")
}

if counts.SubCommand != 2 {
t.Errorf("Subcommand not executed when expected")
}

// reset
counts = &opCounts{}

// run with the Prepare() func failing
err = app.Run([]string{"command", "--opt", "fail", "sub"})

// should be the same error produced by the Prepare func
if err != prepareError {
t.Errorf("Run error expected, but not received")
}

if counts.Prepare != 1 {
t.Errorf("Prepare() not executed when expected")
}

if counts.SubCommand != 0 {
t.Errorf("Subcommand executed when NOT expected")
}

// reset
counts = &opCounts{}

afterError := errors.New("fail again")
app.After = func(_ *Context) error {
return afterError
}

// run with the Prepare() func failing, wrapped by After()
err = app.Run([]string{"command", "--opt", "fail", "sub"})

// should be the same error produced by the Prepare func
if _, ok := err.(MultiError); !ok {
t.Errorf("MultiError expected, but not received")
}

if counts.Prepare != 1 {
t.Errorf("Prepare() not executed when expected")
}

if counts.SubCommand != 0 {
t.Errorf("Subcommand executed when NOT expected")
}
}

func TestApp_AfterFunc(t *testing.T) {
counts := &opCounts{}
afterError := fmt.Errorf("fail")
Expand Down Expand Up @@ -843,10 +936,10 @@ func TestApp_AfterFunc(t *testing.T) {
// reset
counts = &opCounts{}

// run with the Before() func failing
// run with the After() func failing
err = app.Run([]string{"command", "--opt", "fail", "sub"})

// should be the same error produced by the Before func
// should be the same error produced by the After func
if err != afterError {
t.Errorf("Run error expected, but not received")
}
Expand Down Expand Up @@ -974,6 +1067,20 @@ func TestApp_OrderOfOperations(t *testing.T) {
}

app.Before = beforeNoError

prepareNoError := func(c *Context) error {
counts.Total++
counts.Prepare = counts.Total
return nil
}

prepareError := func(c *Context) error {
counts.Total++
counts.Prepare = counts.Total
return errors.New("hay Prepare")
}
app.Prepare = prepareNoError

app.CommandNotFound = func(c *Context, command string) {
counts.Total++
counts.CommandNotFound = counts.Total
Expand Down Expand Up @@ -1032,29 +1139,46 @@ func TestApp_OrderOfOperations(t *testing.T) {
_ = app.Run([]string{"command", "foo"})
expect(t, counts.OnUsageError, 0)
expect(t, counts.Before, 1)
expect(t, counts.Prepare, 2)
expect(t, counts.CommandNotFound, 0)
expect(t, counts.Action, 2)
expect(t, counts.After, 3)
expect(t, counts.Total, 3)
expect(t, counts.Action, 3)
expect(t, counts.After, 4)
expect(t, counts.Total, 4)

resetCounts()

// Before will yield an error and lead prepare without running
app.Before = beforeError
_ = app.Run([]string{"command", "bar"})
expect(t, counts.OnUsageError, 0)
expect(t, counts.Before, 1)
expect(t, counts.Prepare, 0)
expect(t, counts.After, 2)
expect(t, counts.Total, 2)
app.Before = beforeNoError

resetCounts()

// Since we do not execute a Before we then run prepare and expect it will
// yield an error itself
app.Prepare = prepareError
_ = app.Run([]string{"command", "bar"})
expect(t, counts.OnUsageError, 0)
expect(t, counts.Before, 1)
expect(t, counts.Prepare, 2)
expect(t, counts.After, 3)
expect(t, counts.Total, 3)
app.Prepare = prepareNoError

resetCounts()

app.After = nil
_ = app.Run([]string{"command", "bar"})
expect(t, counts.OnUsageError, 0)
expect(t, counts.Before, 1)
expect(t, counts.SubCommand, 2)
expect(t, counts.Total, 2)
expect(t, counts.Prepare, 2)
expect(t, counts.SubCommand, 3)
expect(t, counts.Total, 3)
app.After = afterNoError

resetCounts()
Expand All @@ -1066,9 +1190,10 @@ func TestApp_OrderOfOperations(t *testing.T) {
}
expect(t, counts.OnUsageError, 0)
expect(t, counts.Before, 1)
expect(t, counts.SubCommand, 2)
expect(t, counts.After, 3)
expect(t, counts.Total, 3)
expect(t, counts.Prepare, 2)
expect(t, counts.SubCommand, 3)
expect(t, counts.After, 4)
expect(t, counts.Total, 4)
app.After = afterNoError

resetCounts()
Expand All @@ -1078,9 +1203,10 @@ func TestApp_OrderOfOperations(t *testing.T) {
_ = app.Run([]string{"command"})
expect(t, counts.OnUsageError, 0)
expect(t, counts.Before, 1)
expect(t, counts.Action, 2)
expect(t, counts.After, 3)
expect(t, counts.Total, 3)
expect(t, counts.Prepare, 2)
expect(t, counts.Action, 3)
expect(t, counts.After, 4)
expect(t, counts.Total, 4)
app.Commands = oldCommands
}

Expand Down Expand Up @@ -1485,6 +1611,7 @@ func TestApp_Run_DoesNotOverwriteErrorFromBefore(t *testing.T) {
app := NewApp()
app.Action = func(c *Context) error { return nil }
app.Before = func(c *Context) error { return fmt.Errorf("before error") }
app.Prepare = func(c *Context) error { return fmt.Errorf("prepare error") }
app.After = func(c *Context) error { return fmt.Errorf("after error") }

err := app.Run([]string{"foo"})
Expand All @@ -1495,6 +1622,9 @@ func TestApp_Run_DoesNotOverwriteErrorFromBefore(t *testing.T) {
if !strings.Contains(err.Error(), "before error") {
t.Errorf("expected text of error from Before method, but got none in \"%v\"", err)
}
if strings.Contains(err.Error(), "prepare error") {
t.Errorf("not expecting text of error from Prepare method, because Before errors before Prepare \"%v\"", err)
}
if !strings.Contains(err.Error(), "after error") {
t.Errorf("expected text of error from After method, but got none in \"%v\"", err)
}
Expand All @@ -1509,9 +1639,10 @@ func TestApp_Run_SubcommandDoesNotOverwriteErrorFromBefore(t *testing.T) {
Name: "sub",
},
},
Name: "bar",
Before: func(c *Context) error { return fmt.Errorf("before error") },
After: func(c *Context) error { return fmt.Errorf("after error") },
Name: "bar",
Before: func(c *Context) error { return fmt.Errorf("before error") },
Prepare: func(c *Context) error { return fmt.Errorf("prepare error") },
After: func(c *Context) error { return fmt.Errorf("after error") },
},
}

Expand All @@ -1523,6 +1654,9 @@ func TestApp_Run_SubcommandDoesNotOverwriteErrorFromBefore(t *testing.T) {
if !strings.Contains(err.Error(), "before error") {
t.Errorf("expected text of error from Before method, but got none in \"%v\"", err)
}
if strings.Contains(err.Error(), "prepare error") {
t.Errorf("not expecting text of error from Prepare method, because Before had an error prior, but got none in \"%v\"", err)
}
if !strings.Contains(err.Error(), "after error") {
t.Errorf("expected text of error from After method, but got none in \"%v\"", err)
}
Expand Down
15 changes: 14 additions & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ type Command struct {
// 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 Before is run, any subcommands are run, and after the context is ready
// It is run even if Before() panics, and if a non-nil error is returned, no subcommands are run
Prepare PrepareFunc
// An action to execute after any subcommands are run, but after the subcommand has finished
// It is run even if Action() panics
After AfterFunc
Expand Down Expand Up @@ -158,6 +161,15 @@ func (c Command) Run(ctx *Context) (err error) {
}
}

if c.Prepare != nil {
err = c.Prepare(context)
if err != nil {
ShowCommandHelp(context, c.Name)
context.App.handleExitCoder(context, err)
return err
}
}

if c.Action == nil {
c.Action = helpSubcommand.Action
}
Expand Down Expand Up @@ -266,7 +278,7 @@ func reorderArgs(args []string) []string {
}

func translateShortOptions(set *flag.FlagSet, flagArgs Args) []string {
allCharsFlags := func (s string) bool {
allCharsFlags := func(s string) bool {
for i := range s {
f := set.Lookup(string(s[i]))
if f == nil {
Expand Down Expand Up @@ -362,6 +374,7 @@ func (c Command) startApp(ctx *Context) error {

// set the actions
app.Before = c.Before
app.Prepare = c.Prepare
app.After = c.After
if c.Action != nil {
app.Action = c.Action
Expand Down
Loading