interceptors

package
v1.501.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2023 License: Apache-2.0 Imports: 2 Imported by: 0

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

type RunEContextFn func(ctx context.Context, cmd *cobra.Command, args []string) error

RunEContextFn is the signature based on RunEFn that injects the context as an argument.

type RunEFn

type RunEFn func(cmd *cobra.Command, args []string) error

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]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL