Skip to content

Commit c6621bb

Browse files
committed
Cancel context when command finishes
1 parent 71f2c32 commit c6621bb

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

cli/clibase/cmd.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,10 @@ func (i *Invokation) run(state *runState) error {
251251
mw = Chain()
252252
}
253253

254+
ctx, cancel := context.WithCancel(i.Context())
255+
defer cancel()
256+
i = i.WithContext(ctx)
257+
254258
if i.Command.Handler == nil || errors.Is(state.flagParseErr, pflag.ErrHelp) {
255259
if i.Command.HelpHandler == nil {
256260
return xerrors.Errorf("no handler or help for command %s", i.Command.FullName())

cli/clibase/cmd_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package clibase_test
22

33
import (
4+
"context"
45
"strings"
56
"testing"
67

@@ -327,3 +328,25 @@ func TestCommand_HyphenHypen(t *testing.T) {
327328

328329
require.Equal(t, "--verbose --friendly", stdio.Stdout.String())
329330
}
331+
332+
func TestCommand_ContextCancels(t *testing.T) {
333+
t.Parallel()
334+
335+
var gotCtx context.Context
336+
337+
cmd := &clibase.Cmd{
338+
Handler: (func(i *clibase.Invokation) error {
339+
gotCtx = i.Context()
340+
if err := gotCtx.Err(); err != nil {
341+
return xerrors.Errorf("unexpected context error: %w", i.Context().Err())
342+
}
343+
return nil
344+
}),
345+
}
346+
347+
inv, _ := clibasetest.Invoke(cmd)
348+
err := inv.Run()
349+
require.NoError(t, err)
350+
351+
require.Error(t, gotCtx.Err())
352+
}

0 commit comments

Comments
 (0)