diff --git a/README.md b/README.md index 7b00a024..a29834d6 100644 --- a/README.md +++ b/README.md @@ -344,6 +344,19 @@ A flag can also be assigned locally which will only apply to that specific comma RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") ``` +### Local Flag on Parent Commands + +By default Cobra only parses local flags on the target command, any local flags on +parent commands are ignored. By enabling `Command.TraverseChildren` Cobra will +parse local flags on each command before executing the target command. + +```go +command := cobra.Command{ + Use: "print [OPTIONS] [COMMANDS]", + TraverseChildren: true, +} +``` + ### Bind Flags with Config You can also bind your flags with [viper](https://github.com/spf13/viper): diff --git a/command.go b/command.go index d90cf7f3..a23bb6d9 100644 --- a/command.go +++ b/command.go @@ -125,7 +125,7 @@ type Command struct { // Must be > 0. SuggestionsMinimumDistance int - // TraverseChildren parses flags on all parents before executing child command + // TraverseChildren parses flags on all parents before executing child command. TraverseChildren bool // name is the command name, usually the executable's name. @@ -532,7 +532,7 @@ func (c *Command) findNext(next string) *Command { if cmd.Name() == next || cmd.HasAlias(next) { return cmd } - if EnablePrefixMatching && cmd.HasNameOrAliasPrefix(next) { + if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) { matches = append(matches, cmd) } } @@ -1046,9 +1046,9 @@ func (c *Command) HasAlias(s string) bool { return false } -// HasNameOrAliasPrefix returns true if the Name or any of aliases start +// hasNameOrAliasPrefix returns true if the Name or any of aliases start // with prefix -func (c *Command) HasNameOrAliasPrefix(prefix string) bool { +func (c *Command) hasNameOrAliasPrefix(prefix string) bool { if strings.HasPrefix(c.Name(), prefix) { return true } @@ -1060,6 +1060,7 @@ func (c *Command) HasNameOrAliasPrefix(prefix string) bool { return false } +// NameAndAliases returns a list of the command name and all aliases func (c *Command) NameAndAliases() string { return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") }