added a flag to disable flags
This commit is contained in:
parent
f368244301
commit
dc6e9ece6f
10
command.go
10
command.go
@ -120,6 +120,9 @@ type Command struct {
|
||||
DisableSuggestions bool
|
||||
// If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0
|
||||
SuggestionsMinimumDistance int
|
||||
|
||||
// Disable the flag parsing. If this is true all flags will be passed to the command as arguments.
|
||||
DisableFlagParsing bool
|
||||
}
|
||||
|
||||
// os.Args[1:] by default, if desired, can be overridden
|
||||
@ -536,7 +539,11 @@ func (c *Command) execute(a []string) (err error) {
|
||||
}
|
||||
|
||||
c.preRun()
|
||||
|
||||
argWoFlags := c.Flags().Args()
|
||||
if c.DisableFlagParsing {
|
||||
argWoFlags = a
|
||||
}
|
||||
|
||||
for p := c; p != nil; p = p.Parent() {
|
||||
if p.PersistentPreRunE != nil {
|
||||
@ -1167,6 +1174,9 @@ func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
|
||||
|
||||
// ParseFlags parses persistent flag tree & local flags
|
||||
func (c *Command) ParseFlags(args []string) (err error) {
|
||||
if c.DisableFlagParsing {
|
||||
return nil
|
||||
}
|
||||
c.mergePersistentFlags()
|
||||
err = c.Flags().Parse(args)
|
||||
return
|
||||
|
@ -1,6 +1,7 @@
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
@ -112,3 +113,23 @@ func TestStripFlags(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Test_DisableFlagParsing(t *testing.T) {
|
||||
as := []string{"-v", "-race", "-file", "foo.go"}
|
||||
targs := []string{}
|
||||
cmdPrint := &Command{
|
||||
DisableFlagParsing: true,
|
||||
Run: func(cmd *Command, args []string) {
|
||||
targs = args
|
||||
},
|
||||
}
|
||||
osargs := []string{"cmd"}
|
||||
os.Args = append(osargs, as...)
|
||||
err := cmdPrint.Execute()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if !reflect.DeepEqual(as, targs) {
|
||||
t.Errorf("expected: %v, got: %v", as, targs)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user