Document traversal in README

Signed-off-by: Daniel Nephin <dnephin@gmail.com>
This commit is contained in:
Daniel Nephin 2017-10-06 22:11:15 -04:00
parent d34f8d4094
commit f13905cded
2 changed files with 18 additions and 4 deletions

View file

@ -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):

View file

@ -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...), ", ")
}