command.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072
  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.ParseErrorsAllowlist
  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. const 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. const 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. const 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. // FLow the context down to be used in help text
  1126. if cmd.ctx == nil {
  1127. cmd.ctx = c.ctx
  1128. }
  1129. cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
  1130. cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
  1131. CheckErr(cmd.Help())
  1132. }
  1133. },
  1134. GroupID: c.helpCommandGroupID,
  1135. }
  1136. }
  1137. c.RemoveCommand(c.helpCommand)
  1138. c.AddCommand(c.helpCommand)
  1139. }
  1140. // ResetCommands delete parent, subcommand and help command from c.
  1141. func (c *Command) ResetCommands() {
  1142. c.parent = nil
  1143. c.commands = nil
  1144. c.helpCommand = nil
  1145. c.parentsPflags = nil
  1146. }
  1147. // Sorts commands by their names.
  1148. type commandSorterByName []*Command
  1149. func (c commandSorterByName) Len() int { return len(c) }
  1150. func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
  1151. func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }
  1152. // Commands returns a sorted slice of child commands.
  1153. func (c *Command) Commands() []*Command {
  1154. // do not sort commands if it already sorted or sorting was disabled
  1155. if EnableCommandSorting && !c.commandsAreSorted {
  1156. sort.Sort(commandSorterByName(c.commands))
  1157. c.commandsAreSorted = true
  1158. }
  1159. return c.commands
  1160. }
  1161. // AddCommand adds one or more commands to this parent command.
  1162. func (c *Command) AddCommand(cmds ...*Command) {
  1163. for i, x := range cmds {
  1164. if cmds[i] == c {
  1165. panic("Command can't be a child of itself")
  1166. }
  1167. cmds[i].parent = c
  1168. // update max lengths
  1169. usageLen := len(x.Use)
  1170. if usageLen > c.commandsMaxUseLen {
  1171. c.commandsMaxUseLen = usageLen
  1172. }
  1173. commandPathLen := len(x.CommandPath())
  1174. if commandPathLen > c.commandsMaxCommandPathLen {
  1175. c.commandsMaxCommandPathLen = commandPathLen
  1176. }
  1177. nameLen := len(x.Name())
  1178. if nameLen > c.commandsMaxNameLen {
  1179. c.commandsMaxNameLen = nameLen
  1180. }
  1181. // If global normalization function exists, update all children
  1182. if c.globNormFunc != nil {
  1183. x.SetGlobalNormalizationFunc(c.globNormFunc)
  1184. }
  1185. c.commands = append(c.commands, x)
  1186. c.commandsAreSorted = false
  1187. }
  1188. }
  1189. // Groups returns a slice of child command groups.
  1190. func (c *Command) Groups() []*Group {
  1191. return c.commandgroups
  1192. }
  1193. // AllChildCommandsHaveGroup returns if all subcommands are assigned to a group
  1194. func (c *Command) AllChildCommandsHaveGroup() bool {
  1195. for _, sub := range c.commands {
  1196. if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {
  1197. return false
  1198. }
  1199. }
  1200. return true
  1201. }
  1202. // ContainsGroup return if groupID exists in the list of command groups.
  1203. func (c *Command) ContainsGroup(groupID string) bool {
  1204. for _, x := range c.commandgroups {
  1205. if x.ID == groupID {
  1206. return true
  1207. }
  1208. }
  1209. return false
  1210. }
  1211. // AddGroup adds one or more command groups to this parent command.
  1212. func (c *Command) AddGroup(groups ...*Group) {
  1213. c.commandgroups = append(c.commandgroups, groups...)
  1214. }
  1215. // RemoveCommand removes one or more commands from a parent command.
  1216. func (c *Command) RemoveCommand(cmds ...*Command) {
  1217. commands := []*Command{}
  1218. main:
  1219. for _, command := range c.commands {
  1220. for _, cmd := range cmds {
  1221. if command == cmd {
  1222. command.parent = nil
  1223. continue main
  1224. }
  1225. }
  1226. commands = append(commands, command)
  1227. }
  1228. c.commands = commands
  1229. // recompute all lengths
  1230. c.commandsMaxUseLen = 0
  1231. c.commandsMaxCommandPathLen = 0
  1232. c.commandsMaxNameLen = 0
  1233. for _, command := range c.commands {
  1234. usageLen := len(command.Use)
  1235. if usageLen > c.commandsMaxUseLen {
  1236. c.commandsMaxUseLen = usageLen
  1237. }
  1238. commandPathLen := len(command.CommandPath())
  1239. if commandPathLen > c.commandsMaxCommandPathLen {
  1240. c.commandsMaxCommandPathLen = commandPathLen
  1241. }
  1242. nameLen := len(command.Name())
  1243. if nameLen > c.commandsMaxNameLen {
  1244. c.commandsMaxNameLen = nameLen
  1245. }
  1246. }
  1247. }
  1248. // Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
  1249. func (c *Command) Print(i ...interface{}) {
  1250. fmt.Fprint(c.OutOrStderr(), i...)
  1251. }
  1252. // Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
  1253. func (c *Command) Println(i ...interface{}) {
  1254. c.Print(fmt.Sprintln(i...))
  1255. }
  1256. // Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
  1257. func (c *Command) Printf(format string, i ...interface{}) {
  1258. c.Print(fmt.Sprintf(format, i...))
  1259. }
  1260. // PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.
  1261. func (c *Command) PrintErr(i ...interface{}) {
  1262. fmt.Fprint(c.ErrOrStderr(), i...)
  1263. }
  1264. // PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.
  1265. func (c *Command) PrintErrln(i ...interface{}) {
  1266. c.PrintErr(fmt.Sprintln(i...))
  1267. }
  1268. // PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.
  1269. func (c *Command) PrintErrf(format string, i ...interface{}) {
  1270. c.PrintErr(fmt.Sprintf(format, i...))
  1271. }
  1272. // CommandPath returns the full path to this command.
  1273. func (c *Command) CommandPath() string {
  1274. if c.HasParent() {
  1275. return c.Parent().CommandPath() + " " + c.Name()
  1276. }
  1277. return c.DisplayName()
  1278. }
  1279. // DisplayName returns the name to display in help text. Returns command Name()
  1280. // If CommandDisplayNameAnnoation is not set
  1281. func (c *Command) DisplayName() string {
  1282. if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {
  1283. return displayName
  1284. }
  1285. return c.Name()
  1286. }
  1287. // UseLine puts out the full usage for a given command (including parents).
  1288. func (c *Command) UseLine() string {
  1289. var useline string
  1290. use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1)
  1291. if c.HasParent() {
  1292. useline = c.parent.CommandPath() + " " + use
  1293. } else {
  1294. useline = use
  1295. }
  1296. if c.DisableFlagsInUseLine {
  1297. return useline
  1298. }
  1299. if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
  1300. useline += " [flags]"
  1301. }
  1302. return useline
  1303. }
  1304. // DebugFlags used to determine which flags have been assigned to which commands
  1305. // and which persist.
  1306. func (c *Command) DebugFlags() {
  1307. c.Println("DebugFlags called on", c.Name())
  1308. var debugflags func(*Command)
  1309. debugflags = func(x *Command) {
  1310. if x.HasFlags() || x.HasPersistentFlags() {
  1311. c.Println(x.Name())
  1312. }
  1313. if x.HasFlags() {
  1314. x.flags.VisitAll(func(f *flag.Flag) {
  1315. if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {
  1316. c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")
  1317. } else {
  1318. c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")
  1319. }
  1320. })
  1321. }
  1322. if x.HasPersistentFlags() {
  1323. x.pflags.VisitAll(func(f *flag.Flag) {
  1324. if x.HasFlags() {
  1325. if x.flags.Lookup(f.Name) == nil {
  1326. c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
  1327. }
  1328. } else {
  1329. c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
  1330. }
  1331. })
  1332. }
  1333. c.Println(x.flagErrorBuf)
  1334. if x.HasSubCommands() {
  1335. for _, y := range x.commands {
  1336. debugflags(y)
  1337. }
  1338. }
  1339. }
  1340. debugflags(c)
  1341. }
  1342. // Name returns the command's name: the first word in the use line.
  1343. func (c *Command) Name() string {
  1344. name := c.Use
  1345. i := strings.Index(name, " ")
  1346. if i >= 0 {
  1347. name = name[:i]
  1348. }
  1349. return name
  1350. }
  1351. // HasAlias determines if a given string is an alias of the command.
  1352. func (c *Command) HasAlias(s string) bool {
  1353. for _, a := range c.Aliases {
  1354. if commandNameMatches(a, s) {
  1355. return true
  1356. }
  1357. }
  1358. return false
  1359. }
  1360. // CalledAs returns the command name or alias that was used to invoke
  1361. // this command or an empty string if the command has not been called.
  1362. func (c *Command) CalledAs() string {
  1363. if c.commandCalledAs.called {
  1364. return c.commandCalledAs.name
  1365. }
  1366. return ""
  1367. }
  1368. // hasNameOrAliasPrefix returns true if the Name or any of aliases start
  1369. // with prefix
  1370. func (c *Command) hasNameOrAliasPrefix(prefix string) bool {
  1371. if strings.HasPrefix(c.Name(), prefix) {
  1372. c.commandCalledAs.name = c.Name()
  1373. return true
  1374. }
  1375. for _, alias := range c.Aliases {
  1376. if strings.HasPrefix(alias, prefix) {
  1377. c.commandCalledAs.name = alias
  1378. return true
  1379. }
  1380. }
  1381. return false
  1382. }
  1383. // NameAndAliases returns a list of the command name and all aliases
  1384. func (c *Command) NameAndAliases() string {
  1385. return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
  1386. }
  1387. // HasExample determines if the command has example.
  1388. func (c *Command) HasExample() bool {
  1389. return len(c.Example) > 0
  1390. }
  1391. // Runnable determines if the command is itself runnable.
  1392. func (c *Command) Runnable() bool {
  1393. return c.Run != nil || c.RunE != nil
  1394. }
  1395. // HasSubCommands determines if the command has children commands.
  1396. func (c *Command) HasSubCommands() bool {
  1397. return len(c.commands) > 0
  1398. }
  1399. // IsAvailableCommand determines if a command is available as a non-help command
  1400. // (this includes all non deprecated/hidden commands).
  1401. func (c *Command) IsAvailableCommand() bool {
  1402. if len(c.Deprecated) != 0 || c.Hidden {
  1403. return false
  1404. }
  1405. if c.HasParent() && c.Parent().helpCommand == c {
  1406. return false
  1407. }
  1408. if c.Runnable() || c.HasAvailableSubCommands() {
  1409. return true
  1410. }
  1411. return false
  1412. }
  1413. // IsAdditionalHelpTopicCommand determines if a command is an additional
  1414. // help topic command; additional help topic command is determined by the
  1415. // fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
  1416. // are runnable/hidden/deprecated.
  1417. // Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
  1418. func (c *Command) IsAdditionalHelpTopicCommand() bool {
  1419. // if a command is runnable, deprecated, or hidden it is not a 'help' command
  1420. if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
  1421. return false
  1422. }
  1423. // if any non-help sub commands are found, the command is not a 'help' command
  1424. for _, sub := range c.commands {
  1425. if !sub.IsAdditionalHelpTopicCommand() {
  1426. return false
  1427. }
  1428. }
  1429. // the command either has no sub commands, or no non-help sub commands
  1430. return true
  1431. }
  1432. // HasHelpSubCommands determines if a command has any available 'help' sub commands
  1433. // that need to be shown in the usage/help default template under 'additional help
  1434. // topics'.
  1435. func (c *Command) HasHelpSubCommands() bool {
  1436. // return true on the first found available 'help' sub command
  1437. for _, sub := range c.commands {
  1438. if sub.IsAdditionalHelpTopicCommand() {
  1439. return true
  1440. }
  1441. }
  1442. // the command either has no sub commands, or no available 'help' sub commands
  1443. return false
  1444. }
  1445. // HasAvailableSubCommands determines if a command has available sub commands that
  1446. // need to be shown in the usage/help default template under 'available commands'.
  1447. func (c *Command) HasAvailableSubCommands() bool {
  1448. // return true on the first found available (non deprecated/help/hidden)
  1449. // sub command
  1450. for _, sub := range c.commands {
  1451. if sub.IsAvailableCommand() {
  1452. return true
  1453. }
  1454. }
  1455. // the command either has no sub commands, or no available (non deprecated/help/hidden)
  1456. // sub commands
  1457. return false
  1458. }
  1459. // HasParent determines if the command is a child command.
  1460. func (c *Command) HasParent() bool {
  1461. return c.parent != nil
  1462. }
  1463. // GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.
  1464. func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
  1465. return c.globNormFunc
  1466. }
  1467. // Flags returns the complete FlagSet that applies
  1468. // to this command (local and persistent declared here and by all parents).
  1469. func (c *Command) Flags() *flag.FlagSet {
  1470. if c.flags == nil {
  1471. c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
  1472. if c.flagErrorBuf == nil {
  1473. c.flagErrorBuf = new(bytes.Buffer)
  1474. }
  1475. c.flags.SetOutput(c.flagErrorBuf)
  1476. }
  1477. return c.flags
  1478. }
  1479. // LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
  1480. // This function does not modify the flags of the current command, it's purpose is to return the current state.
  1481. func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
  1482. persistentFlags := c.PersistentFlags()
  1483. out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
  1484. c.LocalFlags().VisitAll(func(f *flag.Flag) {
  1485. if persistentFlags.Lookup(f.Name) == nil {
  1486. out.AddFlag(f)
  1487. }
  1488. })
  1489. return out
  1490. }
  1491. // LocalFlags returns the local FlagSet specifically set in the current command.
  1492. // This function does not modify the flags of the current command, it's purpose is to return the current state.
  1493. func (c *Command) LocalFlags() *flag.FlagSet {
  1494. c.mergePersistentFlags()
  1495. if c.lflags == nil {
  1496. c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
  1497. if c.flagErrorBuf == nil {
  1498. c.flagErrorBuf = new(bytes.Buffer)
  1499. }
  1500. c.lflags.SetOutput(c.flagErrorBuf)
  1501. }
  1502. c.lflags.SortFlags = c.Flags().SortFlags
  1503. if c.globNormFunc != nil {
  1504. c.lflags.SetNormalizeFunc(c.globNormFunc)
  1505. }
  1506. addToLocal := func(f *flag.Flag) {
  1507. // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag
  1508. if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {
  1509. c.lflags.AddFlag(f)
  1510. }
  1511. }
  1512. c.Flags().VisitAll(addToLocal)
  1513. c.PersistentFlags().VisitAll(addToLocal)
  1514. return c.lflags
  1515. }
  1516. // InheritedFlags returns all flags which were inherited from parent commands.
  1517. // This function does not modify the flags of the current command, it's purpose is to return the current state.
  1518. func (c *Command) InheritedFlags() *flag.FlagSet {
  1519. c.mergePersistentFlags()
  1520. if c.iflags == nil {
  1521. c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
  1522. if c.flagErrorBuf == nil {
  1523. c.flagErrorBuf = new(bytes.Buffer)
  1524. }
  1525. c.iflags.SetOutput(c.flagErrorBuf)
  1526. }
  1527. local := c.LocalFlags()
  1528. if c.globNormFunc != nil {
  1529. c.iflags.SetNormalizeFunc(c.globNormFunc)
  1530. }
  1531. c.parentsPflags.VisitAll(func(f *flag.Flag) {
  1532. if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
  1533. c.iflags.AddFlag(f)
  1534. }
  1535. })
  1536. return c.iflags
  1537. }
  1538. // NonInheritedFlags returns all flags which were not inherited from parent commands.
  1539. // This function does not modify the flags of the current command, it's purpose is to return the current state.
  1540. func (c *Command) NonInheritedFlags() *flag.FlagSet {
  1541. return c.LocalFlags()
  1542. }
  1543. // PersistentFlags returns the persistent FlagSet specifically set in the current command.
  1544. func (c *Command) PersistentFlags() *flag.FlagSet {
  1545. if c.pflags == nil {
  1546. c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
  1547. if c.flagErrorBuf == nil {
  1548. c.flagErrorBuf = new(bytes.Buffer)
  1549. }
  1550. c.pflags.SetOutput(c.flagErrorBuf)
  1551. }
  1552. return c.pflags
  1553. }
  1554. // ResetFlags deletes all flags from command.
  1555. func (c *Command) ResetFlags() {
  1556. c.flagErrorBuf = new(bytes.Buffer)
  1557. c.flagErrorBuf.Reset()
  1558. c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
  1559. c.flags.SetOutput(c.flagErrorBuf)
  1560. c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
  1561. c.pflags.SetOutput(c.flagErrorBuf)
  1562. c.lflags = nil
  1563. c.iflags = nil
  1564. c.parentsPflags = nil
  1565. }
  1566. // HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
  1567. func (c *Command) HasFlags() bool {
  1568. return c.Flags().HasFlags()
  1569. }
  1570. // HasPersistentFlags checks if the command contains persistent flags.
  1571. func (c *Command) HasPersistentFlags() bool {
  1572. return c.PersistentFlags().HasFlags()
  1573. }
  1574. // HasLocalFlags checks if the command has flags specifically declared locally.
  1575. func (c *Command) HasLocalFlags() bool {
  1576. return c.LocalFlags().HasFlags()
  1577. }
  1578. // HasInheritedFlags checks if the command has flags inherited from its parent command.
  1579. func (c *Command) HasInheritedFlags() bool {
  1580. return c.InheritedFlags().HasFlags()
  1581. }
  1582. // HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
  1583. // structure) which are not hidden or deprecated.
  1584. func (c *Command) HasAvailableFlags() bool {
  1585. return c.Flags().HasAvailableFlags()
  1586. }
  1587. // HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
  1588. func (c *Command) HasAvailablePersistentFlags() bool {
  1589. return c.PersistentFlags().HasAvailableFlags()
  1590. }
  1591. // HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
  1592. // or deprecated.
  1593. func (c *Command) HasAvailableLocalFlags() bool {
  1594. return c.LocalFlags().HasAvailableFlags()
  1595. }
  1596. // HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are
  1597. // not hidden or deprecated.
  1598. func (c *Command) HasAvailableInheritedFlags() bool {
  1599. return c.InheritedFlags().HasAvailableFlags()
  1600. }
  1601. // Flag climbs up the command tree looking for matching flag.
  1602. func (c *Command) Flag(name string) (flag *flag.Flag) {
  1603. flag = c.Flags().Lookup(name)
  1604. if flag == nil {
  1605. flag = c.persistentFlag(name)
  1606. }
  1607. return
  1608. }
  1609. // Recursively find matching persistent flag.
  1610. func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
  1611. if c.HasPersistentFlags() {
  1612. flag = c.PersistentFlags().Lookup(name)
  1613. }
  1614. if flag == nil {
  1615. c.updateParentsPflags()
  1616. flag = c.parentsPflags.Lookup(name)
  1617. }
  1618. return
  1619. }
  1620. // ParseFlags parses persistent flag tree and local flags.
  1621. func (c *Command) ParseFlags(args []string) error {
  1622. if c.DisableFlagParsing {
  1623. return nil
  1624. }
  1625. if c.flagErrorBuf == nil {
  1626. c.flagErrorBuf = new(bytes.Buffer)
  1627. }
  1628. beforeErrorBufLen := c.flagErrorBuf.Len()
  1629. c.mergePersistentFlags()
  1630. // do it here after merging all flags and just before parse
  1631. c.Flags().ParseErrorsAllowlist = flag.ParseErrorsAllowlist(c.FParseErrWhitelist)
  1632. err := c.Flags().Parse(args)
  1633. // Print warnings if they occurred (e.g. deprecated flag messages).
  1634. if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
  1635. c.Print(c.flagErrorBuf.String())
  1636. }
  1637. return err
  1638. }
  1639. // Parent returns a commands parent command.
  1640. func (c *Command) Parent() *Command {
  1641. return c.parent
  1642. }
  1643. // mergePersistentFlags merges c.PersistentFlags() to c.Flags()
  1644. // and adds missing persistent flags of all parents.
  1645. func (c *Command) mergePersistentFlags() {
  1646. c.updateParentsPflags()
  1647. c.Flags().AddFlagSet(c.PersistentFlags())
  1648. c.Flags().AddFlagSet(c.parentsPflags)
  1649. }
  1650. // updateParentsPflags updates c.parentsPflags by adding
  1651. // new persistent flags of all parents.
  1652. // If c.parentsPflags == nil, it makes new.
  1653. func (c *Command) updateParentsPflags() {
  1654. if c.parentsPflags == nil {
  1655. c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
  1656. c.parentsPflags.SetOutput(c.flagErrorBuf)
  1657. c.parentsPflags.SortFlags = false
  1658. }
  1659. if c.globNormFunc != nil {
  1660. c.parentsPflags.SetNormalizeFunc(c.globNormFunc)
  1661. }
  1662. c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)
  1663. c.VisitParents(func(parent *Command) {
  1664. c.parentsPflags.AddFlagSet(parent.PersistentFlags())
  1665. })
  1666. }
  1667. // commandNameMatches checks if two command names are equal
  1668. // taking into account case sensitivity according to
  1669. // EnableCaseInsensitive global configuration.
  1670. func commandNameMatches(s string, t string) bool {
  1671. if EnableCaseInsensitive {
  1672. return strings.EqualFold(s, t)
  1673. }
  1674. return s == t
  1675. }
  1676. // tmplFunc holds a template and a function that will execute said template.
  1677. type tmplFunc struct {
  1678. tmpl string
  1679. fn func(io.Writer, interface{}) error
  1680. }
  1681. const defaultUsageTemplate = `Usage:{{if .Runnable}}
  1682. {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
  1683. {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
  1684. Aliases:
  1685. {{.NameAndAliases}}{{end}}{{if .HasExample}}
  1686. Examples:
  1687. {{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}
  1688. Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
  1689. {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}
  1690. {{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}
  1691. {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}
  1692. Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}
  1693. {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
  1694. Flags:
  1695. {{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
  1696. Global Flags:
  1697. {{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
  1698. Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
  1699. {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
  1700. Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
  1701. `
  1702. // defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync.
  1703. func defaultUsageFunc(w io.Writer, in interface{}) error {
  1704. c := in.(*Command)
  1705. fmt.Fprint(w, "Usage:")
  1706. if c.Runnable() {
  1707. fmt.Fprintf(w, "\n %s", c.UseLine())
  1708. }
  1709. if c.HasAvailableSubCommands() {
  1710. fmt.Fprintf(w, "\n %s [command]", c.CommandPath())
  1711. }
  1712. if len(c.Aliases) > 0 {
  1713. fmt.Fprintf(w, "\n\nAliases:\n")
  1714. fmt.Fprintf(w, " %s", c.NameAndAliases())
  1715. }
  1716. if c.HasExample() {
  1717. fmt.Fprintf(w, "\n\nExamples:\n")
  1718. fmt.Fprintf(w, "%s", c.Example)
  1719. }
  1720. if c.HasAvailableSubCommands() {
  1721. cmds := c.Commands()
  1722. if len(c.Groups()) == 0 {
  1723. fmt.Fprintf(w, "\n\nAvailable Commands:")
  1724. for _, subcmd := range cmds {
  1725. if subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName {
  1726. fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
  1727. }
  1728. }
  1729. } else {
  1730. for _, group := range c.Groups() {
  1731. fmt.Fprintf(w, "\n\n%s", group.Title)
  1732. for _, subcmd := range cmds {
  1733. if subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {
  1734. fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
  1735. }
  1736. }
  1737. }
  1738. if !c.AllChildCommandsHaveGroup() {
  1739. fmt.Fprintf(w, "\n\nAdditional Commands:")
  1740. for _, subcmd := range cmds {
  1741. if subcmd.GroupID == "" && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) {
  1742. fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
  1743. }
  1744. }
  1745. }
  1746. }
  1747. }
  1748. if c.HasAvailableLocalFlags() {
  1749. fmt.Fprintf(w, "\n\nFlags:\n")
  1750. fmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages()))
  1751. }
  1752. if c.HasAvailableInheritedFlags() {
  1753. fmt.Fprintf(w, "\n\nGlobal Flags:\n")
  1754. fmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages()))
  1755. }
  1756. if c.HasHelpSubCommands() {
  1757. fmt.Fprintf(w, "\n\nAdditional help topics:")
  1758. for _, subcmd := range c.Commands() {
  1759. if subcmd.IsAdditionalHelpTopicCommand() {
  1760. fmt.Fprintf(w, "\n %s %s", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short)
  1761. }
  1762. }
  1763. }
  1764. if c.HasAvailableSubCommands() {
  1765. fmt.Fprintf(w, "\n\nUse \"%s [command] --help\" for more information about a command.", c.CommandPath())
  1766. }
  1767. fmt.Fprintln(w)
  1768. return nil
  1769. }
  1770. const defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
  1771. {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
  1772. // defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync.
  1773. func defaultHelpFunc(w io.Writer, in interface{}) error {
  1774. c := in.(*Command)
  1775. usage := c.Long
  1776. if usage == "" {
  1777. usage = c.Short
  1778. }
  1779. usage = trimRightSpace(usage)
  1780. if usage != "" {
  1781. fmt.Fprintln(w, usage)
  1782. fmt.Fprintln(w)
  1783. }
  1784. if c.Runnable() || c.HasSubCommands() {
  1785. fmt.Fprint(w, c.UsageString())
  1786. }
  1787. return nil
  1788. }
  1789. const defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
  1790. `
  1791. // defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync.
  1792. func defaultVersionFunc(w io.Writer, in interface{}) error {
  1793. c := in.(*Command)
  1794. _, err := fmt.Fprintf(w, "%s version %s\n", c.DisplayName(), c.Version)
  1795. return err
  1796. }