mirror of
https://github.com/spf13/cobra
synced 2025-05-06 05:17:21 +00:00
Add minimal Context support to cobra
This commit is contained in:
parent
7c4570c3eb
commit
3cc50a0861
1 changed files with 22 additions and 0 deletions
22
command.go
22
command.go
|
@ -17,12 +17,14 @@ package cobra
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
flag "github.com/spf13/pflag"
|
flag "github.com/spf13/pflag"
|
||||||
)
|
)
|
||||||
|
@ -195,6 +197,10 @@ type Command struct {
|
||||||
helpCommand *Command
|
helpCommand *Command
|
||||||
// versionTemplate is the version template defined by user.
|
// versionTemplate is the version template defined by user.
|
||||||
versionTemplate string
|
versionTemplate string
|
||||||
|
|
||||||
|
// ctx is a standard context.
|
||||||
|
ctx context.Context
|
||||||
|
ctxMu sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
|
// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
|
||||||
|
@ -681,6 +687,8 @@ func (c *Command) execute(a []string) (err error) {
|
||||||
c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
|
c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.ctx = context.Background()
|
||||||
|
|
||||||
// initialize help and version flag at the last point possible to allow for user
|
// initialize help and version flag at the last point possible to allow for user
|
||||||
// overriding
|
// overriding
|
||||||
c.InitDefaultHelpFlag()
|
c.InitDefaultHelpFlag()
|
||||||
|
@ -1515,3 +1523,17 @@ func (c *Command) updateParentsPflags() {
|
||||||
c.parentsPflags.AddFlagSet(parent.PersistentFlags())
|
c.parentsPflags.AddFlagSet(parent.PersistentFlags())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Context returns the command's current context.
|
||||||
|
func (c *Command) Context() context.Context {
|
||||||
|
c.ctxMu.RLock()
|
||||||
|
defer c.ctxMu.RUnlock()
|
||||||
|
return c.ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetContext sets the command's current context.
|
||||||
|
func (c *Command) SetContext(ctx context.Context) {
|
||||||
|
c.ctxMu.Lock()
|
||||||
|
defer c.ctxMu.Unlock()
|
||||||
|
c.ctx = ctx
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue