Skip to content

Commit

Permalink
feat(client): overwrite client context instead of setting new one (co…
Browse files Browse the repository at this point in the history
  • Loading branch information
islishude authored May 14, 2024
1 parent 7ae23e2 commit b2fe0ff
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
13 changes: 8 additions & 5 deletions client/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,14 +359,17 @@ func GetClientContextFromCmd(cmd *cobra.Command) Context {
// SetCmdClientContext sets a command's Context value to the provided argument.
// If the context has not been set, set the given context as the default.
func SetCmdClientContext(cmd *cobra.Command, clientCtx Context) error {
var cmdCtx context.Context

if cmd.Context() == nil {
cmdCtx := cmd.Context()
if cmdCtx == nil {
cmdCtx = context.Background()
}

v := cmd.Context().Value(ClientContextKey)
if clientCtxPtr, ok := v.(*Context); ok {
*clientCtxPtr = clientCtx
} else {
cmdCtx = cmd.Context()
cmd.SetContext(context.WithValue(cmdCtx, ClientContextKey, &clientCtx))
}

cmd.SetContext(context.WithValue(cmdCtx, ClientContextKey, &clientCtx))
return nil
}
26 changes: 23 additions & 3 deletions client/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,21 @@ func TestSetCmdClientContextHandler(t *testing.T) {
name string
expectedContext client.Context
args []string
ctx context.Context
}{
{
"no flags set",
initClientCtx,
[]string{},
context.WithValue(context.Background(), client.ClientContextKey, &client.Context{}),
},
{
"flags set",
initClientCtx.WithChainID("new-chain-id"),
[]string{
fmt.Sprintf("--%s=new-chain-id", flags.FlagChainID),
},
context.WithValue(context.Background(), client.ClientContextKey, &client.Context{}),
},
{
"flags set with space",
Expand All @@ -99,20 +102,37 @@ func TestSetCmdClientContextHandler(t *testing.T) {
fmt.Sprintf("--%s", flags.FlagHome),
"/tmp/dir",
},
context.Background(),
},
{
"no context provided",
initClientCtx.WithHomeDir("/tmp/noctx"),
[]string{
fmt.Sprintf("--%s", flags.FlagHome),
"/tmp/noctx",
},
nil,
},
{
"with invalid client value in the context",
initClientCtx.WithHomeDir("/tmp/invalid"),
[]string{
fmt.Sprintf("--%s", flags.FlagHome),
"/tmp/invalid",
},
context.WithValue(context.Background(), client.ClientContextKey, "invalid"),
},
}

for _, tc := range testCases {
tc := tc

t.Run(tc.name, func(t *testing.T) {
ctx := context.WithValue(context.Background(), client.ClientContextKey, &client.Context{})

cmd := newCmd()
_ = testutil.ApplyMockIODiscardOutErr(cmd)
cmd.SetArgs(tc.args)

require.NoError(t, cmd.ExecuteContext(ctx))
require.NoError(t, cmd.ExecuteContext(tc.ctx))

clientCtx := client.GetClientContextFromCmd(cmd)
require.Equal(t, tc.expectedContext, clientCtx)
Expand Down

0 comments on commit b2fe0ff

Please sign in to comment.