Pass context to completion (#1265)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Lukas Malkmus · committed by GitHub · parent 7223a99 · Browse files · 4 files·+94 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+94 added−1 removed
- other:+94 added−1 removed
Provenance
- Commit
6d00909- Tree
3c4a1c1- Author
Lukas Malkmus <lukasmalkmus@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
7223a99
4 files changed+94 added−1 removed
modified:command_test.go+40 added
40 unmodified lines41 42 return c, buf.String(), err43 }44 45+func executeCommandWithContextC(ctx context.Context, root *Command, args ...string) (c *Command, output string, err error) {46+ buf := new(bytes.Buffer)47+ root.SetOut(buf)48+ root.SetErr(buf)49+ root.SetArgs(args)50+51+ c, err = root.ExecuteContextC(ctx)52+53+ return c, buf.String(), err54+}55+56 func resetCommandLineFlagSet() {57 pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)58 }59 128 unmodified lines188 t.Errorf("Command child must not fail: %+v", err)189 }190 }191 192+func TestExecuteContextC(t *testing.T) {193+ ctx := context.TODO()194+195+ ctxRun := func(cmd *Command, args []string) {196+ if cmd.Context() != ctx {197+ t.Errorf("Command %q must have context when called with ExecuteContext", cmd.Use)198+ }199+ }200+201+ rootCmd := &Command{Use: "root", Run: ctxRun, PreRun: ctxRun}202+ childCmd := &Command{Use: "child", Run: ctxRun, PreRun: ctxRun}203+ granchildCmd := &Command{Use: "grandchild", Run: ctxRun, PreRun: ctxRun}204+205+ childCmd.AddCommand(granchildCmd)206+ rootCmd.AddCommand(childCmd)207+208+ if _, _, err := executeCommandWithContextC(ctx, rootCmd, ""); err != nil {209+ t.Errorf("Root command must not fail: %+v", err)210+ }211+212+ if _, _, err := executeCommandWithContextC(ctx, rootCmd, "child"); err != nil {213+ t.Errorf("Subcommand must not fail: %+v", err)214+ }215+216+ if _, _, err := executeCommandWithContextC(ctx, rootCmd, "child", "grandchild"); err != nil {217+ t.Errorf("Command child must not fail: %+v", err)218+ }219+}220+221 func TestExecute_NoContext(t *testing.T) {222 run := func(cmd *Command, args []string) {223 if cmd.Context() != context.Background() {224 t.Errorf("Command %s must have background context", cmd.Use)1836 unmodified linesmodified:command.go+10 added-1 removed
885 unmodified lines886 }887 }888 889 // ExecuteContext is the same as Execute(), but sets the ctx on the command.890-// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle functions.890+// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs891+// functions.892 func (c *Command) ExecuteContext(ctx context.Context) error {893 c.ctx = ctx894 return c.Execute()895 }5 unmodified lines901 _, err := c.ExecuteC()902 return err903 }904 905+// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.906+// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs907+// functions.908+func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {909+ c.ctx = ctx910+ return c.ExecuteC()911+}912+913 // ExecuteC executes the command.914 func (c *Command) ExecuteC() (cmd *Command, err error) {915 if c.ctx == nil {916 c.ctx = context.Background()763 unmodified linesmodified:completions_test.go+43 added
1 package cobra2 3 import (4 "bytes"5+ "context"6 "strings"7 "testing"8 )9 1193 unmodified lines1203 t.Errorf("expected: %q, got: %q", expected, output)1204 }1205 }1206 1207+func TestValidArgsFuncCmdContext(t *testing.T) {1208+ validArgsFunc := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1209+ ctx := cmd.Context()1210+1211+ if ctx == nil {1212+ t.Error("Received nil context in completion func")1213+ } else if ctx.Value("testKey") != "123" {1214+ t.Error("Received invalid context")1215+ }1216+1217+ return nil, ShellCompDirectiveDefault1218+ }1219+1220+ rootCmd := &Command{1221+ Use: "root",1222+ Run: emptyRun,1223+ }1224+ childCmd := &Command{1225+ Use: "childCmd",1226+ ValidArgsFunction: validArgsFunc,1227+ Run: emptyRun,1228+ }1229+ rootCmd.AddCommand(childCmd)1230+1231+ //nolint:golint,staticcheck // We can safely use a basic type as key in tests.1232+ ctx := context.WithValue(context.Background(), "testKey", "123")1233+1234+ // Test completing an empty string on the childCmd1235+ _, output, err := executeCommandWithContextC(ctx, rootCmd, ShellCompNoDescRequestCmd, "childCmd", "")1236+ if err != nil {1237+ t.Errorf("Unexpected error: %v", err)1238+ }1239+1240+ expected := strings.Join([]string{1241+ ":0",1242+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")1243+1244+ if output != expected {1245+ t.Errorf("expected: %q, got: %q", expected, output)1246+ }1247+}1248+1249 func TestValidArgsFuncSingleCmd(t *testing.T) {1250 rootCmd := &Command{1251 Use: "root",1252 ValidArgsFunction: validArgsFunc,951 unmodified linesmodified:completions.go+1 added
219 unmodified lines220 if err != nil {221 // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>222 return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)223 }224+ finalCmd.ctx = c.ctx225 226 // Check if we are doing flag value completion before parsing the flags.227 // This is important because if we are completing a flag value, we need to also228 // remove the flag name argument from the list of finalArgs or else the parsing500 unmodified lines