Documentation ¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Interceptor ¶
type Interceptor func(ctx context.Context, cmd *cobra.Command, args []string, next RunEContextFn) error
Interceptor represents an interceptor in the CLI command chain. It's represented as a function signature.
type RunEContextFn ¶
RunEContextFn is the signature based on RunEFn that injects the context as an argument.
type RunEFn ¶
RunEFn matches the cobra command.RunE signature.
func Run ¶
func Run(interceptors []Interceptor, fn RunEContextFn) RunEFn
Run returns a function that matches the cobra RunE signature. It assembles the interceptors and main command to be run in the correct sequence.
Example (Interceptor_order) ¶
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{ LoggingInterceptor1(), InjectIntoContextInterceptor(), LoggingInterceptor2(), }, func(_ctx context.Context, _cmd *cobra.Command, _args []string) error { g.Expect(_cmd).To(Equal(cmd)) g.Expect(_args).To(Equal(args)) ctxVal := _ctx.Value("my_key").(string) fmt.Printf("called %q with %v, and ctx contains %q\n", _cmd.CalledAs(), _args, ctxVal) return nil }, ) cmd.ExecuteContext(ctx)
Output: interceptor 1 interceptor 2: "injected value" called "fake" with [foo bar], and ctx contains "injected value" interceptor 2: "injected value" interceptor 1
Example (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]
Click to show internal directories.
Click to hide internal directories.