command.go
This file
Path
command.go
1,411 lines · 38.9 KiB · Go
Last changed by
enforce required flags (#502)Di Xubefore adoption4d6af28
History of this fileTake it
The walk stopped after 200 commits: lines older than 65a708c point at it.
Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1–13why, one step back1// 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.13Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41
lines 14–15why, one step back14// 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.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 16–23why, one step back16package cobra1718import (19 "bytes"20 "fmt"21 "io"22 "os"23 "path/filepath"Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
line 24why, one step back24 "sort"Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 25–30why, one step back25 "strings"2627 flag "github.com/spf13/pflag"28)2930// Command is just that, a command for your application.Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 31why, one step back31// E.g. 'go run ...' - 'run' is the command. Cobra requiresAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 32–34why, one step back32// you to define the usage and description as part of your command33// definition to ensure usability.34type Command struct {Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 35why, one step back35 // Use is the one-line usage message.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 36why, one step back36 Use stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 37why, one step back37Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 38why, one step back38 // Aliases is an array of aliases that can be used instead of the first word in Use.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 39why, one step back39 Aliases []stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 40why, one step back40Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
lines 41–42why, one step back41 // SuggestFor is an array of command names for which this command will be suggested -42 // similar to aliases but only suggests.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 43why, one step back43 SuggestFor []stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 44why, one step back44Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 45why, one step back45 // Short is the short description shown in the 'help' output.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 46why, one step back46 Short stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 47why, one step back47Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 48why, one step back48 // Long is the long message shown in the 'help <this-command>' output.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 49why, one step back49 Long stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 50why, one step back50Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 51why, one step back51 // Example is examples of how to use the command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 52why, one step back52 Example stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 53why, one step back53Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 54why, one step back54 // ValidArgs is list of all valid non-flag arguments that are accepted in bash completionsAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 55why, one step back55 ValidArgs []stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 56why, one step back56Update documentationAlbert Nigmatzianovbefore adoption1723331
lines 57–59why, one step back57 // Expected arguments58 Args PositionalArgs59Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
lines 60–62why, one step back60 // ArgAliases is List of aliases for ValidArgs.61 // These are not suggested to the user in the bash completion,62 // but accepted if entered manually.Merge pull request #257 from sttts/sttts-noun-aliasesEric Parisbefore adoption60267ae
line 63why, one step back63 ArgAliases []stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 64why, one step back64Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 65why, one step back65 // BashCompletionFunction is custom functions used by the bash autocompletion generator.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 66why, one step back66 BashCompletionFunction stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 67why, one step back67Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8
line 68why, one step back68 // Deprecated defines, if this command is deprecated and should print this string when used.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 69why, one step back69 Deprecated stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 70why, one step back70Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8
line 71why, one step back71 // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 72why, one step back72 Hidden boolDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 73why, one step back73Add a tags field for user defined tags on a Command. (#359)Daniel Nephinbefore adoption99600f6
line 74why, one step back74 // Annotations are key/value pairs that can be used by applications to identify orFix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 75why, one step back75 // group commands.Add a tags field for user defined tags on a Command. (#359)Daniel Nephinbefore adoption99600f6
line 76why, one step back76 Annotations map[string]stringDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 77why, one step back77Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 78–83why, one step back78 // The *Run functions are executed in the following order:79 // * PersistentPreRun()80 // * PreRun()81 // * Run()82 // * PostRun()83 // * PersistentPostRun()Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 84why, one step back84 // All functions get the same args, the arguments after the command name.Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 85why, one step back85 //Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 86why, one step back86 // PersistentPreRun: children of this command will inherit and execute.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 87why, one step back87 PersistentPreRun func(cmd *Command, args []string)Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 88why, one step back88 // PersistentPreRunE: PersistentPreRun but returns an error.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 89–91why, one step back89 PersistentPreRunE func(cmd *Command, args []string) error90 // PreRun: children of this command will not inherit.91 PreRun func(cmd *Command, args []string)Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 92why, one step back92 // PreRunE: PreRun but returns an error.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 93why, one step back93 PreRunE func(cmd *Command, args []string) errorFix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 94why, one step back94 // Run: Typically the actual work function. Most commands will only implement this.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 95why, one step back95 Run func(cmd *Command, args []string)Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 96why, one step back96 // RunE: Run but returns an error.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 97–99why, one step back97 RunE func(cmd *Command, args []string) error98 // PostRun: run after the Run command.99 PostRun func(cmd *Command, args []string)Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 100why, one step back100 // PostRunE: PostRun but returns an error.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 101why, one step back101 PostRunE func(cmd *Command, args []string) errorFix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 102why, one step back102 // PersistentPostRun: children of this command will inherit and execute after PostRun.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 103why, one step back103 PersistentPostRun func(cmd *Command, args []string)Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 104why, one step back104 // PersistentPostRunE: PersistentPostRun but returns an error.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 105why, one step back105 PersistentPostRunE func(cmd *Command, args []string) errorDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
lines 106–112why, one step back106107 // SilenceErrors is an option to quiet errors down stream.108 SilenceErrors bool109110 // SilenceUsage is an option to silence usage when an error occurs.111 SilenceUsage bool112Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
lines 113–115why, one step back113 // DisableFlagParsing disables the flag parsing.114 // If this is true all flags will be passed to the command as arguments.115 DisableFlagParsing boolDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 116why, one step back116Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
lines 117–118why, one step back117 // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")118 // will be printed by generating docs for this command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 119why, one step back119 DisableAutoGenTag boolFix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
lines 120–127why, one step back120121 // DisableSuggestions disables the suggestions based on Levenshtein distance122 // that go along with 'unknown command' messages.123 DisableSuggestions bool124 // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.125 // Must be > 0.126 SuggestionsMinimumDistance int127Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 128–130why, one step back128 // TraverseChildren parses flags on all parents before executing child command.129 TraverseChildren bool130Divide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
lines 131–132why, one step back131 // name is the command name, usually the executable's name.132 name stringFix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 133why, one step back133 // commands is the list of commands supported by this program.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 134why, one step back134 commands []*CommandFix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
line 135why, one step back135 // parent is a parent command for this command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 136why, one step back136 parent *CommandDivide fields of Command for readabilityAlbert Nigmatzianovbefore adoptioneceb483
line 137why, one step back137 // Max lengths of commands' string lengths for use in padding.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 138–140why, one step back138 commandsMaxUseLen int139 commandsMaxCommandPathLen int140 commandsMaxNameLen intGroup fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8
line 141why, one step back141 // commandsAreSorted defines, if command slice are sorted or not.Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
line 142why, one step back142 commandsAreSorted boolGroup fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8
line 143why, one step back143Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
lines 144–145why, one step back144 // args is actual args parsed from flags.145 args []stringGroup fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8
lines 146–161why, one step back146 // flagErrorBuf contains all error messages from pflag.147 flagErrorBuf *bytes.Buffer148 // flags is full set of flags.149 flags *flag.FlagSet150 // pflags contains persistent flags.151 pflags *flag.FlagSet152 // lflags contains local flags.153 lflags *flag.FlagSet154 // iflags contains inherited flags.155 iflags *flag.FlagSet156 // parentsPflags is all persistent flags of cmd's parents.157 parentsPflags *flag.FlagSet158 // globNormFunc is the global normalization function159 // that we can use on every pflag set and children commands160 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName161Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
lines 162–169why, one step back162 // output is an output writer defined by user.163 output io.Writer164 // usageFunc is usage func defined by user.165 usageFunc func(*Command) error166 // usageTemplate is usage template defined by user.167 usageTemplate string168 // flagErrorFunc is func defined by user and it's called when the parsing of169 // flags returns an error.Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75
line 170why, one step back170 flagErrorFunc func(*Command, error) errorFix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
lines 171–174why, one step back171 // helpTemplate is help template defined by user.172 helpTemplate string173 // helpFunc is help func defined by user.174 helpFunc func(*Command, []string)Group fields of CommandAlbert Nigmatzianovbefore adoption90d2fd8
line 175why, one step back175 // helpCommand is command with usage 'help'. If it's not defined by user,Fix docs for CommandAlbert Nigmatzianovbefore adoption4db577d
lines 176–177why, one step back176 // cobra uses default help command.177 helpCommand *CommandAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 178–179why, one step back178}179Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 180why, one step back180// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overriddenAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 181–188why, one step back181// particularly useful when testing.182func (c *Command) SetArgs(a []string) {183 c.args = a184}185186// SetOutput sets the destination for usage and error messages.187// If output is nil, os.Stderr is used.188func (c *Command) SetOutput(output io.Writer) {Avoid storing pointer to nil (#411)Tamir Dubersteinbefore adoption7aeaa2c
line 189why, one step back189 c.output = outputAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 190–191why, one step back190}191Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 192why, one step back192// SetUsageFunc sets usage function. Usage can be defined by application.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 193–196why, one step back193func (c *Command) SetUsageFunc(f func(*Command) error) {194 c.usageFunc = f195}196Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 197why, one step back197// SetUsageTemplate sets usage template. Can be defined by Application.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 198–201why, one step back198func (c *Command) SetUsageTemplate(s string) {199 c.usageTemplate = s200}201Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75
line 202why, one step back202// SetFlagErrorFunc sets a function to generate an error when flag parsingSome fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a
line 203why, one step back203// fails.Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75
lines 204–207why, one step back204func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {205 c.flagErrorFunc = f206}207Some fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a
line 208why, one step back208// SetHelpFunc sets help function. Can be defined by Application.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 209–212why, one step back209func (c *Command) SetHelpFunc(f func(*Command, []string)) {210 c.helpFunc = f211}212Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 213why, one step back213// SetHelpCommand sets help command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 214–217why, one step back214func (c *Command) SetHelpCommand(cmd *Command) {215 c.helpCommand = cmd216}217Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 218why, one step back218// SetHelpTemplate sets help template to be used. Application can use it to set custom template.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 219–234why, one step back219func (c *Command) SetHelpTemplate(s string) {220 c.helpTemplate = s221}222223// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.224// The user should not have a cyclic dependency on commands.225func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {226 c.Flags().SetNormalizeFunc(n)227 c.PersistentFlags().SetNormalizeFunc(n)228 c.globNormFunc = n229230 for _, command := range c.commands {231 command.SetGlobalNormalizationFunc(n)232 }233}234Some fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a
line 235why, one step back235// OutOrStdout returns output to stdout.Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
line 236why, one step back236func (c *Command) OutOrStdout() io.Writer {Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
lines 237–239why, one step back237 return c.getOut(os.Stdout)238}239Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 240why, one step back240// OutOrStderr returns output to stderrMerge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
line 241why, one step back241func (c *Command) OutOrStderr() io.Writer {Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
lines 242–246why, one step back242 return c.getOut(os.Stderr)243}244245func (c *Command) getOut(def io.Writer) io.Writer {246 if c.output != nil {Avoid storing pointer to nil (#411)Tamir Dubersteinbefore adoption7aeaa2c
line 247why, one step back247 return c.outputMerge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
lines 248–255why, one step back248 }249 if c.HasParent() {250 return c.parent.getOut(def)251 }252 return def253}254255// UsageFunc returns either the function set by SetUsageFunc for this commandMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 256why, one step back256// or a parent, or it returns a default usage function.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 257–261why, one step back257func (c *Command) UsageFunc() (f func(*Command) error) {258 if c.usageFunc != nil {259 return c.usageFunc260 }261 if c.HasParent() {Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777
line 262why, one step back262 return c.Parent().UsageFunc()Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
lines 263–264why, one step back263 }264 return func(c *Command) error {Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
lines 265–266why, one step back265 c.mergePersistentFlags()266 err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 267why, one step back267 if err != nil {Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
line 268why, one step back268 c.Println(err)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 269why, one step back269 }Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 270why, one step back270 return errAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 271–273why, one step back271 }272}273Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
lines 274–276why, one step back274// Usage puts out the usage for the command.275// Used when a user provides invalid input.276// Can be defined by user by overriding UsageFunc.Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d
lines 277–280why, one step back277func (c *Command) Usage() error {278 return c.UsageFunc()(c)279}280Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 281why, one step back281// HelpFunc returns either the function set by SetHelpFunc for this commandMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 282why, one step back282// or a parent, or it returns a function with default help behavior.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 283why, one step back283func (c *Command) HelpFunc() func(*Command, []string) {Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777
lines 284–285why, one step back284 if c.helpFunc != nil {285 return c.helpFuncAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 286why, one step back286 }Delete checkHelpFuncAlbert Nigmatzianovbefore adoption681a777
lines 287–290why, one step back287 if c.HasParent() {288 return c.Parent().HelpFunc()289 }290 return func(c *Command, a []string) {Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
lines 291–292why, one step back291 c.mergePersistentFlags()292 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 293–298why, one step back293 if err != nil {294 c.Println(err)295 }296 }297}298Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
lines 299–301why, one step back299// Help puts out the help for the command.300// Used when a user calls help [command].301// Can be defined by user by overriding HelpFunc.Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d
lines 302–306why, one step back302func (c *Command) Help() error {303 c.HelpFunc()(c, []string{})304 return nil305}306Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 307why, one step back307// UsageString return usage string.Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
lines 308–311why, one step back308func (c *Command) UsageString() string {309 tmpOutput := c.output310 bb := new(bytes.Buffer)311 c.SetOutput(bb)Merge pull request #308 from fabianofranz/restore_backwards_compatibilityEric Parisbefore adoptiondbb7c2d
line 312why, one step back312 c.Usage()Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
lines 313–316why, one step back313 c.output = tmpOutput314 return bb.String()315}316Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75
lines 317–332why, one step back317// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this318// command or a parent, or it returns a function which returns the original319// error.320func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {321 if c.flagErrorFunc != nil {322 return c.flagErrorFunc323 }324325 if c.HasParent() {326 return c.parent.FlagErrorFunc()327 }328 return func(c *Command, err error) error {329 return err330 }331}332Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 333why, one step back333var minUsagePadding = 25Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 334why, one step back334Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 335why, one step back335// UsagePadding return padding for the usage.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 336–339why, one step back336func (c *Command) UsagePadding() int {337 if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {338 return minUsagePadding339 }Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 340why, one step back340 return c.parent.commandsMaxUseLenAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 341–342why, one step back341}342Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 343why, one step back343var minCommandPathPadding = 11Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 344why, one step back344Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 345why, one step back345// CommandPathPadding return padding for the command path.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 346–349why, one step back346func (c *Command) CommandPathPadding() int {347 if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {348 return minCommandPathPadding349 }Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 350why, one step back350 return c.parent.commandsMaxCommandPathLenAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 351–352why, one step back351}352Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 353why, one step back353var minNamePadding = 11Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 354why, one step back354Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 355why, one step back355// NamePadding returns padding for the name.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 356–359why, one step back356func (c *Command) NamePadding() int {357 if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {358 return minNamePadding359 }Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 360why, one step back360 return c.parent.commandsMaxNameLenAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 361–362why, one step back361}362Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 363why, one step back363// UsageTemplate returns usage template for the command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 364–370why, one step back364func (c *Command) UsageTemplate() string {365 if c.usageTemplate != "" {366 return c.usageTemplate367 }368369 if c.HasParent() {370 return c.parent.UsageTemplate()Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
lines 371–372why, one step back371 }372 return `Usage:{{if .Runnable}}Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
lines 373–374why, one step back373 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}374 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 375–376why, one step back375376Aliases:Keep only one newline between Aliases and Flags in help (#410)Albert Nigmatzianovbefore adoption9350054
line 377why, one step back377 {{.NameAndAliases}}{{end}}{{if .HasExample}}Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 378–379why, one step back378379Examples:Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
line 380why, one step back380{{.Example}}{{end}}{{if .HasAvailableSubCommands}}Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 381why, one step back381Some fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a
lines 382–383why, one step back382Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}383 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 384–385why, one step back384385Flags:Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
line 386why, one step back386{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 387–388why, one step back387388Global Flags:Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
line 389why, one step back389{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 390why, one step back390Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7
line 391why, one step back391Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}Some fixes related to help command (#394)Albert Nigmatzianovbefore adoptionfcd0c5a
line 392why, one step back392 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 393–397why, one step back393394Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}395`396}397Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 398why, one step back398// HelpTemplate return help template for the command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 399–405why, one step back399func (c *Command) HelpTemplate() string {400 if c.helpTemplate != "" {401 return c.helpTemplate402 }403404 if c.HasParent() {405 return c.parent.HelpTemplate()Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 406why, one step back406 }Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
line 407why, one step back407 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 408–411why, one step back408409{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`410}411Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41
lines 412–413why, one step back412func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {413 flag := fs.Lookup(name)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 414–416why, one step back414 if flag == nil {415 return false416 }Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6
line 417why, one step back417 return flag.NoOptDefVal != ""Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 418–419why, one step back418}419Fix subcommand locations with NoOptDefValue flags (#391)Eric Parisbefore adoption92ea23a
line 420why, one step back420func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {Use pflag.ShorthandLookupAlbert Nigmatzianovbefore adoption4061f41
lines 421–429why, one step back421 if len(name) == 0 {422 return false423 }424425 flag := fs.ShorthandLookup(name[:1])426 if flag == nil {427 return false428 }429 return flag.NoOptDefVal != ""Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 430–432why, one step back430}431432func stripFlags(args []string, c *Command) []string {Simplify stripFlags functionAlbert Nigmatzianovbefore adoption9890b7b
line 433why, one step back433 if len(args) == 0 {Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 434–438why, one step back434 return args435 }436 c.mergePersistentFlags()437438 commands := []string{}Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6
line 439why, one step back439 flags := c.Flags()Simplify stripFlags functionAlbert Nigmatzianovbefore adoption9890b7b
lines 440–443why, one step back440441Loop:442 for len(args) > 0 {443 s := args[0]Simplify stripFlagsAlbert Nigmatzianovbefore adoptionf4f10f6
line 444why, one step back444 args = args[1:]Fix tests so they give correct args (#445)Albert Nigmatzianovbefore adoption51b7cf5
lines 445–457why, one step back445 switch {446 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):447 // If '--flag arg' then448 // delete arg from args.449 fallthrough // (do the same as below)450 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):451 // If '-f arg' then452 // delete 'arg' from args or break the loop if len(args) <= 1.453 if len(args) <= 1 {454 break Loop455 } else {456 args = args[1:]457 continueAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 458why, one step back458 }Fix tests so they give correct args (#445)Albert Nigmatzianovbefore adoption51b7cf5
lines 459–460why, one step back459 case s != "" && !strings.HasPrefix(s, "-"):460 commands = append(commands, s)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 461–480why, one step back461 }462 }463464 return commands465}466467// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like468// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).469func argsMinusFirstX(args []string, x string) []string {470 for i, y := range args {471 if x == y {472 ret := []string{}473 ret = append(ret, args[:i]...)474 ret = append(ret, args[i+1:]...)475 return ret476 }477 }478 return args479}480Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 481–485why, one step back481func isFlagArg(arg string) bool {482 return ((len(arg) >= 3 && arg[1] == '-') ||483 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))484}485Add a tags field for user defined tags on a Command. (#359)Daniel Nephinbefore adoption99600f6
line 486why, one step back486// Find the target command given the args and command treeAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 487–497why, one step back487// Meant to be run on the highest node. Only searches down.488func (c *Command) Find(args []string) (*Command, []string, error) {489 var innerfind func(*Command, []string) (*Command, []string)490491 innerfind = func(c *Command, innerArgs []string) (*Command, []string) {492 argsWOflags := stripFlags(innerArgs, c)493 if len(argsWOflags) == 0 {494 return c, innerArgs495 }496 nextSubCmd := argsWOflags[0]497Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 498–500why, one step back498 cmd := c.findNext(nextSubCmd)499 if cmd != nil {500 return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 501–505why, one step back501 }502 return c, innerArgs503 }504505 commandFound, a := innerfind(c, args)Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
lines 506–507why, one step back506 if commandFound.Args == nil {507 return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 508–509why, one step back508 }509 return commandFound, a, nilAllow commands to explicitly state if they do, or do not take arbitrary argumentsEric Parisbefore adoptiond89c499
lines 510–511why, one step back510}511Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
line 512why, one step back512func (c *Command) findSuggestions(arg string) string {Allow commands to explicitly state if they do, or do not take arbitrary argumentsEric Parisbefore adoptiond89c499
lines 513–519why, one step back513 if c.DisableSuggestions {514 return ""515 }516 if c.SuggestionsMinimumDistance <= 0 {517 c.SuggestionsMinimumDistance = 2518 }519 suggestionsString := ""Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
line 520why, one step back520 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {Allow commands to explicitly state if they do, or do not take arbitrary argumentsEric Parisbefore adoptiond89c499
lines 521–526why, one step back521 suggestionsString += "\n\nDid you mean this?\n"522 for _, s := range suggestions {523 suggestionsString += fmt.Sprintf("\t%v\n", s)524 }525 }526 return suggestionsStringAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 527–528why, one step back527}528Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 529–588why, one step back529func (c *Command) findNext(next string) *Command {530 matches := make([]*Command, 0)531 for _, cmd := range c.commands {532 if cmd.Name() == next || cmd.HasAlias(next) {533 return cmd534 }535 if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {536 matches = append(matches, cmd)537 }538 }539540 if len(matches) == 1 {541 return matches[0]542 }543 return nil544}545546// Traverse the command tree to find the command, and parse args for547// each parent.548func (c *Command) Traverse(args []string) (*Command, []string, error) {549 flags := []string{}550 inFlag := false551552 for i, arg := range args {553 switch {554 // A long flag with a space separated value555 case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):556 // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'557 inFlag = !hasNoOptDefVal(arg[2:], c.Flags())558 flags = append(flags, arg)559 continue560 // A short flag with a space separated value561 case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):562 inFlag = true563 flags = append(flags, arg)564 continue565 // The value for a flag566 case inFlag:567 inFlag = false568 flags = append(flags, arg)569 continue570 // A flag without a value, or with an `=` separated value571 case isFlagArg(arg):572 flags = append(flags, arg)573 continue574 }575576 cmd := c.findNext(arg)577 if cmd == nil {578 return c, args, nil579 }580581 if err := c.ParseFlags(flags); err != nil {582 return nil, args, err583 }584 return cmd.Traverse(args[i+1:])585 }586 return c, args, nil587}588Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 589why, one step back589// SuggestionsFor provides suggestions for the typedName.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 590–609why, one step back590func (c *Command) SuggestionsFor(typedName string) []string {591 suggestions := []string{}592 for _, cmd := range c.commands {593 if cmd.IsAvailableCommand() {594 levenshteinDistance := ld(typedName, cmd.Name(), true)595 suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance596 suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))597 if suggestByLevenshtein || suggestByPrefix {598 suggestions = append(suggestions, cmd.Name())599 }600 for _, explicitSuggestion := range cmd.SuggestFor {601 if strings.EqualFold(typedName, explicitSuggestion) {602 suggestions = append(suggestions, cmd.Name())603 }604 }605 }606 }607 return suggestions608}609Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 610why, one step back610// VisitParents visits all parents of the command and invokes fn on each parent.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 611why, one step back611func (c *Command) VisitParents(fn func(*Command)) {Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 612–614why, one step back612 if c.HasParent() {613 fn(c.Parent())614 c.Parent().VisitParents(fn)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 615–617why, one step back615 }616}617Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 618why, one step back618// Root finds root command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 619why, one step back619func (c *Command) Root() *Command {Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 620–621why, one step back620 if c.HasParent() {621 return c.Parent().Root()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 622why, one step back622 }Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
line 623why, one step back623 return cAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 624–644why, one step back624}625626// ArgsLenAtDash will return the length of f.Args at the moment when a -- was627// found during arg parsing. This allows your program to know which args were628// before the -- and which came after. (Description from629// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).630func (c *Command) ArgsLenAtDash() int {631 return c.Flags().ArgsLenAtDash()632}633634func (c *Command) execute(a []string) (err error) {635 if c == nil {636 return fmt.Errorf("Called Execute() on a nil Command")637 }638639 if len(c.Deprecated) > 0 {640 c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)641 }642643 // initialize help flag as the last point possible to allow for user644 // overridingMake initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e
line 645why, one step back645 c.InitDefaultHelpFlag()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 646–648why, one step back646647 err = c.ParseFlags(a)648 if err != nil {Merge pull request #283 from dnephin/add_flag_usage_funcEric Parisbefore adoptionb620a75
line 649why, one step back649 return c.FlagErrorFunc()(c, err)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 650why, one step back650 }Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e
lines 651–652why, one step back651652 // If help is called, regardless of other flags, return we want help.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 653–656why, one step back653 // Also say we need help if the command isn't runnable.654 helpVal, err := c.Flags().GetBool("help")655 if err != nil {656 // should be impossible to get here as we always declare a helpMake initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e
line 657why, one step back657 // flag in InitDefaultHelpFlag()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 658–660why, one step back658 c.Println("\"help\" flag declared as non-bool. Please correct your code")659 return err660 }Merge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
line 661why, one step back661Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 662–666why, one step back662 if helpVal || !c.Runnable() {663 return flag.ErrHelp664 }665666 c.preRun()Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048
line 667why, one step back667Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 668why, one step back668 argWoFlags := c.Flags().Args()Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048
lines 669–671why, one step back669 if c.DisableFlagParsing {670 argWoFlags = a671 }Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 672why, one step back672Refactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
lines 673–676why, one step back673 if err := c.ValidateArgs(argWoFlags); err != nil {674 return err675 }676Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 677–695why, one step back677 for p := c; p != nil; p = p.Parent() {678 if p.PersistentPreRunE != nil {679 if err := p.PersistentPreRunE(c, argWoFlags); err != nil {680 return err681 }682 break683 } else if p.PersistentPreRun != nil {684 p.PersistentPreRun(c, argWoFlags)685 break686 }687 }688 if c.PreRunE != nil {689 if err := c.PreRunE(c, argWoFlags); err != nil {690 return err691 }692 } else if c.PreRun != nil {693 c.PreRun(c, argWoFlags)694 }695enforce required flags (#502)Di Xubefore adoption4d6af28
lines 696–698why, one step back696 if err := c.validateRequiredFlags(); err != nil {697 return err698 }Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 699–733why, one step back699 if c.RunE != nil {700 if err := c.RunE(c, argWoFlags); err != nil {701 return err702 }703 } else {704 c.Run(c, argWoFlags)705 }706 if c.PostRunE != nil {707 if err := c.PostRunE(c, argWoFlags); err != nil {708 return err709 }710 } else if c.PostRun != nil {711 c.PostRun(c, argWoFlags)712 }713 for p := c; p != nil; p = p.Parent() {714 if p.PersistentPostRunE != nil {715 if err := p.PersistentPostRunE(c, argWoFlags); err != nil {716 return err717 }718 break719 } else if p.PersistentPostRun != nil {720 p.PersistentPostRun(c, argWoFlags)721 break722 }723 }724725 return nil726}727728func (c *Command) preRun() {729 for _, x := range initializers {730 x()731 }732}733Fix typosAlbert Nigmatzianovbefore adoptione606913
line 734why, one step back734// Execute uses the args (os.Args[1:] by default)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 735–741why, one step back735// and run through the command tree finding appropriate matches736// for commands and then corresponding flags.737func (c *Command) Execute() error {738 _, err := c.ExecuteC()739 return err740}741Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 742why, one step back742// ExecuteC executes the command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 743–755why, one step back743func (c *Command) ExecuteC() (cmd *Command, err error) {744 // Regardless of what command execute is called on, run on Root only745 if c.HasParent() {746 return c.Root().ExecuteC()747 }748749 // windows hook750 if preExecHookFn != nil {751 preExecHookFn(c)752 }753754 // initialize help as the last point possible to allow for user755 // overridingMake initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1
line 756why, one step back756 c.InitDefaultHelpCmd()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 757–766why, one step back757758 var args []string759760 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155761 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {762 args = os.Args[1:]763 } else {764 args = c.args765 }766Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 767–772why, one step back767 var flags []string768 if c.TraverseChildren {769 cmd, flags, err = c.Traverse(args)770 } else {771 cmd, flags, err = c.Find(args)772 }Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 773–783why, one step back773 if err != nil {774 // If found parse to a subcommand and then failed, talk about the subcommand775 if cmd != nil {776 c = cmd777 }778 if !c.SilenceErrors {779 c.Println("Error:", err.Error())780 c.Printf("Run '%v --help' for usage.\n", c.CommandPath())781 }782 return c, err783 }Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
line 784why, one step back784Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 785–805why, one step back785 err = cmd.execute(flags)786 if err != nil {787 // Always show help if requested, even if SilenceErrors is in788 // effect789 if err == flag.ErrHelp {790 cmd.HelpFunc()(cmd, args)791 return cmd, nil792 }793794 // If root command has SilentErrors flagged,795 // all subcommands should respect it796 if !cmd.SilenceErrors && !c.SilenceErrors {797 c.Println("Error:", err.Error())798 }799800 // If root command has SilentUsage flagged,801 // all subcommands should respect it802 if !cmd.SilenceUsage && !c.SilenceUsage {803 c.Println(cmd.UsageString())804 }805 }Fix typosAlbert Nigmatzianovbefore adoptione606913
line 806why, one step back806 return cmd, errRefactor TakesArgs to use an interface for arg validation.Daniel Nephinbefore adoptionf20b4e9
lines 807–813why, one step back807}808809func (c *Command) ValidateArgs(args []string) error {810 if c.Args == nil {811 return nil812 }813 return c.Args(c, args)enforce required flags (#502)Di Xubefore adoption4d6af28
lines 814–832why, one step back814}815816func (c *Command) validateRequiredFlags() error {817 flags := c.Flags()818 missingFlagNames := []string{}819 flags.VisitAll(func(pflag *flag.Flag) {820 requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]821 if !found {822 return823 }824 if (requiredAnnotation[0] == "true") && !pflag.Changed {825 missingFlagNames = append(missingFlagNames, pflag.Name)826 }827 })828829 if len(missingFlagNames) > 0 {830 return fmt.Errorf(`Required flag(s) "%s" have/has not been set`, strings.Join(missingFlagNames, `", "`))831 }832 return nilAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 833–834why, one step back833}834Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e
lines 835–836why, one step back835// InitDefaultHelpFlag adds default help flag to c.836// It is called automatically by executing the c or by calling help and usage.Add comment for InitDefaultHelpFlagAlbert Nigmatzianovbefore adoptiond83a1d7
line 837why, one step back837// If c already has help flag, it will do nothing.Make initHelpFlag publicAlbert Nigmatzianovbefore adoptionfe69f2e
line 838why, one step back838func (c *Command) InitDefaultHelpFlag() {Merge pull request #286 from dnephin/merge_flags_before_adding_helpEric Parisbefore adoptionec2fe78
line 839why, one step back839 c.mergePersistentFlags()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 840why, one step back840 if c.Flags().Lookup("help") == nil {Initialize help flag in initHelpCmdAlbert Nigmatzianovbefore adoption867d414
lines 841–847why, one step back841 usage := "help for "842 if c.Name() == "" {843 usage += "this command"844 } else {845 usage += c.Name()846 }847 c.Flags().BoolP("help", "h", false, usage)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 848–850why, one step back848 }849}850Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1
lines 851–854why, one step back851// InitDefaultHelpCmd adds default help command to c.852// It is called automatically by executing the c or by calling help and usage.853// If c already has help command or c has no subcommands, it will do nothing.854func (c *Command) InitDefaultHelpCmd() {Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02
line 855why, one step back855 if !c.HasSubCommands() {Make initHelpCmd public (#436)Albert Nigmatzianovbefore adoption52ae6a1
lines 856–857why, one step back856 return857 }Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 858why, one step back858Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02
lines 859–863why, one step back859 if c.helpCommand == nil {860 c.helpCommand = &Command{861 Use: "help [command]",862 Short: "Help about any command",863 Long: `Help provides help for any command in the application.Delete tab in the long description of helpAlbert Nigmatzianovbefore adoptiond994347
line 864why, one step back864Simply type ` + c.Name() + ` help [path to command] for full details.`,Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 865why, one step back865Fix InitDefaultHelpCmd when custom help command is setAlbert Nigmatzianovbefore adoption8c6fa02
lines 866–876why, one step back866 Run: func(c *Command, args []string) {867 cmd, _, e := c.Root().Find(args)868 if cmd == nil || e != nil {869 c.Printf("Unknown help topic %#q\n", args)870 c.Root().Usage()871 } else {872 cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown873 cmd.Help()874 }875 },876 }Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 877why, one step back877 }remove help command before adding it (#399)Tamir Dubersteinbefore adoption7be4bed
line 878why, one step back878 c.RemoveCommand(c.helpCommand)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 879–881why, one step back879 c.AddCommand(c.helpCommand)880}881Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 882why, one step back882// ResetCommands used for testing.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 883why, one step back883func (c *Command) ResetCommands() {Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
line 884why, one step back884 c.parent = nilAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 885–886why, one step back885 c.commands = nil886 c.helpCommand = nilAdd only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4
line 887why, one step back887 c.parentsPflags = nilAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 888–889why, one step back888}889Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 890why, one step back890// Sorts commands by their names.Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
lines 891–897why, one step back891type commandSorterByName []*Command892893func (c commandSorterByName) Len() int { return len(c) }894func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }895func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }896897// Commands returns a sorted slice of child commands.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 898why, one step back898func (c *Command) Commands() []*Command {Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
line 899why, one step back899 // do not sort commands if it already sorted or sorting was disabledMerge pull request #303 from fabianofranz/testing_help_exiting_1Eric Parisbefore adoptiona272c3c
line 900why, one step back900 if EnableCommandSorting && !c.commandsAreSorted {Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
lines 901–903why, one step back901 sort.Sort(commandSorterByName(c.commands))902 c.commandsAreSorted = true903 }Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 904–931why, one step back904 return c.commands905}906907// AddCommand adds one or more commands to this parent command.908func (c *Command) AddCommand(cmds ...*Command) {909 for i, x := range cmds {910 if cmds[i] == c {911 panic("Command can't be a child of itself")912 }913 cmds[i].parent = c914 // update max lengths915 usageLen := len(x.Use)916 if usageLen > c.commandsMaxUseLen {917 c.commandsMaxUseLen = usageLen918 }919 commandPathLen := len(x.CommandPath())920 if commandPathLen > c.commandsMaxCommandPathLen {921 c.commandsMaxCommandPathLen = commandPathLen922 }923 nameLen := len(x.Name())924 if nameLen > c.commandsMaxNameLen {925 c.commandsMaxNameLen = nameLen926 }927 // If global normalization function exists, update all children928 if c.globNormFunc != nil {929 x.SetGlobalNormalizationFunc(c.globNormFunc)930 }931 c.commands = append(c.commands, x)Merge pull request #293 from andreykurilin/sort_commandsEric Parisbefore adoptionbc81c21
line 932why, one step back932 c.commandsAreSorted = falseAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 933–935why, one step back933 }934}935Merge pull request #278 from kevintpeng/patch-1Eric Parisbefore adoptionf368244
line 936why, one step back936// RemoveCommand removes one or more commands from a parent command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 937–969why, one step back937func (c *Command) RemoveCommand(cmds ...*Command) {938 commands := []*Command{}939main:940 for _, command := range c.commands {941 for _, cmd := range cmds {942 if command == cmd {943 command.parent = nil944 continue main945 }946 }947 commands = append(commands, command)948 }949 c.commands = commands950 // recompute all lengths951 c.commandsMaxUseLen = 0952 c.commandsMaxCommandPathLen = 0953 c.commandsMaxNameLen = 0954 for _, command := range c.commands {955 usageLen := len(command.Use)956 if usageLen > c.commandsMaxUseLen {957 c.commandsMaxUseLen = usageLen958 }959 commandPathLen := len(command.CommandPath())960 if commandPathLen > c.commandsMaxCommandPathLen {961 c.commandsMaxCommandPathLen = commandPathLen962 }963 nameLen := len(command.Name())964 if nameLen > c.commandsMaxNameLen {965 c.commandsMaxNameLen = nameLen966 }967 }968}969Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 970why, one step back970// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 971why, one step back971func (c *Command) Print(i ...interface{}) {Merge pull request #305 from fabianofranz/expose_outEric Parisbefore adoptionb24564e
line 972why, one step back972 fmt.Fprint(c.OutOrStderr(), i...)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 973–974why, one step back973}974Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 975why, one step back975// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 976why, one step back976func (c *Command) Println(i ...interface{}) {Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
line 977why, one step back977 c.Print(fmt.Sprintln(i...))Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 978–979why, one step back978}979Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 980why, one step back980// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 981why, one step back981func (c *Command) Printf(format string, i ...interface{}) {Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
line 982why, one step back982 c.Print(fmt.Sprintf(format, i...))Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 983–986why, one step back983}984985// CommandPath returns the full path to this command.986func (c *Command) CommandPath() string {Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
lines 987–988why, one step back987 if c.HasParent() {988 return c.Parent().CommandPath() + " " + c.Name()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 989why, one step back989 }Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
line 990why, one step back990 return c.Name()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 991–992why, one step back991}992Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 993why, one step back993// UseLine puts out the full usage for a given command (including parents).Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 994why, one step back994func (c *Command) UseLine() string {Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
line 995why, one step back995 var useline stringAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 996why, one step back996 if c.HasParent() {Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
lines 997–999why, one step back997 useline = c.parent.CommandPath() + " " + c.Use998 } else {999 useline = c.UseAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1000why, one step back1000 }Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
lines 1001–1004why, one step back1001 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {1002 useline += " [flags]"1003 }1004 return uselineAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1005–1006why, one step back1005}1006Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1007why, one step back1007// DebugFlags used to determine which flags have been assigned to which commandsMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1008why, one step back1008// and which persist.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1009–1018why, one step back1009func (c *Command) DebugFlags() {1010 c.Println("DebugFlags called on", c.Name())1011 var debugflags func(*Command)10121013 debugflags = func(x *Command) {1014 if x.HasFlags() || x.HasPersistentFlags() {1015 c.Println(x.Name())1016 }1017 if x.HasFlags() {1018 x.flags.VisitAll(func(f *flag.Flag) {Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 1019–1020why, one step back1019 if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {1020 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1021–1036why, one step back1021 } else {1022 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")1023 }1024 })1025 }1026 if x.HasPersistentFlags() {1027 x.pflags.VisitAll(func(f *flag.Flag) {1028 if x.HasFlags() {1029 if x.flags.Lookup(f.Name) == nil {1030 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1031 }1032 } else {1033 c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")1034 }1035 })1036 }Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8
line 1037why, one step back1037 c.Println(x.flagErrorBuf)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1038–1049why, one step back1038 if x.HasSubCommands() {1039 for _, y := range x.commands {1040 debugflags(y)1041 }1042 }1043 }10441045 debugflags(c)1046}10471048// Name returns the command's name: the first word in the use line.1049func (c *Command) Name() string {Improve template mechanismsAlbert Nigmatzianovbefore adoption4d2c4af
lines 1050–1056why, one step back1050 if c.name == "" {1051 name := c.Use1052 i := strings.Index(name, " ")1053 if i >= 0 {1054 name = name[:i]1055 }1056 c.name = nameAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1057why, one step back1057 }cache command name (#390)Di Xubefore adoptionb5d8e8f
line 1058why, one step back1058 return c.nameAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1059–1060why, one step back1059}1060Merge pull request #260 from ianwalter/code-cleanupEric Parisbefore adoptionb0d571e
line 1061why, one step back1061// HasAlias determines if a given string is an alias of the command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1062–1070why, one step back1062func (c *Command) HasAlias(s string) bool {1063 for _, a := range c.Aliases {1064 if a == s {1065 return true1066 }1067 }1068 return false1069}1070Add a TraverseChildren option to allow for flags on each command in the hierarchy (#299)Daniel Nephinbefore adoption83b1f03
lines 1071–1085why, one step back1071// hasNameOrAliasPrefix returns true if the Name or any of aliases start1072// with prefix1073func (c *Command) hasNameOrAliasPrefix(prefix string) bool {1074 if strings.HasPrefix(c.Name(), prefix) {1075 return true1076 }1077 for _, alias := range c.Aliases {1078 if strings.HasPrefix(alias, prefix) {1079 return true1080 }1081 }1082 return false1083}10841085// NameAndAliases returns a list of the command name and all aliasesAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1086–1089why, one step back1086func (c *Command) NameAndAliases() string {1087 return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")1088}1089Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1090why, one step back1090// HasExample determines if the command has example.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1091–1094why, one step back1091func (c *Command) HasExample() bool {1092 return len(c.Example) > 01093}1094Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1095why, one step back1095// Runnable determines if the command is itself runnable.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1096–1099why, one step back1096func (c *Command) Runnable() bool {1097 return c.Run != nil || c.RunE != nil1098}1099Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1100why, one step back1100// HasSubCommands determines if the command has children commands.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1101–1105why, one step back1101func (c *Command) HasSubCommands() bool {1102 return len(c.commands) > 01103}11041105// IsAvailableCommand determines if a command is available as a non-help commandMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1106why, one step back1106// (this includes all non deprecated/hidden commands).Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1107–1122why, one step back1107func (c *Command) IsAvailableCommand() bool {1108 if len(c.Deprecated) != 0 || c.Hidden {1109 return false1110 }11111112 if c.HasParent() && c.Parent().helpCommand == c {1113 return false1114 }11151116 if c.Runnable() || c.HasAvailableSubCommands() {1117 return true1118 }11191120 return false1121}1122Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7
lines 1123–1128why, one step back1123// IsAdditionalHelpTopicCommand determines if a command is an additional1124// help topic command; additional help topic command is determined by the1125// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that1126// are runnable/hidden/deprecated.1127// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.1128func (c *Command) IsAdditionalHelpTopicCommand() bool {Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1129–1135why, one step back1129 // if a command is runnable, deprecated, or hidden it is not a 'help' command1130 if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {1131 return false1132 }11331134 // if any non-help sub commands are found, the command is not a 'help' command1135 for _, sub := range c.commands {Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7
line 1136why, one step back1136 if !sub.IsAdditionalHelpTopicCommand() {Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1137–1144why, one step back1137 return false1138 }1139 }11401141 // the command either has no sub commands, or no non-help sub commands1142 return true1143}1144Merge pull request #327 from bogem/fixesEric Parisbefore adoption1f47171
line 1145why, one step back1145// HasHelpSubCommands determines if a command has any available 'help' sub commandsAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1146why, one step back1146// that need to be shown in the usage/help default template under 'additional helpMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1147why, one step back1147// topics'.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1148–1150why, one step back1148func (c *Command) HasHelpSubCommands() bool {1149 // return true on the first found available 'help' sub command1150 for _, sub := range c.commands {Rename IsHelpCommand to IsAdditionalHelpTopicCommand (#398)Albert Nigmatzianovbefore adoption0960ff7
line 1151why, one step back1151 if sub.IsAdditionalHelpTopicCommand() {Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1152–1160why, one step back1152 return true1153 }1154 }11551156 // the command either has no sub commands, or no available 'help' sub commands1157 return false1158}11591160// HasAvailableSubCommands determines if a command has available sub commands thatMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1161why, one step back1161// need to be shown in the usage/help default template under 'available commands'.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1162–1175why, one step back1162func (c *Command) HasAvailableSubCommands() bool {1163 // return true on the first found available (non deprecated/help/hidden)1164 // sub command1165 for _, sub := range c.commands {1166 if sub.IsAvailableCommand() {1167 return true1168 }1169 }11701171 // the command either has no sub comamnds, or no available (non deprecated/help/hidden)1172 // sub commands1173 return false1174}1175Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1176why, one step back1176// HasParent determines if the command is a child command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1177–1180why, one step back1177func (c *Command) HasParent() bool {1178 return c.parent != nil1179}1180Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1181why, one step back1181// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1182–1185why, one step back1182func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {1183 return c.globNormFunc1184}1185Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1186why, one step back1186// Flags returns the complete FlagSet that appliesMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1187why, one step back1187// to this command (local and persistent declared here and by all parents).Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1188–1190why, one step back1188func (c *Command) Flags() *flag.FlagSet {1189 if c.flags == nil {1190 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8
lines 1191–1194why, one step back1191 if c.flagErrorBuf == nil {1192 c.flagErrorBuf = new(bytes.Buffer)1193 }1194 c.flags.SetOutput(c.flagErrorBuf)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1195why, one step back1195 }Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
line 1196why, one step back1196Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1197–1199why, one step back1197 return c.flags1198}1199Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1200why, one step back1200// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.Merge pull request #288 from eparis/flags-vs-commandsEric Parisbefore adoptionc21ee9d
lines 1201–1212why, one step back1201func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {1202 persistentFlags := c.PersistentFlags()12031204 out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)1205 c.LocalFlags().VisitAll(func(f *flag.Flag) {1206 if persistentFlags.Lookup(f.Name) == nil {1207 out.AddFlag(f)1208 }1209 })1210 return out1211}1212Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1213why, one step back1213// LocalFlags returns the local FlagSet specifically set in the current command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1214–1216why, one step back1214func (c *Command) LocalFlags() *flag.FlagSet {1215 c.mergePersistentFlags()1216Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 1217–1218why, one step back1217 if c.lflags == nil {1218 c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8
lines 1219–1222why, one step back1219 if c.flagErrorBuf == nil {1220 c.flagErrorBuf = new(bytes.Buffer)1221 }1222 c.lflags.SetOutput(c.flagErrorBuf)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1223why, one step back1223 }Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867
line 1224why, one step back1224 c.lflags.SortFlags = c.Flags().SortFlagsImprove consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
lines 1225–1227why, one step back1225 if c.globNormFunc != nil {1226 c.lflags.SetNormalizeFunc(c.globNormFunc)1227 }Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 1228–1233why, one step back12281229 addToLocal := func(f *flag.Flag) {1230 if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil {1231 c.lflags.AddFlag(f)1232 }1233 }Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867
line 1234why, one step back1234 c.Flags().VisitAll(addToLocal)Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 1235–1236why, one step back1235 c.PersistentFlags().VisitAll(addToLocal)1236 return c.lflagsAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1237–1238why, one step back1237}1238Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1239why, one step back1239// InheritedFlags returns all flags which were inherited from parents commands.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1240–1242why, one step back1240func (c *Command) InheritedFlags() *flag.FlagSet {1241 c.mergePersistentFlags()1242Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 1243–1244why, one step back1243 if c.iflags == nil {1244 c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8
lines 1245–1248why, one step back1245 if c.flagErrorBuf == nil {1246 c.flagErrorBuf = new(bytes.Buffer)1247 }1248 c.iflags.SetOutput(c.flagErrorBuf)Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 1249–1250why, one step back1249 }1250Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1251why, one step back1251 local := c.LocalFlags()Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
lines 1252–1255why, one step back1252 if c.globNormFunc != nil {1253 c.iflags.SetNormalizeFunc(c.globNormFunc)1254 }1255Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 1256–1258why, one step back1256 c.parentsPflags.VisitAll(func(f *flag.Flag) {1257 if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {1258 c.iflags.AddFlag(f)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1259why, one step back1259 }Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 1260–1261why, one step back1260 })1261 return c.iflagsAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1262–1263why, one step back1262}1263Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1264why, one step back1264// NonInheritedFlags returns all flags which were not inherited from parent commands.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1265–1268why, one step back1265func (c *Command) NonInheritedFlags() *flag.FlagSet {1266 return c.LocalFlags()1267}1268Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1269why, one step back1269// PersistentFlags returns the persistent FlagSet specifically set in the current command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1270–1272why, one step back1270func (c *Command) PersistentFlags() *flag.FlagSet {1271 if c.pflags == nil {1272 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8
lines 1273–1276why, one step back1273 if c.flagErrorBuf == nil {1274 c.flagErrorBuf = new(bytes.Buffer)1275 }1276 c.pflags.SetOutput(c.flagErrorBuf)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1277–1280why, one step back1277 }1278 return c.pflags1279}1280Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1281why, one step back1281// ResetFlags is used in testing.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1282why, one step back1282func (c *Command) ResetFlags() {Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8
lines 1283–1284why, one step back1283 c.flagErrorBuf = new(bytes.Buffer)1284 c.flagErrorBuf.Reset()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1285why, one step back1285 c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8
line 1286why, one step back1286 c.flags.SetOutput(c.flagErrorBuf)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1287why, one step back1287 c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8
line 1288why, one step back1288 c.pflags.SetOutput(c.flagErrorBuf)Improve consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
lines 1289–1292why, one step back12891290 c.lflags = nil1291 c.iflags = nil1292 c.parentsPflags = nilAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1293–1294why, one step back1293}1294Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1295why, one step back1295// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1296–1299why, one step back1296func (c *Command) HasFlags() bool {1297 return c.Flags().HasFlags()1298}1299Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1300why, one step back1300// HasPersistentFlags checks if the command contains persistent flags.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1301–1304why, one step back1301func (c *Command) HasPersistentFlags() bool {1302 return c.PersistentFlags().HasFlags()1303}1304Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1305why, one step back1305// HasLocalFlags checks if the command has flags specifically declared locally.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1306–1309why, one step back1306func (c *Command) HasLocalFlags() bool {1307 return c.LocalFlags().HasFlags()1308}1309Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1310why, one step back1310// HasInheritedFlags checks if the command has flags inherited from its parent command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1311–1312why, one step back1311func (c *Command) HasInheritedFlags() bool {1312 return c.InheritedFlags().HasFlags()Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1313–1314why, one step back1313}1314Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1315why, one step back1315// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entireMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1316why, one step back1316// structure) which are not hidden or deprecated.Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1317–1320why, one step back1317func (c *Command) HasAvailableFlags() bool {1318 return c.Flags().HasAvailableFlags()1319}1320Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1321why, one step back1321// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1322–1325why, one step back1322func (c *Command) HasAvailablePersistentFlags() bool {1323 return c.PersistentFlags().HasAvailableFlags()1324}1325Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1326why, one step back1326// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hiddenMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1327why, one step back1327// or deprecated.Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1328–1331why, one step back1328func (c *Command) HasAvailableLocalFlags() bool {1329 return c.LocalFlags().HasAvailableFlags()1330}1331Added godocs to public methods. (#386)Oleg Atamanenkobefore adoption0f056af
line 1332why, one step back1332// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which areMerge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1333why, one step back1333// not hidden or deprecated.Issue #267: Ensure hidden flags/subcommands do not change helpJohn Schnakebefore adoptione14e47b
lines 1334–1335why, one step back1334func (c *Command) HasAvailableInheritedFlags() bool {1335 return c.InheritedFlags().HasAvailableFlags()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1336–1337why, one step back1336}1337Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1338why, one step back1338// Flag climbs up the command tree looking for matching flag.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1339–1348why, one step back1339func (c *Command) Flag(name string) (flag *flag.Flag) {1340 flag = c.Flags().Lookup(name)13411342 if flag == nil {1343 flag = c.persistentFlag(name)1344 }13451346 return1347}1348Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1349why, one step back1349// Recursively find matching persistent flag.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1350–1354why, one step back1350func (c *Command) persistentFlag(name string) (flag *flag.Flag) {1351 if c.HasPersistentFlags() {1352 flag = c.PersistentFlags().Lookup(name)1353 }1354Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867
lines 1355–1357why, one step back1355 if flag == nil {1356 c.updateParentsPflags()1357 flag = c.parentsPflags.Lookup(name)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1358–1361why, one step back1358 }1359 return1360}1361Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1362why, one step back1362// ParseFlags parses persistent flag tree and local flags.Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83
line 1363why, one step back1363func (c *Command) ParseFlags(args []string) error {Merge pull request #289 from markbates/disable-flagsEric Parisbefore adoptionf447048
lines 1364–1366why, one step back1364 if c.DisableFlagParsing {1365 return nil1366 }Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83
lines 1367–1368why, one step back13671368 beforeErrorBufLen := c.flagErrorBuf.Len()Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1369why, one step back1369 c.mergePersistentFlags()Show messages if deprecated flags are usedAlbert Nigmatzianovbefore adoption99b5d83
lines 1370–1376why, one step back1370 err := c.Flags().Parse(args)1371 // Print warnings if they occurred (e.g. deprecated flag messages).1372 if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {1373 c.Print(c.flagErrorBuf.String())1374 }13751376 return errAllow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1377–1378why, one step back1377}1378Merge pull request #339 from bogem/fixesEric Parisbefore adoption9c28e4b
line 1379why, one step back1379// Parent returns a commands parent command.Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
lines 1380–1383why, one step back1380func (c *Command) Parent() *Command {1381 return c.parent1382}1383Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4
lines 1384–1386why, one step back1384// mergePersistentFlags merges c.PersistentFlags() to c.Flags()1385// and adds missing persistent flags of all parents.1386func (c *Command) mergePersistentFlags() {Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867
line 1387why, one step back1387 c.updateParentsPflags()Fix incorrect merge of pflag.CommandLine to cmd.Flags()Albert Nigmatzianovbefore adoption7d22e77
line 1388why, one step back1388 c.Flags().AddFlagSet(c.PersistentFlags())Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867
line 1389why, one step back1389 c.Flags().AddFlagSet(c.parentsPflags)Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4
lines 1390–1392why, one step back1390}13911392// updateParentsPflags updates c.parentsPflags by addingMake parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867
line 1393why, one step back1393// new persistent flags of all parents.Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4
line 1394why, one step back1394// If c.parentsPflags == nil, it makes new.Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867
line 1395why, one step back1395func (c *Command) updateParentsPflags() {Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
lines 1396–1397why, one step back1396 if c.parentsPflags == nil {1397 c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)Revert "Get rid of flagErrorBuf (#417)"Albert Nigmatzianovbefore adoption3d7bff8
line 1398why, one step back1398 c.parentsPflags.SetOutput(c.flagErrorBuf)Add only missing persistent flags of parents in mergePersistentFlagsAlbert Nigmatzianovbefore adoption3d89ed4
line 1399why, one step back1399 c.parentsPflags.SortFlags = falseImprove consistency of flags when using SetGlobalNormalizationFunc (#522)Diego Becciolinibefore adoption0dacccf
lines 1400–1403why, one step back1400 }14011402 if c.globNormFunc != nil {1403 c.parentsPflags.SetNormalizeFunc(c.globNormFunc)Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1404why, one step back1404 }Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
line 1405why, one step back1405Add merging of CommandLine flags to Root commandAlbert Nigmatzianovbefore adoption458d797
lines 1406–1407why, one step back1406 c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)1407Make parentsPflags more flexibleAlbert Nigmatzianovbefore adoptione135867
lines 1408–1409why, one step back1408 c.VisitParents(func(parent *Command) {1409 c.parentsPflags.AddFlagSet(parent.PersistentFlags())Refactor flags mechanismsAlbert Nigmatzianovbefore adoption6202b59
line 1410why, one step back1410 })Allow bash-completion to work with full-path executableAnthony Fokbefore adoption65a708c
line 1411why, one step back1411}