Skip to content

Commit

Permalink
Adds SetContext()
Browse files Browse the repository at this point in the history
fixes spf13#563
  • Loading branch information
poy committed Jun 2, 2021
1 parent 352d20c commit 817fe94
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
8 changes: 7 additions & 1 deletion command.go
Expand Up @@ -244,11 +244,17 @@ type Command struct {
}

// Context returns underlying command context. If command wasn't
// executed with ExecuteContext Context returns Background context.
// executed with ExecuteContext Context, or overriden via SetContext it
// returns Background context.
func (c *Command) Context() context.Context {
return c.ctx
}

// SetContext overrides the command's underlying context.
func (c *Command) SetContext(ctx context.Context) {
c.ctx = ctx
}

// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
// particularly useful when testing.
func (c *Command) SetArgs(a []string) {
Expand Down
21 changes: 14 additions & 7 deletions command_test.go
Expand Up @@ -162,17 +162,24 @@ func TestSubcommandExecuteC(t *testing.T) {
}

func TestExecuteContext(t *testing.T) {
ctx := context.TODO()
ctx := context.WithValue(context.TODO(), "base", "base")

ctxRun := func(cmd *Command, args []string) {
if cmd.Context() != ctx {
t.Errorf("Command %q must have context when called with ExecuteContext", cmd.Use)
ctxRun := func(name string, testValues ...string) func(*Command, []string) {
return func(cmd *Command, args []string) {
for _, testValue := range testValues {
actual, _ := cmd.Context().Value(testValue).(string)
if actual != testValue {
t.Fatalf("Command %q must have context with value %s, got %s", name, testValue, actual)
}
}

cmd.SetContext(context.WithValue(cmd.Context(), name, name))
}
}

rootCmd := &Command{Use: "root", Run: ctxRun, PreRun: ctxRun}
childCmd := &Command{Use: "child", Run: ctxRun, PreRun: ctxRun}
granchildCmd := &Command{Use: "grandchild", Run: ctxRun, PreRun: ctxRun}
rootCmd := &Command{TraverseChildrenHooks: true, Use: "root", PersistentPreRun: ctxRun("root", "base"), Run: ctxRun("root", "base", "root")}
childCmd := &Command{Use: "child", PersistentPreRun: ctxRun("child", "base", "root", "root"), Run: ctxRun("child", "base", "root", "root", "child")}
granchildCmd := &Command{Use: "grandchild", PersistentPreRun: ctxRun("grandchild", "base", "root", "root", "child", "child"), Run: ctxRun("grandchild", "base", "root", "root", "child", "child", "grandchild")}

childCmd.AddCommand(granchildCmd)
rootCmd.AddCommand(childCmd)
Expand Down

0 comments on commit 817fe94

Please sign in to comment.