http urls monitor.

command.go 42KB

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