2
0

command.go 47 KB

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