From 3900c1e86f533f1443e77368ad2c98ea94fc3c04 Mon Sep 17 00:00:00 2001 From: Jason Bedard Date: Wed, 9 Feb 2022 11:30:13 -0800 Subject: [PATCH] fix: interceptors Run() when list of interceptors is empty --- pkg/interceptors/run.go | 8 ++++---- pkg/interceptors/run_test.go | 26 +++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/pkg/interceptors/run.go b/pkg/interceptors/run.go index 7a16a6e79..3cf78bd90 100644 --- a/pkg/interceptors/run.go +++ b/pkg/interceptors/run.go @@ -28,13 +28,13 @@ type Interceptor func(ctx context.Context, cmd *cobra.Command, args []string, ne func Run(interceptors []Interceptor, fn RunEContextFn) RunEFn { return func(cmd *cobra.Command, args []string) error { current := fn - for i := len(interceptors) - 1; i > 0; i-- { - j := i + for i := len(interceptors) - 1; i >= 0; i-- { + interceptor := interceptors[i] next := current current = func(ctx context.Context, cmd *cobra.Command, args []string) error { - return interceptors[j](ctx, cmd, args, next) + return interceptor(ctx, cmd, args, next) } } - return interceptors[0](cmd.Context(), cmd, args, current) + return current(cmd.Context(), cmd, args) } } diff --git a/pkg/interceptors/run_test.go b/pkg/interceptors/run_test.go index 630c080a4..696968ec8 100644 --- a/pkg/interceptors/run_test.go +++ b/pkg/interceptors/run_test.go @@ -16,7 +16,7 @@ import ( "github.com/spf13/cobra" ) -func ExampleRun() { +func ExampleRun_interceptor_order() { g := NewGomega(func(message string, callerSkip ...int) { log.Fatal(message) }) @@ -49,6 +49,30 @@ func ExampleRun() { // interceptor 1 } +func ExampleRun_nointerceptors() { + g := NewGomega(func(message string, callerSkip ...int) { + log.Fatal(message) + }) + + ctx := context.Background() + args := []string{"foo", "bar"} + os.Args = append([]string{"fake"}, args...) + cmd := &cobra.Command{Use: "fake"} + cmd.RunE = Run( + []Interceptor{}, + func(_ctx context.Context, _cmd *cobra.Command, _args []string) error { + g.Expect(_cmd).To(Equal(cmd)) + g.Expect(_args).To(Equal(args)) + fmt.Printf("called %q with %v\n", _cmd.Use, _args) + return nil + }, + ) + cmd.ExecuteContext(ctx) + + // Output: + // called "fake" with [foo bar] +} + func LoggingInterceptor1() Interceptor { return func(ctx context.Context, cmd *cobra.Command, args []string, next RunEContextFn) error { fmt.Println("interceptor 1")