command.go 54 KB

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