Merge pull request #975 from marwan-at-work/fixctx

add RunWithContext + remove signal cancellation
main
Audrius Butkevicius 5 years ago committed by GitHub
commit 0fae42541a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,6 +1,7 @@
package cli package cli
import ( import (
"context"
"flag" "flag"
"fmt" "fmt"
"io" "io"
@ -207,6 +208,13 @@ func (a *App) useShortOptionHandling() bool {
// Run is the entry point to the cli app. Parses the arguments slice and routes // Run is the entry point to the cli app. Parses the arguments slice and routes
// to the proper flag/args combination // to the proper flag/args combination
func (a *App) Run(arguments []string) (err error) { func (a *App) Run(arguments []string) (err error) {
return a.RunContext(context.Background(), arguments)
}
// RunContext is like Run except it takes a Context that will be
// passed to its commands and sub-commands. Through this, you can
// propagate timeouts and cancellation requests
func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
a.Setup() a.Setup()
// handle the completion flag separately from the flagset since // handle the completion flag separately from the flagset since
@ -224,7 +232,7 @@ func (a *App) Run(arguments []string) (err error) {
err = parseIter(set, a, arguments[1:], shellComplete) err = parseIter(set, a, arguments[1:], shellComplete)
nerr := normalizeFlags(a.Flags, set) nerr := normalizeFlags(a.Flags, set)
context := NewContext(a, set, nil) context := NewContext(a, set, &Context{Context: ctx})
if nerr != nil { if nerr != nil {
_, _ = fmt.Fprintln(a.Writer, nerr) _, _ = fmt.Fprintln(a.Writer, nerr)
_ = ShowAppHelp(context) _ = ShowAppHelp(context)

@ -5,10 +5,7 @@ import (
"errors" "errors"
"flag" "flag"
"fmt" "fmt"
"os"
"os/signal"
"strings" "strings"
"syscall"
) )
// Context is a type that is passed through to // Context is a type that is passed through to
@ -36,14 +33,7 @@ func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
c.Command = &Command{} c.Command = &Command{}
if c.Context == nil { if c.Context == nil {
ctx, cancel := context.WithCancel(context.Background()) c.Context = context.Background()
go func() {
defer cancel()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
<-sigs
}()
c.Context = ctx
} }
return c return c

Loading…
Cancel
Save