command.go 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  1. // Copyright 2013-2023 The Cobra Authors
  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 at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // 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.
  16. package cobra
  17. import (
  18. "bytes"
  19. "context"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "os"
  24. "path/filepath"
  25. "sort"
  26. "strings"
  27. flag "github.com/spf13/pflag"
  28. )
  29. const (
  30. FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
  31. CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"
  32. )
  33. // FParseErrWhitelist configures Flag parse errors to be ignored
  34. type FParseErrWhitelist flag.ParseErrorsWhitelist
  35. // Group Structure to manage groups for commands
  36. type Group struct {
  37. ID string
  38. Title string
  39. }
  40. // Command is just that, a command for your application.
  41. // E.g. 'go run ...' - 'run' is the command. Cobra requires
  42. // you to define the usage and description as part of your command
  43. // definition to ensure usability.
  44. type Command struct {
  45. // Use is the one-line usage message.
  46. // Recommended syntax is as follows:
  47. // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.
  48. // ... indicates that you can specify multiple values for the previous argument.
  49. // | indicates mutually exclusive information. You can use the argument to the left of the separator or the
  50. // argument to the right of the separator. You cannot use both arguments in a single use of the command.
  51. // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are
  52. // optional, they are enclosed in brackets ([ ]).
  53. // Example: add [-F file | -D dir]... [-f format] profile
  54. Use string
  55. // Aliases is an array of aliases that can be used instead of the first word in Use.
  56. Aliases []string
  57. // SuggestFor is an array of command names for which this command will be suggested -
  58. // similar to aliases but only suggests.
  59. SuggestFor []string
  60. // Short is the short description shown in the 'help' output.
  61. Short string
  62. // The group id under which this subcommand is grouped in the 'help' output of its parent.
  63. GroupID string
  64. // Long is the long message shown in the 'help <this-command>' output.
  65. Long string
  66. // Example is examples of how to use the command.
  67. Example string
  68. // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions
  69. ValidArgs []string
  70. // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.
  71. // It is a dynamic version of using ValidArgs.
  72. // Only one of ValidArgs and ValidArgsFunction can be used for a command.
  73. ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
  74. // Expected arguments
  75. Args PositionalArgs
  76. // ArgAliases is List of aliases for ValidArgs.
  77. // These are not suggested to the user in the shell completion,
  78. // but accepted if entered manually.
  79. ArgAliases []string
  80. // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.
  81. // For portability with other shells, it is recommended to instead use ValidArgsFunction
  82. BashCompletionFunction string
  83. // Deprecated defines, if this command is deprecated and should print this string when used.
  84. Deprecated string
  85. // Annotations are key/value pairs that can be used by applications to identify or
  86. // group commands or set special options.
  87. Annotations map[string]string
  88. // Version defines the version for this command. If this value is non-empty and the command does not
  89. // define a "version" flag, a "version" boolean flag will be added to the command and, if specified,
  90. // will print content of the "Version" variable. A shorthand "v" flag will also be added if the
  91. // command does not define one.
  92. Version string
  93. // The *Run functions are executed in the following order:
  94. // * PersistentPreRun()
  95. // * PreRun()
  96. // * Run()
  97. // * PostRun()
  98. // * PersistentPostRun()
  99. // All functions get the same args, the arguments after the command name.
  100. // The *PreRun and *PostRun functions will only be executed if the Run function of the current
  101. // command has been declared.
  102. //
  103. // PersistentPreRun: children of this command will inherit and execute.
  104. PersistentPreRun func(cmd *Command, args []string)
  105. // PersistentPreRunE: PersistentPreRun but returns an error.
  106. PersistentPreRunE func(cmd *Command, args []string) error
  107. // PreRun: children of this command will not inherit.
  108. PreRun func(cmd *Command, args []string)
  109. // PreRunE: PreRun but returns an error.
  110. PreRunE func(cmd *Command, args []string) error
  111. // Run: Typically the actual work function. Most commands will only implement this.
  112. Run func(cmd *Command, args []string)
  113. // RunE: Run but returns an error.
  114. RunE func(cmd *Command, args []string) error
  115. // PostRun: run after the Run command.
  116. PostRun func(cmd *Command, args []string)
  117. // PostRunE: PostRun but returns an error.
  118. PostRunE func(cmd *Command, args []string) error
  119. // PersistentPostRun: children of this command will inherit and execute after PostRun.
  120. PersistentPostRun func(cmd *Command, args []string)
  121. // PersistentPostRunE: PersistentPostRun but returns an error.
  122. PersistentPostRunE func(cmd *Command, args []string) error
  123. // groups for subcommands
  124. commandgroups []*Group
  125. // args is actual args parsed from flags.
  126. args []string
  127. // flagErrorBuf contains all error messages from pflag.
  128. flagErrorBuf *bytes.Buffer
  129. // flags is full set of flags.
  130. flags *flag.FlagSet
  131. // pflags contains persistent flags.
  132. pflags *flag.FlagSet
  133. // lflags contains local flags.
  134. // This field does not represent internal state, it's used as a cache to optimise LocalFlags function call
  135. lflags *flag.FlagSet
  136. // iflags contains inherited flags.
  137. // This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call
  138. iflags *flag.FlagSet
  139. // parentsPflags is all persistent flags of cmd's parents.
  140. parentsPflags *flag.FlagSet
  141. // globNormFunc is the global normalization function
  142. // that we can use on every pflag set and children commands
  143. globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName
  144. // usageFunc is usage func defined by user.
  145. usageFunc func(*Command) error
  146. // usageTemplate is usage template defined by user.
  147. usageTemplate string
  148. // flagErrorFunc is func defined by user and it's called when the parsing of
  149. // flags returns an error.
  150. flagErrorFunc func(*Command, error) error
  151. // helpTemplate is help template defined by user.
  152. helpTemplate string
  153. // helpFunc is help func defined by user.
  154. helpFunc func(*Command, []string)
  155. // helpCommand is command with usage 'help'. If it's not defined by user,
  156. // cobra uses default help command.
  157. helpCommand *Command
  158. // helpCommandGroupID is the group id for the helpCommand
  159. helpCommandGroupID string
  160. // completionCommandGroupID is the group id for the completion command
  161. completionCommandGroupID string
  162. // versionTemplate is the version template defined by user.
  163. versionTemplate string
  164. // errPrefix is the error message prefix defined by user.
  165. errPrefix string
  166. // inReader is a reader defined by the user that replaces stdin
  167. inReader io.Reader
  168. // outWriter is a writer defined by the user that replaces stdout
  169. outWriter io.Writer
  170. // errWriter is a writer defined by the user that replaces stderr
  171. errWriter io.Writer
  172. // FParseErrWhitelist flag parse errors to be ignored
  173. FParseErrWhitelist FParseErrWhitelist
  174. // CompletionOptions is a set of options to control the handling of shell completion
  175. CompletionOptions CompletionOptions
  176. // commandsAreSorted defines, if command slice are sorted or not.
  177. commandsAreSorted bool
  178. // commandCalledAs is the name or alias value used to call this command.
  179. commandCalledAs struct {
  180. name string
  181. called bool
  182. }
  183. ctx context.Context
  184. // commands is the list of commands supported by this program.
  185. commands []*Command
  186. // parent is a parent command for this command.
  187. parent *Command
  188. // Max lengths of commands' string lengths for use in padding.
  189. commandsMaxUseLen int
  190. commandsMaxCommandPathLen int
  191. commandsMaxNameLen int
  192. // TraverseChildren parses flags on all parents before executing child command.
  193. TraverseChildren bool
  194. // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
  195. Hidden bool
  196. // SilenceErrors is an option to quiet errors down stream.
  197. SilenceErrors bool
  198. // SilenceUsage is an option to silence usage when an error occurs.
  199. SilenceUsage bool
  200. // DisableFlagParsing disables the flag parsing.
  201. // If this is true all flags will be passed to the command as arguments.
  202. DisableFlagParsing bool
  203. // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
  204. // will be printed by generating docs for this command.
  205. DisableAutoGenTag bool
  206. // DisableFlagsInUseLine will disable the addition of [flags] to the usage
  207. // line of a command when printing help or generating docs
  208. DisableFlagsInUseLine bool
  209. // DisableSuggestions disables the suggestions based on Levenshtein distance
  210. // that go along with 'unknown command' messages.
  211. DisableSuggestions bool
  212. // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
  213. // Must be > 0.
  214. SuggestionsMinimumDistance int
  215. }
  216. // Context returns underlying command context. If command was executed
  217. // with ExecuteContext or the context was set with SetContext, the
  218. // previously set context will be returned. Otherwise, nil is returned.
  219. //
  220. // Notice that a call to Execute and ExecuteC will replace a nil context of
  221. // a command with a context.Background, so a background context will be
  222. // returned by Context after one of these functions has been called.
  223. func (c *Command) Context() context.Context {
  224. return c.ctx
  225. }
  226. // SetContext sets context for the command. This context will be overwritten by
  227. // Command.ExecuteContext or Command.ExecuteContextC.
  228. func (c *Command) SetContext(ctx context.Context) {
  229. c.ctx = ctx
  230. }
  231. // SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
  232. // particularly useful when testing.
  233. func (c *Command) SetArgs(a []string) {
  234. c.args = a
  235. }
  236. // SetOutput sets the destination for usage and error messages.
  237. // If output is nil, os.Stderr is used.
  238. // Deprecated: Use SetOut and/or SetErr instead
  239. func (c *Command) SetOutput(output io.Writer) {
  240. c.outWriter = output
  241. c.errWriter = output
  242. }
  243. // SetOut sets the destination for usage messages.
  244. // If newOut is nil, os.Stdout is used.
  245. func (c *Command) SetOut(newOut io.Writer) {
  246. c.outWriter = newOut
  247. }
  248. // SetErr sets the destination for error messages.
  249. // If newErr is nil, os.Stderr is used.
  250. func (c *Command) SetErr(newErr io.Writer) {
  251. c.errWriter = newErr
  252. }
  253. // SetIn sets the source for input data
  254. // If newIn is nil, os.Stdin is used.
  255. func (c *Command) SetIn(newIn io.Reader) {
  256. c.inReader = newIn
  257. }
  258. // SetUsageFunc sets usage function. Usage can be defined by application.
  259. func (c *Command) SetUsageFunc(f func(*Command) error) {
  260. c.usageFunc = f
  261. }
  262. // SetUsageTemplate sets usage template. Can be defined by Application.
  263. func (c *Command) SetUsageTemplate(s string) {
  264. c.usageTemplate = s
  265. }
  266. // SetFlagErrorFunc sets a function to generate an error when flag parsing
  267. // fails.
  268. func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
  269. c.flagErrorFunc = f
  270. }
  271. // SetHelpFunc sets help function. Can be defined by Application.
  272. func (c *Command) SetHelpFunc(f func(*Command, []string)) {
  273. c.helpFunc = f
  274. }
  275. // SetHelpCommand sets help command.
  276. func (c *Command) SetHelpCommand(cmd *Command) {
  277. c.helpCommand = cmd
  278. }
  279. // SetHelpCommandGroupID sets the group id of the help command.
  280. func (c *Command) SetHelpCommandGroupID(groupID string) {
  281. if c.helpCommand != nil {
  282. c.helpCommand.GroupID = groupID
  283. }
  284. // helpCommandGroupID is used if no helpCommand is defined by the user
  285. c.helpCommandGroupID = groupID
  286. }
  287. // SetCompletionCommandGroupID sets the group id of the completion command.
  288. func (c *Command) SetCompletionCommandGroupID(groupID string) {
  289. // completionCommandGroupID is used if no completion command is defined by the user
  290. c.Root().completionCommandGroupID = groupID
  291. }
  292. // SetHelpTemplate sets help template to be used. Application can use it to set custom template.
  293. func (c *Command) SetHelpTemplate(s string) {
  294. c.helpTemplate = s
  295. }
  296. // SetVersionTemplate sets version template to be used. Application can use it to set custom template.
  297. func (c *Command) SetVersionTemplate(s string) {
  298. c.versionTemplate = s
  299. }
  300. // SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.
  301. func (c *Command) SetErrPrefix(s string) {
  302. c.errPrefix = s
  303. }
  304. // SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
  305. // The user should not have a cyclic dependency on commands.
  306. func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
  307. c.Flags().SetNormalizeFunc(n)
  308. c.PersistentFlags().SetNormalizeFunc(n)
  309. c.globNormFunc = n
  310. for _, command := range c.commands {
  311. command.SetGlobalNormalizationFunc(n)
  312. }
  313. }
  314. // OutOrStdout returns output to stdout.
  315. func (c *Command) OutOrStdout() io.Writer {
  316. return c.getOut(os.Stdout)
  317. }
  318. // OutOrStderr returns output to stderr
  319. func (c *Command) OutOrStderr() io.Writer {
  320. return c.getOut(os.Stderr)
  321. }
  322. // ErrOrStderr returns output to stderr
  323. func (c *Command) ErrOrStderr() io.Writer {
  324. return c.getErr(os.Stderr)
  325. }
  326. // InOrStdin returns input to stdin
  327. func (c *Command) InOrStdin() io.Reader {
  328. return c.getIn(os.Stdin)
  329. }
  330. func (c *Command) getOut(def io.Writer) io.Writer {
  331. if c.outWriter != nil {
  332. return c.outWriter
  333. }
  334. if c.HasParent() {
  335. return c.parent.getOut(def)
  336. }
  337. return def
  338. }
  339. func (c *Command) getErr(def io.Writer) io.Writer {
  340. if c.errWriter != nil {
  341. return c.errWriter
  342. }
  343. if c.HasParent() {
  344. return c.parent.getErr(def)
  345. }
  346. return def
  347. }
  348. func (c *Command) getIn(def io.Reader) io.Reader {
  349. if c.inReader != nil {
  350. return c.inReader
  351. }
  352. if c.HasParent() {
  353. return c.parent.getIn(def)
  354. }
  355. return def
  356. }
  357. // UsageFunc returns either the function set by SetUsageFunc for this command
  358. // or a parent, or it returns a default usage function.
  359. func (c *Command) UsageFunc() (f func(*Command) error) {
  360. if c.usageFunc != nil {
  361. return c.usageFunc
  362. }
  363. if c.HasParent() {
  364. return c.Parent().UsageFunc()
  365. }
  366. return func(c *Command) error {
  367. c.mergePersistentFlags()
  368. err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)
  369. if err != nil {
  370. c.PrintErrln(err)
  371. }
  372. return err
  373. }
  374. }
  375. // Usage puts out the usage for the command.
  376. // Used when a user provides invalid input.
  377. // Can be defined by user by overriding UsageFunc.
  378. func (c *Command) Usage() error {
  379. return c.UsageFunc()(c)
  380. }
  381. // HelpFunc returns either the function set by SetHelpFunc for this command
  382. // or a parent, or it returns a function with default help behavior.
  383. func (c *Command) HelpFunc() func(*Command, []string) {
  384. if c.helpFunc != nil {
  385. return c.helpFunc
  386. }
  387. if c.HasParent() {
  388. return c.Parent().HelpFunc()
  389. }
  390. return func(c *Command, a []string) {
  391. c.mergePersistentFlags()
  392. // The help should be sent to stdout
  393. // See https://github.com/spf13/cobra/issues/1002
  394. err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
  395. if err != nil {
  396. c.PrintErrln(err)
  397. }
  398. }
  399. }
  400. // Help puts out the help for the command.
  401. // Used when a user calls help [command].
  402. // Can be defined by user by overriding HelpFunc.
  403. func (c *Command) Help() error {
  404. c.HelpFunc()(c, []string{})
  405. return nil
  406. }
  407. // UsageString returns usage string.
  408. func (c *Command) UsageString() string {
  409. // Storing normal writers
  410. tmpOutput := c.outWriter
  411. tmpErr := c.errWriter
  412. bb := new(bytes.Buffer)
  413. c.outWriter = bb
  414. c.errWriter = bb
  415. CheckErr(c.Usage())
  416. // Setting things back to normal
  417. c.outWriter = tmpOutput
  418. c.errWriter = tmpErr
  419. return bb.String()
  420. }
  421. // FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
  422. // command or a parent, or it returns a function which returns the original
  423. // error.
  424. func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
  425. if c.flagErrorFunc != nil {
  426. return c.flagErrorFunc
  427. }
  428. if c.HasParent() {
  429. return c.parent.FlagErrorFunc()
  430. }
  431. return func(c *Command, err error) error {
  432. return err
  433. }
  434. }
  435. var minUsagePadding = 25
  436. // UsagePadding return padding for the usage.
  437. func (c *Command) UsagePadding() int {
  438. if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
  439. return minUsagePadding
  440. }
  441. return c.parent.commandsMaxUseLen
  442. }
  443. var minCommandPathPadding = 11
  444. // CommandPathPadding return padding for the command path.
  445. func (c *Command) CommandPathPadding() int {
  446. if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
  447. return minCommandPathPadding
  448. }
  449. return c.parent.commandsMaxCommandPathLen
  450. }
  451. var minNamePadding = 11
  452. // NamePadding returns padding for the name.
  453. func (c *Command) NamePadding() int {
  454. if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
  455. return minNamePadding
  456. }
  457. return c.parent.commandsMaxNameLen
  458. }
  459. // UsageTemplate returns usage template for the command.
  460. func (c *Command) UsageTemplate() string {
  461. if c.usageTemplate != "" {
  462. return c.usageTemplate
  463. }
  464. if c.HasParent() {
  465. return c.parent.UsageTemplate()
  466. }
  467. return `Usage:{{if .Runnable}}
  468. {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
  469. {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
  470. Aliases:
  471. {{.NameAndAliases}}{{end}}{{if .HasExample}}
  472. Examples:
  473. {{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}
  474. Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  475. {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}
  476. {{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}
  477. {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}
  478. Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}
  479. {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
  480. Flags:
  481. {{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
  482. Global Flags:
  483. {{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
  484. Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
  485. {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
  486. Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
  487. `
  488. }
  489. // HelpTemplate return help template for the command.
  490. func (c *Command) HelpTemplate() string {
  491. if c.helpTemplate != "" {
  492. return c.helpTemplate
  493. }
  494. if c.HasParent() {
  495. return c.parent.HelpTemplate()
  496. }
  497. return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
  498. {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
  499. }
  500. // VersionTemplate return version template for the command.
  501. func (c *Command) VersionTemplate() string {
  502. if c.versionTemplate != "" {
  503. return c.versionTemplate
  504. }
  505. if c.HasParent() {
  506. return c.parent.VersionTemplate()
  507. }
  508. return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
  509. `
  510. }
  511. // ErrPrefix return error message prefix for the command
  512. func (c *Command) ErrPrefix() string {
  513. if c.errPrefix != "" {
  514. return c.errPrefix
  515. }
  516. if c.HasParent() {
  517. return c.parent.ErrPrefix()
  518. }
  519. return "Error:"
  520. }
  521. func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
  522. flag := fs.Lookup(name)
  523. if flag == nil {
  524. return false
  525. }
  526. return flag.NoOptDefVal != ""
  527. }
  528. func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
  529. if len(name) == 0 {
  530. return false
  531. }
  532. flag := fs.ShorthandLookup(name[:1])
  533. if flag == nil {
  534. return false
  535. }
  536. return flag.NoOptDefVal != ""
  537. }
  538. func stripFlags(args []string, c *Command) []string {
  539. if len(args) == 0 {
  540. return args
  541. }
  542. c.mergePersistentFlags()
  543. commands := []string{}
  544. flags := c.Flags()
  545. Loop:
  546. for len(args) > 0 {
  547. s := args[0]
  548. args = args[1:]
  549. switch {
  550. case s == "--":
  551. // "--" terminates the flags
  552. break Loop
  553. case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
  554. // If '--flag arg' then
  555. // delete arg from args.
  556. fallthrough // (do the same as below)
  557. case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
  558. // If '-f arg' then
  559. // delete 'arg' from args or break the loop if len(args) <= 1.
  560. if len(args) <= 1 {
  561. break Loop
  562. } else {
  563. args = args[1:]
  564. continue
  565. }
  566. case s != "" && !strings.HasPrefix(s, "-"):
  567. commands = append(commands, s)
  568. }
  569. }
  570. return commands
  571. }
  572. // argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
  573. // openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
  574. // Special care needs to be taken not to remove a flag value.
  575. func (c *Command) argsMinusFirstX(args []string, x string) []string {
  576. if len(args) == 0 {
  577. return args
  578. }
  579. c.mergePersistentFlags()
  580. flags := c.Flags()
  581. Loop:
  582. for pos := 0; pos < len(args); pos++ {
  583. s := args[pos]
  584. switch {
  585. case s == "--":
  586. // -- means we have reached the end of the parseable args. Break out of the loop now.
  587. break Loop
  588. case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
  589. fallthrough
  590. case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
  591. // This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip
  592. // over the next arg, because that is the value of this flag.
  593. pos++
  594. continue
  595. case !strings.HasPrefix(s, "-"):
  596. // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,
  597. // return the args, excluding the one at this position.
  598. if s == x {
  599. ret := make([]string, 0, len(args)-1)
  600. ret = append(ret, args[:pos]...)
  601. ret = append(ret, args[pos+1:]...)
  602. return ret
  603. }
  604. }
  605. }
  606. return args
  607. }
  608. func isFlagArg(arg string) bool {
  609. return ((len(arg) >= 3 && arg[0:2] == "--") ||
  610. (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
  611. }
  612. // Find the target command given the args and command tree
  613. // Meant to be run on the highest node. Only searches down.
  614. func (c *Command) Find(args []string) (*Command, []string, error) {
  615. var innerfind func(*Command, []string) (*Command, []string)
  616. innerfind = func(c *Command, innerArgs []string) (*Command, []string) {
  617. argsWOflags := stripFlags(innerArgs, c)
  618. if len(argsWOflags) == 0 {
  619. return c, innerArgs
  620. }
  621. nextSubCmd := argsWOflags[0]
  622. cmd := c.findNext(nextSubCmd)
  623. if cmd != nil {
  624. return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd))
  625. }
  626. return c, innerArgs
  627. }
  628. commandFound, a := innerfind(c, args)
  629. if commandFound.Args == nil {
  630. return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))
  631. }
  632. return commandFound, a, nil
  633. }
  634. func (c *Command) findSuggestions(arg string) string {
  635. if c.DisableSuggestions {
  636. return ""
  637. }
  638. if c.SuggestionsMinimumDistance <= 0 {
  639. c.SuggestionsMinimumDistance = 2
  640. }
  641. var sb strings.Builder
  642. if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
  643. sb.WriteString("\n\nDid you mean this?\n")
  644. for _, s := range suggestions {
  645. _, _ = fmt.Fprintf(&sb, "\t%v\n", s)
  646. }
  647. }
  648. return sb.String()
  649. }
  650. func (c *Command) findNext(next string) *Command {
  651. matches := make([]*Command, 0)
  652. for _, cmd := range c.commands {
  653. if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {
  654. cmd.commandCalledAs.name = next
  655. return cmd
  656. }
  657. if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {
  658. matches = append(matches, cmd)
  659. }
  660. }
  661. if len(matches) == 1 {
  662. // Temporarily disable gosec G602, which produces a false positive.
  663. // See https://github.com/securego/gosec/issues/1005.
  664. return matches[0] // #nosec G602
  665. }
  666. return nil
  667. }
  668. // Traverse the command tree to find the command, and parse args for
  669. // each parent.
  670. func (c *Command) Traverse(args []string) (*Command, []string, error) {
  671. flags := []string{}
  672. inFlag := false
  673. for i, arg := range args {
  674. switch {
  675. // A long flag with a space separated value
  676. case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):
  677. // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
  678. inFlag = !hasNoOptDefVal(arg[2:], c.Flags())
  679. flags = append(flags, arg)
  680. continue
  681. // A short flag with a space separated value
  682. case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):
  683. inFlag = true
  684. flags = append(flags, arg)
  685. continue
  686. // The value for a flag
  687. case inFlag:
  688. inFlag = false
  689. flags = append(flags, arg)
  690. continue
  691. // A flag without a value, or with an `=` separated value
  692. case isFlagArg(arg):
  693. flags = append(flags, arg)
  694. continue
  695. }
  696. cmd := c.findNext(arg)
  697. if cmd == nil {
  698. return c, args, nil
  699. }
  700. if err := c.ParseFlags(flags); err != nil {
  701. return nil, args, err
  702. }
  703. return cmd.Traverse(args[i+1:])
  704. }
  705. return c, args, nil
  706. }
  707. // SuggestionsFor provides suggestions for the typedName.
  708. func (c *Command) SuggestionsFor(typedName string) []string {
  709. suggestions := []string{}
  710. for _, cmd := range c.commands {
  711. if cmd.IsAvailableCommand() {
  712. levenshteinDistance := ld(typedName, cmd.Name(), true)
  713. suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance
  714. suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))
  715. if suggestByLevenshtein || suggestByPrefix {
  716. suggestions = append(suggestions, cmd.Name())
  717. }
  718. for _, explicitSuggestion := range cmd.SuggestFor {
  719. if strings.EqualFold(typedName, explicitSuggestion) {
  720. suggestions = append(suggestions, cmd.Name())
  721. }
  722. }
  723. }
  724. }
  725. return suggestions
  726. }
  727. // VisitParents visits all parents of the command and invokes fn on each parent.
  728. func (c *Command) VisitParents(fn func(*Command)) {
  729. if c.HasParent() {
  730. fn(c.Parent())
  731. c.Parent().VisitParents(fn)
  732. }
  733. }
  734. // Root finds root command.
  735. func (c *Command) Root() *Command {
  736. if c.HasParent() {
  737. return c.Parent().Root()
  738. }
  739. return c
  740. }
  741. // ArgsLenAtDash will return the length of c.Flags().Args at the moment
  742. // when a -- was found during args parsing.
  743. func (c *Command) ArgsLenAtDash() int {
  744. return c.Flags().ArgsLenAtDash()
  745. }
  746. func (c *Command) execute(a []string) (err error) {
  747. if c == nil {
  748. return fmt.Errorf("called Execute() on a nil Command")
  749. }
  750. if len(c.Deprecated) > 0 {
  751. c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
  752. }
  753. // initialize help and version flag at the last point possible to allow for user
  754. // overriding
  755. c.InitDefaultHelpFlag()
  756. c.InitDefaultVersionFlag()
  757. err = c.ParseFlags(a)
  758. if err != nil {
  759. return c.FlagErrorFunc()(c, err)
  760. }
  761. // If help is called, regardless of other flags, return we want help.
  762. // Also say we need help if the command isn't runnable.
  763. helpVal, err := c.Flags().GetBool("help")
  764. if err != nil {
  765. // should be impossible to get here as we always declare a help
  766. // flag in InitDefaultHelpFlag()
  767. c.Println("\"help\" flag declared as non-bool. Please correct your code")
  768. return err
  769. }
  770. if helpVal {
  771. return flag.ErrHelp
  772. }
  773. // for back-compat, only add version flag behavior if version is defined
  774. if c.Version != "" {
  775. versionVal, err := c.Flags().GetBool("version")
  776. if err != nil {
  777. c.Println("\"version\" flag declared as non-bool. Please correct your code")
  778. return err
  779. }
  780. if versionVal {
  781. err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c)
  782. if err != nil {
  783. c.Println(err)
  784. }
  785. return err
  786. }
  787. }
  788. if !c.Runnable() {
  789. return flag.ErrHelp
  790. }
  791. c.preRun()
  792. defer c.postRun()
  793. argWoFlags := c.Flags().Args()
  794. if c.DisableFlagParsing {
  795. argWoFlags = a
  796. }
  797. if err := c.ValidateArgs(argWoFlags); err != nil {
  798. return err
  799. }
  800. parents := make([]*Command, 0, 5)
  801. for p := c; p != nil; p = p.Parent() {
  802. if EnableTraverseRunHooks {
  803. // When EnableTraverseRunHooks is set:
  804. // - Execute all persistent pre-runs from the root parent till this command.
  805. // - Execute all persistent post-runs from this command till the root parent.
  806. parents = append([]*Command{p}, parents...)
  807. } else {
  808. // Otherwise, execute only the first found persistent hook.
  809. parents = append(parents, p)
  810. }
  811. }
  812. for _, p := range parents {
  813. if p.PersistentPreRunE != nil {
  814. if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
  815. return err
  816. }
  817. if !EnableTraverseRunHooks {
  818. break
  819. }
  820. } else if p.PersistentPreRun != nil {
  821. p.PersistentPreRun(c, argWoFlags)
  822. if !EnableTraverseRunHooks {
  823. break
  824. }
  825. }
  826. }
  827. if c.PreRunE != nil {
  828. if err := c.PreRunE(c, argWoFlags); err != nil {
  829. return err
  830. }
  831. } else if c.PreRun != nil {
  832. c.PreRun(c, argWoFlags)
  833. }
  834. if err := c.ValidateRequiredFlags(); err != nil {
  835. return err
  836. }
  837. if err := c.ValidateFlagGroups(); err != nil {
  838. return err
  839. }
  840. if c.RunE != nil {
  841. if err := c.RunE(c, argWoFlags); err != nil {
  842. return err
  843. }
  844. } else {
  845. c.Run(c, argWoFlags)
  846. }
  847. if c.PostRunE != nil {
  848. if err := c.PostRunE(c, argWoFlags); err != nil {
  849. return err
  850. }
  851. } else if c.PostRun != nil {
  852. c.PostRun(c, argWoFlags)
  853. }
  854. for p := c; p != nil; p = p.Parent() {
  855. if p.PersistentPostRunE != nil {
  856. if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
  857. return err
  858. }
  859. if !EnableTraverseRunHooks {
  860. break
  861. }
  862. } else if p.PersistentPostRun != nil {
  863. p.PersistentPostRun(c, argWoFlags)
  864. if !EnableTraverseRunHooks {
  865. break
  866. }
  867. }
  868. }
  869. return nil
  870. }
  871. func (c *Command) preRun() {
  872. for _, x := range initializers {
  873. x()
  874. }
  875. }
  876. func (c *Command) postRun() {
  877. for _, x := range finalizers {
  878. x()
  879. }
  880. }
  881. // ExecuteContext is the same as Execute(), but sets the ctx on the command.
  882. // Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
  883. // functions.
  884. func (c *Command) ExecuteContext(ctx context.Context) error {
  885. c.ctx = ctx
  886. return c.Execute()
  887. }
  888. // Execute uses the args (os.Args[1:] by default)
  889. // and run through the command tree finding appropriate matches
  890. // for commands and then corresponding flags.
  891. func (c *Command) Execute() error {
  892. _, err := c.ExecuteC()
  893. return err
  894. }
  895. // ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.
  896. // Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
  897. // functions.
  898. func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {
  899. c.ctx = ctx
  900. return c.ExecuteC()
  901. }
  902. // ExecuteC executes the command.
  903. func (c *Command) ExecuteC() (cmd *Command, err error) {
  904. if c.ctx == nil {
  905. c.ctx = context.Background()
  906. }
  907. // Regardless of what command execute is called on, run on Root only
  908. if c.HasParent() {
  909. return c.Root().ExecuteC()
  910. }
  911. // windows hook
  912. if preExecHookFn != nil {
  913. preExecHookFn(c)
  914. }
  915. // initialize help at the last point to allow for user overriding
  916. c.InitDefaultHelpCmd()
  917. // initialize completion at the last point to allow for user overriding
  918. c.InitDefaultCompletionCmd()
  919. // Now that all commands have been created, let's make sure all groups
  920. // are properly created also
  921. c.checkCommandGroups()
  922. args := c.args
  923. // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
  924. if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
  925. args = os.Args[1:]
  926. }
  927. // initialize the hidden command to be used for shell completion
  928. c.initCompleteCmd(args)
  929. var flags []string
  930. if c.TraverseChildren {
  931. cmd, flags, err = c.Traverse(args)
  932. } else {
  933. cmd, flags, err = c.Find(args)
  934. }
  935. if err != nil {
  936. // If found parse to a subcommand and then failed, talk about the subcommand
  937. if cmd != nil {
  938. c = cmd
  939. }
  940. if !c.SilenceErrors {
  941. c.PrintErrln(c.ErrPrefix(), err.Error())
  942. c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())
  943. }
  944. return c, err
  945. }
  946. cmd.commandCalledAs.called = true
  947. if cmd.commandCalledAs.name == "" {
  948. cmd.commandCalledAs.name = cmd.Name()
  949. }
  950. // We have to pass global context to children command
  951. // if context is present on the parent command.
  952. if cmd.ctx == nil {
  953. cmd.ctx = c.ctx
  954. }
  955. err = cmd.execute(flags)
  956. if err != nil {
  957. // Always show help if requested, even if SilenceErrors is in
  958. // effect
  959. if errors.Is(err, flag.ErrHelp) {
  960. cmd.HelpFunc()(cmd, args)
  961. return cmd, nil
  962. }
  963. // If root command has SilenceErrors flagged,
  964. // all subcommands should respect it
  965. if !cmd.SilenceErrors && !c.SilenceErrors {
  966. c.PrintErrln(cmd.ErrPrefix(), err.Error())
  967. }
  968. // If root command has SilenceUsage flagged,
  969. // all subcommands should respect it
  970. if !cmd.SilenceUsage && !c.SilenceUsage {
  971. c.Println(cmd.UsageString())
  972. }
  973. }
  974. return cmd, err
  975. }
  976. func (c *Command) ValidateArgs(args []string) error {
  977. if c.Args == nil {
  978. return ArbitraryArgs(c, args)
  979. }
  980. return c.Args(c, args)
  981. }
  982. // ValidateRequiredFlags validates all required flags are present and returns an error otherwise
  983. func (c *Command) ValidateRequiredFlags() error {
  984. if c.DisableFlagParsing {
  985. return nil
  986. }
  987. flags := c.Flags()
  988. missingFlagNames := []string{}
  989. flags.VisitAll(func(pflag *flag.Flag) {
  990. requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]
  991. if !found {
  992. return
  993. }
  994. if (requiredAnnotation[0] == "true") && !pflag.Changed {
  995. missingFlagNames = append(missingFlagNames, pflag.Name)
  996. }
  997. })
  998. if len(missingFlagNames) > 0 {
  999. return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))
  1000. }
  1001. return nil
  1002. }
  1003. // checkCommandGroups checks if a command has been added to a group that does not exists.
  1004. // If so, we panic because it indicates a coding error that should be corrected.
  1005. func (c *Command) checkCommandGroups() {
  1006. for _, sub := range c.commands {
  1007. // if Group is not defined let the developer know right away
  1008. if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) {
  1009. panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath()))
  1010. }
  1011. sub.checkCommandGroups()
  1012. }
  1013. }
  1014. // InitDefaultHelpFlag adds default help flag to c.
  1015. // It is called automatically by executing the c or by calling help and usage.
  1016. // If c already has help flag, it will do nothing.
  1017. func (c *Command) InitDefaultHelpFlag() {
  1018. c.mergePersistentFlags()
  1019. if c.Flags().Lookup("help") == nil {
  1020. usage := "help for "
  1021. name := c.displayName()
  1022. if name == "" {
  1023. usage += "this command"
  1024. } else {
  1025. usage += name
  1026. }
  1027. c.Flags().BoolP("help", "h", false, usage)
  1028. _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})
  1029. }
  1030. }
  1031. // InitDefaultVersionFlag adds default version flag to c.
  1032. // It is called automatically by executing the c.
  1033. // If c already has a version flag, it will do nothing.
  1034. // If c.Version is empty, it will do nothing.
  1035. func (c *Command) InitDefaultVersionFlag() {
  1036. if c.Version == "" {
  1037. return
  1038. }
  1039. c.mergePersistentFlags()
  1040. if c.Flags().Lookup("version") == nil {
  1041. usage := "version for "
  1042. if c.Name() == "" {
  1043. usage += "this command"
  1044. } else {
  1045. usage += c.Name()
  1046. }
  1047. if c.Flags().ShorthandLookup("v") == nil {
  1048. c.Flags().BoolP("version", "v", false, usage)
  1049. } else {
  1050. c.Flags().Bool("version", false, usage)
  1051. }
  1052. _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"})
  1053. }
  1054. }
  1055. // InitDefaultHelpCmd adds default help command to c.
  1056. // It is called automatically by executing the c or by calling help and usage.
  1057. // If c already has help command or c has no subcommands, it will do nothing.
  1058. func (c *Command) InitDefaultHelpCmd() {
  1059. if !c.HasSubCommands() {
  1060. return
  1061. }
  1062. if c.helpCommand == nil {
  1063. c.helpCommand = &Command{
  1064. Use: "help [command]",
  1065. Short: "Help about any command",
  1066. Long: `Help provides help for any command in the application.
  1067. Simply type ` + c.displayName() + ` help [path to command] for full details.`,
  1068. ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
  1069. var completions []string
  1070. cmd, _, e := c.Root().Find(args)
  1071. if e != nil {
  1072. return nil, ShellCompDirectiveNoFileComp
  1073. }
  1074. if cmd == nil {
  1075. // Root help command.
  1076. cmd = c.Root()
  1077. }
  1078. for _, subCmd := range cmd.Commands() {
  1079. if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {
  1080. if strings.HasPrefix(subCmd.Name(), toComplete) {
  1081. completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
  1082. }
  1083. }
  1084. }
  1085. return completions, ShellCompDirectiveNoFileComp
  1086. },
  1087. Run: func(c *Command, args []string) {
  1088. cmd, _, e := c.Root().Find(args)
  1089. if cmd == nil || e != nil {
  1090. c.Printf("Unknown help topic %#q\n", args)
  1091. CheckErr(c.Root().Usage())
  1092. } else {
  1093. cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
  1094. cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
  1095. CheckErr(cmd.Help())
  1096. }
  1097. },
  1098. GroupID: c.helpCommandGroupID,
  1099. }
  1100. }
  1101. c.RemoveCommand(c.helpCommand)
  1102. c.AddCommand(c.helpCommand)
  1103. }
  1104. // ResetCommands delete parent, subcommand and help command from c.
  1105. func (c *Command) ResetCommands() {
  1106. c.parent = nil
  1107. c.commands = nil
  1108. c.helpCommand = nil
  1109. c.parentsPflags = nil
  1110. }
  1111. // Sorts commands by their names.
  1112. type commandSorterByName []*Command
  1113. func (c commandSorterByName) Len() int { return len(c) }
  1114. func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
  1115. func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }
  1116. // Commands returns a sorted slice of child commands.
  1117. func (c *Command) Commands() []*Command {
  1118. // do not sort commands if it already sorted or sorting was disabled
  1119. if EnableCommandSorting && !c.commandsAreSorted {
  1120. sort.Sort(commandSorterByName(c.commands))
  1121. c.commandsAreSorted = true
  1122. }
  1123. return c.commands
  1124. }
  1125. // AddCommand adds one or more commands to this parent command.
  1126. func (c *Command) AddCommand(cmds ...*Command) {
  1127. for i, x := range cmds {
  1128. if cmds[i] == c {
  1129. panic("Command can't be a child of itself")
  1130. }
  1131. cmds[i].parent = c
  1132. // update max lengths
  1133. usageLen := len(x.Use)
  1134. if usageLen > c.commandsMaxUseLen {
  1135. c.commandsMaxUseLen = usageLen
  1136. }
  1137. commandPathLen := len(x.CommandPath())
  1138. if commandPathLen > c.commandsMaxCommandPathLen {
  1139. c.commandsMaxCommandPathLen = commandPathLen
  1140. }
  1141. nameLen := len(x.Name())
  1142. if nameLen > c.commandsMaxNameLen {
  1143. c.commandsMaxNameLen = nameLen
  1144. }
  1145. // If global normalization function exists, update all children
  1146. if c.globNormFunc != nil {
  1147. x.SetGlobalNormalizationFunc(c.globNormFunc)
  1148. }
  1149. c.commands = append(c.commands, x)
  1150. c.commandsAreSorted = false
  1151. }
  1152. }
  1153. // Groups returns a slice of child command groups.
  1154. func (c *Command) Groups() []*Group {
  1155. return c.commandgroups
  1156. }
  1157. // AllChildCommandsHaveGroup returns if all subcommands are assigned to a group
  1158. func (c *Command) AllChildCommandsHaveGroup() bool {
  1159. for _, sub := range c.commands {
  1160. if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {
  1161. return false
  1162. }
  1163. }
  1164. return true
  1165. }
  1166. // ContainsGroup return if groupID exists in the list of command groups.
  1167. func (c *Command) ContainsGroup(groupID string) bool {
  1168. for _, x := range c.commandgroups {
  1169. if x.ID == groupID {
  1170. return true
  1171. }
  1172. }
  1173. return false
  1174. }
  1175. // AddGroup adds one or more command groups to this parent command.
  1176. func (c *Command) AddGroup(groups ...*Group) {
  1177. c.commandgroups = append(c.commandgroups, groups...)
  1178. }
  1179. // RemoveCommand removes one or more commands from a parent command.
  1180. func (c *Command) RemoveCommand(cmds ...*Command) {
  1181. commands := []*Command{}
  1182. main:
  1183. for _, command := range c.commands {
  1184. for _, cmd := range cmds {
  1185. if command == cmd {
  1186. command.parent = nil
  1187. continue main
  1188. }
  1189. }
  1190. commands = append(commands, command)
  1191. }
  1192. c.commands = commands
  1193. // recompute all lengths
  1194. c.commandsMaxUseLen = 0
  1195. c.commandsMaxCommandPathLen = 0
  1196. c.commandsMaxNameLen = 0
  1197. for _, command := range c.commands {
  1198. usageLen := len(command.Use)
  1199. if usageLen > c.commandsMaxUseLen {
  1200. c.commandsMaxUseLen = usageLen
  1201. }
  1202. commandPathLen := len(command.CommandPath())
  1203. if commandPathLen > c.commandsMaxCommandPathLen {
  1204. c.commandsMaxCommandPathLen = commandPathLen
  1205. }
  1206. nameLen := len(command.Name())
  1207. if nameLen > c.commandsMaxNameLen {
  1208. c.commandsMaxNameLen = nameLen
  1209. }
  1210. }
  1211. }
  1212. // Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
  1213. func (c *Command) Print(i ...interface{}) {
  1214. fmt.Fprint(c.OutOrStderr(), i...)
  1215. }
  1216. // Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
  1217. func (c *Command) Println(i ...interface{}) {
  1218. c.Print(fmt.Sprintln(i...))
  1219. }
  1220. // Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
  1221. func (c *Command) Printf(format string, i ...interface{}) {
  1222. c.Print(fmt.Sprintf(format, i...))
  1223. }
  1224. // PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.
  1225. func (c *Command) PrintErr(i ...interface{}) {
  1226. fmt.Fprint(c.ErrOrStderr(), i...)
  1227. }
  1228. // PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.
  1229. func (c *Command) PrintErrln(i ...interface{}) {
  1230. c.PrintErr(fmt.Sprintln(i...))
  1231. }
  1232. // PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.
  1233. func (c *Command) PrintErrf(format string, i ...interface{}) {
  1234. c.PrintErr(fmt.Sprintf(format, i...))
  1235. }
  1236. // CommandPath returns the full path to this command.
  1237. func (c *Command) CommandPath() string {
  1238. if c.HasParent() {
  1239. return c.Parent().CommandPath() + " " + c.Name()
  1240. }
  1241. return c.displayName()
  1242. }
  1243. func (c *Command) displayName() string {
  1244. if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {
  1245. return displayName
  1246. }
  1247. return c.Name()
  1248. }
  1249. // UseLine puts out the full usage for a given command (including parents).
  1250. func (c *Command) UseLine() string {
  1251. var useline string
  1252. use := strings.Replace(c.Use, c.Name(), c.displayName(), 1)
  1253. if c.HasParent() {
  1254. useline = c.parent.CommandPath() + " " + use
  1255. } else {
  1256. useline = use
  1257. }
  1258. if c.DisableFlagsInUseLine {
  1259. return useline
  1260. }
  1261. if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
  1262. useline += " [flags]"
  1263. }
  1264. return useline
  1265. }
  1266. // DebugFlags used to determine which flags have been assigned to which commands
  1267. // and which persist.
  1268. func (c *Command) DebugFlags() {
  1269. c.Println("DebugFlags called on", c.Name())
  1270. var debugflags func(*Command)
  1271. debugflags = func(x *Command) {
  1272. if x.HasFlags() || x.HasPersistentFlags() {
  1273. c.Println(x.Name())
  1274. }
  1275. if x.HasFlags() {
  1276. x.flags.VisitAll(func(f *flag.Flag) {
  1277. if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {
  1278. c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")
  1279. } else {
  1280. c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")
  1281. }
  1282. })
  1283. }
  1284. if x.HasPersistentFlags() {
  1285. x.pflags.VisitAll(func(f *flag.Flag) {
  1286. if x.HasFlags() {
  1287. if x.flags.Lookup(f.Name) == nil {
  1288. c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
  1289. }
  1290. } else {
  1291. c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
  1292. }
  1293. })
  1294. }
  1295. c.Println(x.flagErrorBuf)
  1296. if x.HasSubCommands() {
  1297. for _, y := range x.commands {
  1298. debugflags(y)
  1299. }
  1300. }
  1301. }
  1302. debugflags(c)
  1303. }
  1304. // Name returns the command's name: the first word in the use line.
  1305. func (c *Command) Name() string {
  1306. name := c.Use
  1307. i := strings.Index(name, " ")
  1308. if i >= 0 {
  1309. name = name[:i]
  1310. }
  1311. return name
  1312. }
  1313. // HasAlias determines if a given string is an alias of the command.
  1314. func (c *Command) HasAlias(s string) bool {
  1315. for _, a := range c.Aliases {
  1316. if commandNameMatches(a, s) {
  1317. return true
  1318. }
  1319. }
  1320. return false
  1321. }
  1322. // CalledAs returns the command name or alias that was used to invoke
  1323. // this command or an empty string if the command has not been called.
  1324. func (c *Command) CalledAs() string {
  1325. if c.commandCalledAs.called {
  1326. return c.commandCalledAs.name
  1327. }
  1328. return ""
  1329. }
  1330. // hasNameOrAliasPrefix returns true if the Name or any of aliases start
  1331. // with prefix
  1332. func (c *Command) hasNameOrAliasPrefix(prefix string) bool {
  1333. if strings.HasPrefix(c.Name(), prefix) {
  1334. c.commandCalledAs.name = c.Name()
  1335. return true
  1336. }
  1337. for _, alias := range c.Aliases {
  1338. if strings.HasPrefix(alias, prefix) {
  1339. c.commandCalledAs.name = alias
  1340. return true
  1341. }
  1342. }
  1343. return false
  1344. }
  1345. // NameAndAliases returns a list of the command name and all aliases
  1346. func (c *Command) NameAndAliases() string {
  1347. return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
  1348. }
  1349. // HasExample determines if the command has example.
  1350. func (c *Command) HasExample() bool {
  1351. return len(c.Example) > 0
  1352. }
  1353. // Runnable determines if the command is itself runnable.
  1354. func (c *Command) Runnable() bool {
  1355. return c.Run != nil || c.RunE != nil
  1356. }
  1357. // HasSubCommands determines if the command has children commands.
  1358. func (c *Command) HasSubCommands() bool {
  1359. return len(c.commands) > 0
  1360. }
  1361. // IsAvailableCommand determines if a command is available as a non-help command
  1362. // (this includes all non deprecated/hidden commands).
  1363. func (c *Command) IsAvailableCommand() bool {
  1364. if len(c.Deprecated) != 0 || c.Hidden {
  1365. return false
  1366. }
  1367. if c.HasParent() && c.Parent().helpCommand == c {
  1368. return false
  1369. }
  1370. if c.Runnable() || c.HasAvailableSubCommands() {
  1371. return true
  1372. }
  1373. return false
  1374. }
  1375. // IsAdditionalHelpTopicCommand determines if a command is an additional
  1376. // help topic command; additional help topic command is determined by the
  1377. // fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
  1378. // are runnable/hidden/deprecated.
  1379. // Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
  1380. func (c *Command) IsAdditionalHelpTopicCommand() bool {
  1381. // if a command is runnable, deprecated, or hidden it is not a 'help' command
  1382. if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
  1383. return false
  1384. }
  1385. // if any non-help sub commands are found, the command is not a 'help' command
  1386. for _, sub := range c.commands {
  1387. if !sub.IsAdditionalHelpTopicCommand() {
  1388. return false
  1389. }
  1390. }
  1391. // the command either has no sub commands, or no non-help sub commands
  1392. return true
  1393. }
  1394. // HasHelpSubCommands determines if a command has any available 'help' sub commands
  1395. // that need to be shown in the usage/help default template under 'additional help
  1396. // topics'.
  1397. func (c *Command) HasHelpSubCommands() bool {
  1398. // return true on the first found available 'help' sub command
  1399. for _, sub := range c.commands {
  1400. if sub.IsAdditionalHelpTopicCommand() {
  1401. return true
  1402. }
  1403. }
  1404. // the command either has no sub commands, or no available 'help' sub commands
  1405. return false
  1406. }
  1407. // HasAvailableSubCommands determines if a command has available sub commands that
  1408. // need to be shown in the usage/help default template under 'available commands'.
  1409. func (c *Command) HasAvailableSubCommands() bool {
  1410. // return true on the first found available (non deprecated/help/hidden)
  1411. // sub command
  1412. for _, sub := range c.commands {
  1413. if sub.IsAvailableCommand() {
  1414. return true
  1415. }
  1416. }
  1417. // the command either has no sub commands, or no available (non deprecated/help/hidden)
  1418. // sub commands
  1419. return false
  1420. }
  1421. // HasParent determines if the command is a child command.
  1422. func (c *Command) HasParent() bool {
  1423. return c.parent != nil
  1424. }
  1425. // GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.
  1426. func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
  1427. return c.globNormFunc
  1428. }
  1429. // Flags returns the complete FlagSet that applies
  1430. // to this command (local and persistent declared here and by all parents).
  1431. func (c *Command) Flags() *flag.FlagSet {
  1432. if c.flags == nil {
  1433. c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
  1434. if c.flagErrorBuf == nil {
  1435. c.flagErrorBuf = new(bytes.Buffer)
  1436. }
  1437. c.flags.SetOutput(c.flagErrorBuf)
  1438. }
  1439. return c.flags
  1440. }
  1441. // LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
  1442. // This function does not modify the flags of the current command, it's purpose is to return the current state.
  1443. func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
  1444. persistentFlags := c.PersistentFlags()
  1445. out := flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
  1446. c.LocalFlags().VisitAll(func(f *flag.Flag) {
  1447. if persistentFlags.Lookup(f.Name) == nil {
  1448. out.AddFlag(f)
  1449. }
  1450. })
  1451. return out
  1452. }
  1453. // LocalFlags returns the local FlagSet specifically set in the current command.
  1454. // This function does not modify the flags of the current command, it's purpose is to return the current state.
  1455. func (c *Command) LocalFlags() *flag.FlagSet {
  1456. c.mergePersistentFlags()
  1457. if c.lflags == nil {
  1458. c.lflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
  1459. if c.flagErrorBuf == nil {
  1460. c.flagErrorBuf = new(bytes.Buffer)
  1461. }
  1462. c.lflags.SetOutput(c.flagErrorBuf)
  1463. }
  1464. c.lflags.SortFlags = c.Flags().SortFlags
  1465. if c.globNormFunc != nil {
  1466. c.lflags.SetNormalizeFunc(c.globNormFunc)
  1467. }
  1468. addToLocal := func(f *flag.Flag) {
  1469. // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag
  1470. if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {
  1471. c.lflags.AddFlag(f)
  1472. }
  1473. }
  1474. c.Flags().VisitAll(addToLocal)
  1475. c.PersistentFlags().VisitAll(addToLocal)
  1476. return c.lflags
  1477. }
  1478. // InheritedFlags returns all flags which were inherited from parent commands.
  1479. // This function does not modify the flags of the current command, it's purpose is to return the current state.
  1480. func (c *Command) InheritedFlags() *flag.FlagSet {
  1481. c.mergePersistentFlags()
  1482. if c.iflags == nil {
  1483. c.iflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
  1484. if c.flagErrorBuf == nil {
  1485. c.flagErrorBuf = new(bytes.Buffer)
  1486. }
  1487. c.iflags.SetOutput(c.flagErrorBuf)
  1488. }
  1489. local := c.LocalFlags()
  1490. if c.globNormFunc != nil {
  1491. c.iflags.SetNormalizeFunc(c.globNormFunc)
  1492. }
  1493. c.parentsPflags.VisitAll(func(f *flag.Flag) {
  1494. if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
  1495. c.iflags.AddFlag(f)
  1496. }
  1497. })
  1498. return c.iflags
  1499. }
  1500. // NonInheritedFlags returns all flags which were not inherited from parent commands.
  1501. // This function does not modify the flags of the current command, it's purpose is to return the current state.
  1502. func (c *Command) NonInheritedFlags() *flag.FlagSet {
  1503. return c.LocalFlags()
  1504. }
  1505. // PersistentFlags returns the persistent FlagSet specifically set in the current command.
  1506. func (c *Command) PersistentFlags() *flag.FlagSet {
  1507. if c.pflags == nil {
  1508. c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
  1509. if c.flagErrorBuf == nil {
  1510. c.flagErrorBuf = new(bytes.Buffer)
  1511. }
  1512. c.pflags.SetOutput(c.flagErrorBuf)
  1513. }
  1514. return c.pflags
  1515. }
  1516. // ResetFlags deletes all flags from command.
  1517. func (c *Command) ResetFlags() {
  1518. c.flagErrorBuf = new(bytes.Buffer)
  1519. c.flagErrorBuf.Reset()
  1520. c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
  1521. c.flags.SetOutput(c.flagErrorBuf)
  1522. c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
  1523. c.pflags.SetOutput(c.flagErrorBuf)
  1524. c.lflags = nil
  1525. c.iflags = nil
  1526. c.parentsPflags = nil
  1527. }
  1528. // HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
  1529. func (c *Command) HasFlags() bool {
  1530. return c.Flags().HasFlags()
  1531. }
  1532. // HasPersistentFlags checks if the command contains persistent flags.
  1533. func (c *Command) HasPersistentFlags() bool {
  1534. return c.PersistentFlags().HasFlags()
  1535. }
  1536. // HasLocalFlags checks if the command has flags specifically declared locally.
  1537. func (c *Command) HasLocalFlags() bool {
  1538. return c.LocalFlags().HasFlags()
  1539. }
  1540. // HasInheritedFlags checks if the command has flags inherited from its parent command.
  1541. func (c *Command) HasInheritedFlags() bool {
  1542. return c.InheritedFlags().HasFlags()
  1543. }
  1544. // HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
  1545. // structure) which are not hidden or deprecated.
  1546. func (c *Command) HasAvailableFlags() bool {
  1547. return c.Flags().HasAvailableFlags()
  1548. }
  1549. // HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
  1550. func (c *Command) HasAvailablePersistentFlags() bool {
  1551. return c.PersistentFlags().HasAvailableFlags()
  1552. }
  1553. // HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
  1554. // or deprecated.
  1555. func (c *Command) HasAvailableLocalFlags() bool {
  1556. return c.LocalFlags().HasAvailableFlags()
  1557. }
  1558. // HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are
  1559. // not hidden or deprecated.
  1560. func (c *Command) HasAvailableInheritedFlags() bool {
  1561. return c.InheritedFlags().HasAvailableFlags()
  1562. }
  1563. // Flag climbs up the command tree looking for matching flag.
  1564. func (c *Command) Flag(name string) (flag *flag.Flag) {
  1565. flag = c.Flags().Lookup(name)
  1566. if flag == nil {
  1567. flag = c.persistentFlag(name)
  1568. }
  1569. return
  1570. }
  1571. // Recursively find matching persistent flag.
  1572. func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
  1573. if c.HasPersistentFlags() {
  1574. flag = c.PersistentFlags().Lookup(name)
  1575. }
  1576. if flag == nil {
  1577. c.updateParentsPflags()
  1578. flag = c.parentsPflags.Lookup(name)
  1579. }
  1580. return
  1581. }
  1582. // ParseFlags parses persistent flag tree and local flags.
  1583. func (c *Command) ParseFlags(args []string) error {
  1584. if c.DisableFlagParsing {
  1585. return nil
  1586. }
  1587. if c.flagErrorBuf == nil {
  1588. c.flagErrorBuf = new(bytes.Buffer)
  1589. }
  1590. beforeErrorBufLen := c.flagErrorBuf.Len()
  1591. c.mergePersistentFlags()
  1592. // do it here after merging all flags and just before parse
  1593. c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)
  1594. err := c.Flags().Parse(args)
  1595. // Print warnings if they occurred (e.g. deprecated flag messages).
  1596. if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
  1597. c.Print(c.flagErrorBuf.String())
  1598. }
  1599. return err
  1600. }
  1601. // Parent returns a commands parent command.
  1602. func (c *Command) Parent() *Command {
  1603. return c.parent
  1604. }
  1605. // mergePersistentFlags merges c.PersistentFlags() to c.Flags()
  1606. // and adds missing persistent flags of all parents.
  1607. func (c *Command) mergePersistentFlags() {
  1608. c.updateParentsPflags()
  1609. c.Flags().AddFlagSet(c.PersistentFlags())
  1610. c.Flags().AddFlagSet(c.parentsPflags)
  1611. }
  1612. // updateParentsPflags updates c.parentsPflags by adding
  1613. // new persistent flags of all parents.
  1614. // If c.parentsPflags == nil, it makes new.
  1615. func (c *Command) updateParentsPflags() {
  1616. if c.parentsPflags == nil {
  1617. c.parentsPflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError)
  1618. c.parentsPflags.SetOutput(c.flagErrorBuf)
  1619. c.parentsPflags.SortFlags = false
  1620. }
  1621. if c.globNormFunc != nil {
  1622. c.parentsPflags.SetNormalizeFunc(c.globNormFunc)
  1623. }
  1624. c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)
  1625. c.VisitParents(func(parent *Command) {
  1626. c.parentsPflags.AddFlagSet(parent.PersistentFlags())
  1627. })
  1628. }
  1629. // commandNameMatches checks if two command names are equal
  1630. // taking into account case sensitivity according to
  1631. // EnableCaseInsensitive global configuration.
  1632. func commandNameMatches(s string, t string) bool {
  1633. if EnableCaseInsensitive {
  1634. return strings.EqualFold(s, t)
  1635. }
  1636. return s == t
  1637. }