2
0

command.go 46 KB

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