command.go
This file
Path
command.go
1,197 lines · 31.1 KiB · Go
Last changed by
always show help if requested, even if SilenceErrors is enabledSascha Holzleiterbefore adoption2bd8a73
History of this fileTake it
1// Copyright © 2013 Steve Francia <spf@spf13.com>.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314//Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.15//In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.16package cobra1718import (19 "bytes"20 "fmt"21 "io"22 "os"23 "path/filepath"24 "strings"2526 flag "github.com/spf13/pflag"27)2829// Command is just that, a command for your application.30// eg. 'go run' ... 'run' is the command. Cobra requires31// you to define the usage and description as part of your command32// definition to ensure usability.33type Command struct {34 // Name is the command name, usually the executable's name.35 name string36 // The one-line usage message.37 Use string38 // An array of aliases that can be used instead of the first word in Use.39 Aliases []string40 // An array of command names for which this command will be suggested - similar to aliases but only suggests.41 SuggestFor []string42 // The short description shown in the 'help' output.43 Short string44 // The long message shown in the 'help <this-command>' output.45 Long string46 // Examples of how to use the command47 Example string48 // List of all valid non-flag arguments, used for bash completions *TODO* actually validate these49 ValidArgs []string50 // Custom functions used by the bash autocompletion generator51 BashCompletionFunction string52 // Is this command deprecated and should print this string when used?53 Deprecated string54 // Is this command hidden and should NOT show up in the list of available commands?55 Hidden bool56 // Full set of flags57 flags *flag.FlagSet58 // Set of flags childrens of this command will inherit59 pflags *flag.FlagSet60 // Flags that are declared specifically by this command (not inherited).61 lflags *flag.FlagSet62 // SilenceErrors is an option to quiet errors down stream63 SilenceErrors bool64 // Silence Usage is an option to silence usage when an error occurs.65 SilenceUsage bool66 // The *Run functions are executed in the following order:67 // * PersistentPreRun()68 // * PreRun()69 // * Run()70 // * PostRun()71 // * PersistentPostRun()72 // All functions get the same args, the arguments after the command name73 // PersistentPreRun: children of this command will inherit and execute74 PersistentPreRun func(cmd *Command, args []string)75 // PersistentPreRunE: PersistentPreRun but returns an error76 PersistentPreRunE func(cmd *Command, args []string) error77 // PreRun: children of this command will not inherit.78 PreRun func(cmd *Command, args []string)79 // PreRunE: PreRun but returns an error80 PreRunE func(cmd *Command, args []string) error81 // Run: Typically the actual work function. Most commands will only implement this82 Run func(cmd *Command, args []string)83 // RunE: Run but returns an error84 RunE func(cmd *Command, args []string) error85 // PostRun: run after the Run command.86 PostRun func(cmd *Command, args []string)87 // PostRunE: PostRun but returns an error88 PostRunE func(cmd *Command, args []string) error89 // PersistentPostRun: children of this command will inherit and execute after PostRun90 PersistentPostRun func(cmd *Command, args []string)91 // PersistentPostRunE: PersistentPostRun but returns an error92 PersistentPostRunE func(cmd *Command, args []string) error93 // DisableAutoGenTag remove94 DisableAutoGenTag bool95 // Commands is the list of commands supported by this program.96 commands []*Command97 // Parent Command for this command98 parent *Command99 // max lengths of commands' string lengths for use in padding100 commandsMaxUseLen int101 commandsMaxCommandPathLen int102 commandsMaxNameLen int103104 flagErrorBuf *bytes.Buffer105106 args []string // actual args parsed from flags107 output *io.Writer // nil means stderr; use Out() method instead108 usageFunc func(*Command) error // Usage can be defined by application109 usageTemplate string // Can be defined by Application110 helpTemplate string // Can be defined by Application111 helpFunc func(*Command, []string) // Help can be defined by application112 helpCommand *Command // The help command113 // The global normalization function that we can use on every pFlag set and children commands114 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName115116 // Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages117 DisableSuggestions bool118 // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0119 SuggestionsMinimumDistance int120}121122// os.Args[1:] by default, if desired, can be overridden123// particularly useful when testing.124func (c *Command) SetArgs(a []string) {125 c.args = a126}127128func (c *Command) getOut(def io.Writer) io.Writer {129 if c.output != nil {130 return *c.output131 }132133 if c.HasParent() {134 return c.parent.Out()135 } else {136 return def137 }138}139140func (c *Command) Out() io.Writer {141 return c.getOut(os.Stderr)142}143144func (c *Command) getOutOrStdout() io.Writer {145 return c.getOut(os.Stdout)146}147148// SetOutput sets the destination for usage and error messages.149// If output is nil, os.Stderr is used.150func (c *Command) SetOutput(output io.Writer) {151 c.output = &output152}153154// Usage can be defined by application155func (c *Command) SetUsageFunc(f func(*Command) error) {156 c.usageFunc = f157}158159// Can be defined by Application160func (c *Command) SetUsageTemplate(s string) {161 c.usageTemplate = s162}163164// Can be defined by Application165func (c *Command) SetHelpFunc(f func(*Command, []string)) {166 c.helpFunc = f167}168169func (c *Command) SetHelpCommand(cmd *Command) {170 c.helpCommand = cmd171}172173// Can be defined by Application174func (c *Command) SetHelpTemplate(s string) {175 c.helpTemplate = s176}177178// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.179// The user should not have a cyclic dependency on commands.180func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {181 c.Flags().SetNormalizeFunc(n)182 c.PersistentFlags().SetNormalizeFunc(n)183 c.globNormFunc = n184185 for _, command := range c.commands {186 command.SetGlobalNormalizationFunc(n)187 }188}189190func (c *Command) UsageFunc() (f func(*Command) error) {191 if c.usageFunc != nil {192 return c.usageFunc193 }194195 if c.HasParent() {196 return c.parent.UsageFunc()197 } else {198 return func(c *Command) error {199 err := tmpl(c.Out(), c.UsageTemplate(), c)200 if err != nil {201 fmt.Print(err)202 }203 return err204 }205 }206}207208// HelpFunc returns either the function set by SetHelpFunc for this command209// or a parent, or it returns a function which calls c.Help()210func (c *Command) HelpFunc() func(*Command, []string) {211 cmd := c212 for cmd != nil {213 if cmd.helpFunc != nil {214 return cmd.helpFunc215 }216 cmd = cmd.parent217 }218 return func(*Command, []string) {219 err := c.Help()220 if err != nil {221 c.Println(err)222 }223 }224}225226var minUsagePadding int = 25227228func (c *Command) UsagePadding() int {229 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {230 return minUsagePadding231 } else {232 return c.parent.commandsMaxUseLen233 }234}235236var minCommandPathPadding int = 11237238//239func (c *Command) CommandPathPadding() int {240 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {241 return minCommandPathPadding242 } else {243 return c.parent.commandsMaxCommandPathLen244 }245}246247var minNamePadding int = 11248249func (c *Command) NamePadding() int {250 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {251 return minNamePadding252 } else {253 return c.parent.commandsMaxNameLen254 }255}256257func (c *Command) UsageTemplate() string {258 if c.usageTemplate != "" {259 return c.usageTemplate260 }261262 if c.HasParent() {263 return c.parent.UsageTemplate()264 } else {265 return `Usage:{{if .Runnable}}266 {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}267 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}268269Aliases:270 {{.NameAndAliases}}271{{end}}{{if .HasExample}}272273Examples:274{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}275276Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}277 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}}278279Flags:280{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasInheritedFlags}}281282Global Flags:283{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}284285Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}286 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}287288Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}289`290 }291}292293func (c *Command) HelpTemplate() string {294 if c.helpTemplate != "" {295 return c.helpTemplate296 }297298 if c.HasParent() {299 return c.parent.HelpTemplate()300 } else {301 return `{{with or .Long .Short }}{{. | trim}}302303{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`304 }305}306307// Really only used when casting a command to a commander308func (c *Command) resetChildrensParents() {309 for _, x := range c.commands {310 x.parent = c311 }312}313314// Test if the named flag is a boolean flag.315func isBooleanFlag(name string, f *flag.FlagSet) bool {316 flag := f.Lookup(name)317 if flag == nil {318 return false319 }320 return flag.Value.Type() == "bool"321}322323// Test if the named flag is a boolean flag.324func isBooleanShortFlag(name string, f *flag.FlagSet) bool {325 result := false326 f.VisitAll(func(f *flag.Flag) {327 if f.Shorthand == name && f.Value.Type() == "bool" {328 result = true329 }330 })331 return result332}333334func stripFlags(args []string, c *Command) []string {335 if len(args) < 1 {336 return args337 }338 c.mergePersistentFlags()339340 commands := []string{}341342 inQuote := false343 inFlag := false344 for _, y := range args {345 if !inQuote {346 switch {347 case strings.HasPrefix(y, "\""):348 inQuote = true349 case strings.Contains(y, "=\""):350 inQuote = true351 case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):352 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'353 inFlag = !isBooleanFlag(y[2:], c.Flags())354 case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):355 inFlag = true356 case inFlag:357 inFlag = false358 case y == "":359 // strip empty commands, as the go tests expect this to be ok....360 case !strings.HasPrefix(y, "-"):361 commands = append(commands, y)362 inFlag = false363 }364 }365366 if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {367 inQuote = false368 }369 }370371 return commands372}373374// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like375// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).376func argsMinusFirstX(args []string, x string) []string {377 for i, y := range args {378 if x == y {379 ret := []string{}380 ret = append(ret, args[:i]...)381 ret = append(ret, args[i+1:]...)382 return ret383 }384 }385 return args386}387388// find the target command given the args and command tree389// Meant to be run on the highest node. Only searches down.390func (c *Command) Find(args []string) (*Command, []string, error) {391 if c == nil {392 return nil, nil, fmt.Errorf("Called find() on a nil Command")393 }394395 var innerfind func(*Command, []string) (*Command, []string)396397 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {398 argsWOflags := stripFlags(innerArgs, c)399 if len(argsWOflags) == 0 {400 return c, innerArgs401 }402 nextSubCmd := argsWOflags[0]403 matches := make([]*Command, 0)404 for _, cmd := range c.commands {405 if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match406 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))407 }408 if EnablePrefixMatching {409 if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match410 matches = append(matches, cmd)411 }412 for _, x := range cmd.Aliases {413 if strings.HasPrefix(x, nextSubCmd) {414 matches = append(matches, cmd)415 }416 }417 }418 }419420 // only accept a single prefix match - multiple matches would be ambiguous421 if len(matches) == 1 {422 return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))423 }424425 return c, innerArgs426 }427428 commandFound, a := innerfind(c, args)429 argsWOflags := stripFlags(a, commandFound)430431 // no subcommand, always take args432 if !commandFound.HasSubCommands() {433 return commandFound, a, nil434 }435436 // root command with subcommands, do subcommand checking437 if commandFound == c && len(argsWOflags) > 0 {438 suggestionsString := ""439 if !c.DisableSuggestions {440 if c.SuggestionsMinimumDistance <= 0 {441 c.SuggestionsMinimumDistance = 2442 }443 if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {444 suggestionsString += "\n\nDid you mean this?\n"445 for _, s := range suggestions {446 suggestionsString += fmt.Sprintf("\t%v\n", s)447 }448 }449 }450 return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)451 }452453 return commandFound, a, nil454}455456func (c *Command) SuggestionsFor(typedName string) []string {457 suggestions := []string{}458 for _, cmd := range c.commands {459 if cmd.IsAvailableCommand() {460 levenshteinDistance := ld(typedName, cmd.Name(), true)461 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance462 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))463 if suggestByLevenshtein || suggestByPrefix {464 suggestions = append(suggestions, cmd.Name())465 }466 for _, explicitSuggestion := range cmd.SuggestFor {467 if strings.EqualFold(typedName, explicitSuggestion) {468 suggestions = append(suggestions, cmd.Name())469 }470 }471 }472 }473 return suggestions474}475476func (c *Command) VisitParents(fn func(*Command)) {477 var traverse func(*Command) *Command478479 traverse = func(x *Command) *Command {480 if x != c {481 fn(x)482 }483 if x.HasParent() {484 return traverse(x.parent)485 }486 return x487 }488 traverse(c)489}490491func (c *Command) Root() *Command {492 var findRoot func(*Command) *Command493494 findRoot = func(x *Command) *Command {495 if x.HasParent() {496 return findRoot(x.parent)497 }498 return x499 }500501 return findRoot(c)502}503504// ArgsLenAtDash will return the length of f.Args at the moment when a -- was505// found during arg parsing. This allows your program to know which args were506// before the -- and which came after. (Description from507// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).508func (c *Command) ArgsLenAtDash() int {509 return c.Flags().ArgsLenAtDash()510}511512func (c *Command) execute(a []string) (err error) {513 if c == nil {514 return fmt.Errorf("Called Execute() on a nil Command")515 }516517 if len(c.Deprecated) > 0 {518 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)519 }520521 // initialize help flag as the last point possible to allow for user522 // overriding523 c.initHelpFlag()524525 err = c.ParseFlags(a)526 if err != nil {527 return err528 }529 // If help is called, regardless of other flags, return we want help530 // Also say we need help if the command isn't runnable.531 helpVal, err := c.Flags().GetBool("help")532 if err != nil {533 // should be impossible to get here as we always declare a help534 // flag in initHelpFlag()535 c.Println("\"help\" flag declared as non-bool. Please correct your code")536 return err537 }538 if helpVal || !c.Runnable() {539 return flag.ErrHelp540 }541542 c.preRun()543 argWoFlags := c.Flags().Args()544545 for p := c; p != nil; p = p.Parent() {546 if p.PersistentPreRunE != nil {547 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {548 return err549 }550 break551 } else if p.PersistentPreRun != nil {552 p.PersistentPreRun(c, argWoFlags)553 break554 }555 }556 if c.PreRunE != nil {557 if err := c.PreRunE(c, argWoFlags); err != nil {558 return err559 }560 } else if c.PreRun != nil {561 c.PreRun(c, argWoFlags)562 }563564 if c.RunE != nil {565 if err := c.RunE(c, argWoFlags); err != nil {566 return err567 }568 } else {569 c.Run(c, argWoFlags)570 }571 if c.PostRunE != nil {572 if err := c.PostRunE(c, argWoFlags); err != nil {573 return err574 }575 } else if c.PostRun != nil {576 c.PostRun(c, argWoFlags)577 }578 for p := c; p != nil; p = p.Parent() {579 if p.PersistentPostRunE != nil {580 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {581 return err582 }583 break584 } else if p.PersistentPostRun != nil {585 p.PersistentPostRun(c, argWoFlags)586 break587 }588 }589590 return nil591}592593func (c *Command) preRun() {594 for _, x := range initializers {595 x()596 }597}598599func (c *Command) errorMsgFromParse() string {600 s := c.flagErrorBuf.String()601602 x := strings.Split(s, "\n")603604 if len(x) > 0 {605 return x[0]606 } else {607 return ""608 }609}610611// Call execute to use the args (os.Args[1:] by default)612// and run through the command tree finding appropriate matches613// for commands and then corresponding flags.614func (c *Command) Execute() error {615 _, err := c.ExecuteC()616 return err617}618619func (c *Command) ExecuteC() (cmd *Command, err error) {620621 // Regardless of what command execute is called on, run on Root only622 if c.HasParent() {623 return c.Root().ExecuteC()624 }625626 // windows hook627 if preExecHookFn != nil {628 preExecHookFn(c)629 }630631 // initialize help as the last point possible to allow for user632 // overriding633 c.initHelpCmd()634635 var args []string636637 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155638 if len(c.args) == 0 && filepath.Base(os.Args[0]) != "cobra.test" {639 args = os.Args[1:]640 } else {641 args = c.args642 }643644 cmd, flags, err := c.Find(args)645 if err != nil {646 // If found parse to a subcommand and then failed, talk about the subcommand647 if cmd != nil {648 c = cmd649 }650 if !c.SilenceErrors {651 c.Println("Error:", err.Error())652 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())653 }654 return c, err655 }656 err = cmd.execute(flags)657 if err != nil {658 // Always show help if requested, even if SilenceErrors is in659 // effect660 if err == flag.ErrHelp {661 cmd.HelpFunc()(cmd, args)662 return cmd, nil663 }664665 // If root command has SilentErrors flagged,666 // all subcommands should respect it667 if !cmd.SilenceErrors && !c.SilenceErrors {668 c.Println("Error:", err.Error())669 }670671 // If root command has SilentUsage flagged,672 // all subcommands should respect it673 if !cmd.SilenceUsage && !c.SilenceUsage {674 c.Println(cmd.UsageString())675 }676 return cmd, err677 }678 return cmd, nil679}680681func (c *Command) initHelpFlag() {682 if c.Flags().Lookup("help") == nil {683 c.Flags().BoolP("help", "h", false, "help for "+c.Name())684 }685}686687func (c *Command) initHelpCmd() {688 if c.helpCommand == nil {689 if !c.HasSubCommands() {690 return691 }692693 c.helpCommand = &Command{694 Use: "help [command]",695 Short: "Help about any command",696 Long: `Help provides help for any command in the application.697 Simply type ` + c.Name() + ` help [path to command] for full details.`,698 PersistentPreRun: func(cmd *Command, args []string) {},699 PersistentPostRun: func(cmd *Command, args []string) {},700701 Run: func(c *Command, args []string) {702 cmd, _, e := c.Root().Find(args)703 if cmd == nil || e != nil {704 c.Printf("Unknown help topic %#q.", args)705 c.Root().Usage()706 } else {707 helpFunc := cmd.HelpFunc()708 helpFunc(cmd, args)709 }710 },711 }712 }713 c.AddCommand(c.helpCommand)714}715716// Used for testing717func (c *Command) ResetCommands() {718 c.commands = nil719 c.helpCommand = nil720}721722//Commands returns a slice of child commands.723func (c *Command) Commands() []*Command {724 return c.commands725}726727// AddCommand adds one or more commands to this parent command.728func (c *Command) AddCommand(cmds ...*Command) {729 for i, x := range cmds {730 if cmds[i] == c {731 panic("Command can't be a child of itself")732 }733 cmds[i].parent = c734 // update max lengths735 usageLen := len(x.Use)736 if usageLen > c.commandsMaxUseLen {737 c.commandsMaxUseLen = usageLen738 }739 commandPathLen := len(x.CommandPath())740 if commandPathLen > c.commandsMaxCommandPathLen {741 c.commandsMaxCommandPathLen = commandPathLen742 }743 nameLen := len(x.Name())744 if nameLen > c.commandsMaxNameLen {745 c.commandsMaxNameLen = nameLen746 }747 // If global normalization function exists, update all children748 if c.globNormFunc != nil {749 x.SetGlobalNormalizationFunc(c.globNormFunc)750 }751 c.commands = append(c.commands, x)752 }753}754755// AddCommand removes one or more commands from a parent command.756func (c *Command) RemoveCommand(cmds ...*Command) {757 commands := []*Command{}758main:759 for _, command := range c.commands {760 for _, cmd := range cmds {761 if command == cmd {762 command.parent = nil763 continue main764 }765 }766 commands = append(commands, command)767 }768 c.commands = commands769 // recompute all lengths770 c.commandsMaxUseLen = 0771 c.commandsMaxCommandPathLen = 0772 c.commandsMaxNameLen = 0773 for _, command := range c.commands {774 usageLen := len(command.Use)775 if usageLen > c.commandsMaxUseLen {776 c.commandsMaxUseLen = usageLen777 }778 commandPathLen := len(command.CommandPath())779 if commandPathLen > c.commandsMaxCommandPathLen {780 c.commandsMaxCommandPathLen = commandPathLen781 }782 nameLen := len(command.Name())783 if nameLen > c.commandsMaxNameLen {784 c.commandsMaxNameLen = nameLen785 }786 }787}788789// Convenience method to Print to the defined output790func (c *Command) Print(i ...interface{}) {791 fmt.Fprint(c.Out(), i...)792}793794// Convenience method to Println to the defined output795func (c *Command) Println(i ...interface{}) {796 str := fmt.Sprintln(i...)797 c.Print(str)798}799800// Convenience method to Printf to the defined output801func (c *Command) Printf(format string, i ...interface{}) {802 str := fmt.Sprintf(format, i...)803 c.Print(str)804}805806// Output the usage for the command807// Used when a user provides invalid input808// Can be defined by user by overriding UsageFunc809func (c *Command) Usage() error {810 c.mergePersistentFlags()811 err := c.UsageFunc()(c)812 return err813}814815// Output the help for the command816// Used when a user calls help [command]817// by the default HelpFunc in the commander818func (c *Command) Help() error {819 c.mergePersistentFlags()820 err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)821 return err822}823824func (c *Command) UsageString() string {825 tmpOutput := c.output826 bb := new(bytes.Buffer)827 c.SetOutput(bb)828 c.Usage()829 c.output = tmpOutput830 return bb.String()831}832833// CommandPath returns the full path to this command.834func (c *Command) CommandPath() string {835 str := c.Name()836 x := c837 for x.HasParent() {838 str = x.parent.Name() + " " + str839 x = x.parent840 }841 return str842}843844//The full usage for a given command (including parents)845func (c *Command) UseLine() string {846 str := ""847 if c.HasParent() {848 str = c.parent.CommandPath() + " "849 }850 return str + c.Use851}852853// For use in determining which flags have been assigned to which commands854// and which persist855func (c *Command) DebugFlags() {856 c.Println("DebugFlags called on", c.Name())857 var debugflags func(*Command)858859 debugflags = func(x *Command) {860 if x.HasFlags() || x.HasPersistentFlags() {861 c.Println(x.Name())862 }863 if x.HasFlags() {864 x.flags.VisitAll(func(f *flag.Flag) {865 if x.HasPersistentFlags() {866 if x.persistentFlag(f.Name) == nil {867 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")868 } else {869 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")870 }871 } else {872 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")873 }874 })875 }876 if x.HasPersistentFlags() {877 x.pflags.VisitAll(func(f *flag.Flag) {878 if x.HasFlags() {879 if x.flags.Lookup(f.Name) == nil {880 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")881 }882 } else {883 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")884 }885 })886 }887 c.Println(x.flagErrorBuf)888 if x.HasSubCommands() {889 for _, y := range x.commands {890 debugflags(y)891 }892 }893 }894895 debugflags(c)896}897898// Name returns the command's name: the first word in the use line.899func (c *Command) Name() string {900 if c.name != "" {901 return c.name902 }903 name := c.Use904 i := strings.Index(name, " ")905 if i >= 0 {906 name = name[:i]907 }908 return name909}910911// Determine if a given string is an alias of the command.912func (c *Command) HasAlias(s string) bool {913 for _, a := range c.Aliases {914 if a == s {915 return true916 }917 }918 return false919}920921func (c *Command) NameAndAliases() string {922 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")923}924925func (c *Command) HasExample() bool {926 return len(c.Example) > 0927}928929// Determine if the command is itself runnable930func (c *Command) Runnable() bool {931 return c.Run != nil || c.RunE != nil932}933934// Determine if the command has children commands935func (c *Command) HasSubCommands() bool {936 return len(c.commands) > 0937}938939// IsAvailableCommand determines if a command is available as a non-help command940// (this includes all non deprecated/hidden commands)941func (c *Command) IsAvailableCommand() bool {942 if len(c.Deprecated) != 0 || c.Hidden {943 return false944 }945946 if c.HasParent() && c.Parent().helpCommand == c {947 return false948 }949950 if c.Runnable() || c.HasAvailableSubCommands() {951 return true952 }953954 return false955}956957// IsHelpCommand determines if a command is a 'help' command; a help command is958// determined by the fact that it is NOT runnable/hidden/deprecated, and has no959// sub commands that are runnable/hidden/deprecated960func (c *Command) IsHelpCommand() bool {961962 // if a command is runnable, deprecated, or hidden it is not a 'help' command963 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {964 return false965 }966967 // if any non-help sub commands are found, the command is not a 'help' command968 for _, sub := range c.commands {969 if !sub.IsHelpCommand() {970 return false971 }972 }973974 // the command either has no sub commands, or no non-help sub commands975 return true976}977978// HasHelpSubCommands determines if a command has any avilable 'help' sub commands979// that need to be shown in the usage/help default template under 'additional help980// topics'981func (c *Command) HasHelpSubCommands() bool {982983 // return true on the first found available 'help' sub command984 for _, sub := range c.commands {985 if sub.IsHelpCommand() {986 return true987 }988 }989990 // the command either has no sub commands, or no available 'help' sub commands991 return false992}993994// HasAvailableSubCommands determines if a command has available sub commands that995// need to be shown in the usage/help default template under 'available commands'996func (c *Command) HasAvailableSubCommands() bool {997998 // return true on the first found available (non deprecated/help/hidden)999 // sub command1000 for _, sub := range c.commands {1001 if sub.IsAvailableCommand() {1002 return true1003 }1004 }10051006 // the command either has no sub comamnds, or no available (non deprecated/help/hidden)1007 // sub commands1008 return false1009}10101011// Determine if the command is a child command1012func (c *Command) HasParent() bool {1013 return c.parent != nil1014}10151016// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists1017func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1018 return c.globNormFunc1019}10201021// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)1022func (c *Command) Flags() *flag.FlagSet {1023 if c.flags == nil {1024 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1025 if c.flagErrorBuf == nil {1026 c.flagErrorBuf = new(bytes.Buffer)1027 }1028 c.flags.SetOutput(c.flagErrorBuf)1029 }1030 return c.flags1031}10321033// Get the local FlagSet specifically set in the current command1034func (c *Command) LocalFlags() *flag.FlagSet {1035 c.mergePersistentFlags()10361037 local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1038 c.lflags.VisitAll(func(f *flag.Flag) {1039 local.AddFlag(f)1040 })1041 if !c.HasParent() {1042 flag.CommandLine.VisitAll(func(f *flag.Flag) {1043 if local.Lookup(f.Name) == nil {1044 local.AddFlag(f)1045 }1046 })1047 }1048 return local1049}10501051// All Flags which were inherited from parents commands1052func (c *Command) InheritedFlags() *flag.FlagSet {1053 c.mergePersistentFlags()10541055 inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1056 local := c.LocalFlags()10571058 var rmerge func(x *Command)10591060 rmerge = func(x *Command) {1061 if x.HasPersistentFlags() {1062 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1063 if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1064 inherited.AddFlag(f)1065 }1066 })1067 }1068 if x.HasParent() {1069 rmerge(x.parent)1070 }1071 }10721073 if c.HasParent() {1074 rmerge(c.parent)1075 }10761077 return inherited1078}10791080// All Flags which were not inherited from parent commands1081func (c *Command) NonInheritedFlags() *flag.FlagSet {1082 return c.LocalFlags()1083}10841085// Get the Persistent FlagSet specifically set in the current command1086func (c *Command) PersistentFlags() *flag.FlagSet {1087 if c.pflags == nil {1088 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1089 if c.flagErrorBuf == nil {1090 c.flagErrorBuf = new(bytes.Buffer)1091 }1092 c.pflags.SetOutput(c.flagErrorBuf)1093 }1094 return c.pflags1095}10961097// For use in testing1098func (c *Command) ResetFlags() {1099 c.flagErrorBuf = new(bytes.Buffer)1100 c.flagErrorBuf.Reset()1101 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1102 c.flags.SetOutput(c.flagErrorBuf)1103 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1104 c.pflags.SetOutput(c.flagErrorBuf)1105}11061107// Does the command contain any flags (local plus persistent from the entire structure)1108func (c *Command) HasFlags() bool {1109 return c.Flags().HasFlags()1110}11111112// Does the command contain persistent flags1113func (c *Command) HasPersistentFlags() bool {1114 return c.PersistentFlags().HasFlags()1115}11161117// Does the command has flags specifically declared locally1118func (c *Command) HasLocalFlags() bool {1119 return c.LocalFlags().HasFlags()1120}11211122func (c *Command) HasInheritedFlags() bool {1123 return c.InheritedFlags().HasFlags()1124}11251126// Climbs up the command tree looking for matching flag1127func (c *Command) Flag(name string) (flag *flag.Flag) {1128 flag = c.Flags().Lookup(name)11291130 if flag == nil {1131 flag = c.persistentFlag(name)1132 }11331134 return1135}11361137// recursively find matching persistent flag1138func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1139 if c.HasPersistentFlags() {1140 flag = c.PersistentFlags().Lookup(name)1141 }11421143 if flag == nil && c.HasParent() {1144 flag = c.parent.persistentFlag(name)1145 }1146 return1147}11481149// Parses persistent flag tree & local flags1150func (c *Command) ParseFlags(args []string) (err error) {1151 c.mergePersistentFlags()1152 err = c.Flags().Parse(args)1153 return1154}11551156func (c *Command) Parent() *Command {1157 return c.parent1158}11591160func (c *Command) mergePersistentFlags() {1161 var rmerge func(x *Command)11621163 // Save the set of local flags1164 if c.lflags == nil {1165 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)1166 if c.flagErrorBuf == nil {1167 c.flagErrorBuf = new(bytes.Buffer)1168 }1169 c.lflags.SetOutput(c.flagErrorBuf)1170 addtolocal := func(f *flag.Flag) {1171 c.lflags.AddFlag(f)1172 }1173 c.Flags().VisitAll(addtolocal)1174 c.PersistentFlags().VisitAll(addtolocal)1175 }1176 rmerge = func(x *Command) {1177 if !x.HasParent() {1178 flag.CommandLine.VisitAll(func(f *flag.Flag) {1179 if x.PersistentFlags().Lookup(f.Name) == nil {1180 x.PersistentFlags().AddFlag(f)1181 }1182 })1183 }1184 if x.HasPersistentFlags() {1185 x.PersistentFlags().VisitAll(func(f *flag.Flag) {1186 if c.Flags().Lookup(f.Name) == nil {1187 c.Flags().AddFlag(f)1188 }1189 })1190 }1191 if x.HasParent() {1192 rmerge(x.parent)1193 }1194 }11951196 rmerge(c)1197}