File tree Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -251,6 +251,10 @@ func (i *Invokation) run(state *runState) error {
251
251
mw = Chain ()
252
252
}
253
253
254
+ ctx , cancel := context .WithCancel (i .Context ())
255
+ defer cancel ()
256
+ i = i .WithContext (ctx )
257
+
254
258
if i .Command .Handler == nil || errors .Is (state .flagParseErr , pflag .ErrHelp ) {
255
259
if i .Command .HelpHandler == nil {
256
260
return xerrors .Errorf ("no handler or help for command %s" , i .Command .FullName ())
Original file line number Diff line number Diff line change 1
1
package clibase_test
2
2
3
3
import (
4
+ "context"
4
5
"strings"
5
6
"testing"
6
7
@@ -327,3 +328,25 @@ func TestCommand_HyphenHypen(t *testing.T) {
327
328
328
329
require .Equal (t , "--verbose --friendly" , stdio .Stdout .String ())
329
330
}
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
+ }
You can’t perform that action at this time.
0 commit comments