command.go 60 KB

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