completions.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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
  15. import (
  16. "fmt"
  17. "os"
  18. "regexp"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "github.com/spf13/pflag"
  23. )
  24. const (
  25. // ShellCompRequestCmd is the name of the hidden command that is used to request
  26. // completion results from the program. It is used by the shell completion scripts.
  27. ShellCompRequestCmd = "__complete"
  28. // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request
  29. // completion results without their description. It is used by the shell completion scripts.
  30. ShellCompNoDescRequestCmd = "__completeNoDesc"
  31. )
  32. // Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it.
  33. var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
  34. // lock for reading and writing from flagCompletionFunctions
  35. var flagCompletionMutex = &sync.RWMutex{}
  36. // ShellCompDirective is a bit map representing the different behaviors the shell
  37. // can be instructed to have once completions have been provided.
  38. type ShellCompDirective int
  39. type flagCompError struct {
  40. subCommand string
  41. flagName string
  42. }
  43. func (e *flagCompError) Error() string {
  44. return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'"
  45. }
  46. const (
  47. // ShellCompDirectiveError indicates an error occurred and completions should be ignored.
  48. ShellCompDirectiveError ShellCompDirective = 1 << iota
  49. // ShellCompDirectiveNoSpace indicates that the shell should not add a space
  50. // after the completion even if there is a single completion provided.
  51. ShellCompDirectiveNoSpace
  52. // ShellCompDirectiveNoFileComp indicates that the shell should not provide
  53. // file completion even when no completion is provided.
  54. ShellCompDirectiveNoFileComp
  55. // ShellCompDirectiveFilterFileExt indicates that the provided completions
  56. // should be used as file extension filters.
  57. // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()
  58. // is a shortcut to using this directive explicitly. The BashCompFilenameExt
  59. // annotation can also be used to obtain the same behavior for flags.
  60. ShellCompDirectiveFilterFileExt
  61. // ShellCompDirectiveFilterDirs indicates that only directory names should
  62. // be provided in file completion. To request directory names within another
  63. // directory, the returned completions should specify the directory within
  64. // which to search. The BashCompSubdirsInDir annotation can be used to
  65. // obtain the same behavior but only for flags.
  66. ShellCompDirectiveFilterDirs
  67. // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order
  68. // in which the completions are provided
  69. ShellCompDirectiveKeepOrder
  70. // ===========================================================================
  71. // All directives using iota should be above this one.
  72. // For internal use.
  73. shellCompDirectiveMaxValue
  74. // ShellCompDirectiveDefault indicates to let the shell perform its default
  75. // behavior after completions have been provided.
  76. // This one must be last to avoid messing up the iota count.
  77. ShellCompDirectiveDefault ShellCompDirective = 0
  78. )
  79. const (
  80. // Constants for the completion command
  81. compCmdName = "completion"
  82. compCmdNoDescFlagName = "no-descriptions"
  83. compCmdNoDescFlagDesc = "disable completion descriptions"
  84. compCmdNoDescFlagDefault = false
  85. )
  86. // CompletionOptions are the options to control shell completion
  87. type CompletionOptions struct {
  88. // DisableDefaultCmd prevents Cobra from creating a default 'completion' command
  89. DisableDefaultCmd bool
  90. // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag
  91. // for shells that support completion descriptions
  92. DisableNoDescFlag bool
  93. // DisableDescriptions turns off all completion descriptions for shells
  94. // that support them
  95. DisableDescriptions bool
  96. // HiddenDefaultCmd makes the default 'completion' command hidden
  97. HiddenDefaultCmd bool
  98. }
  99. // NoFileCompletions can be used to disable file completion for commands that should
  100. // not trigger file completions.
  101. func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
  102. return nil, ShellCompDirectiveNoFileComp
  103. }
  104. // FixedCompletions can be used to create a completion function which always
  105. // returns the same results.
  106. func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
  107. return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
  108. return choices, directive
  109. }
  110. }
  111. // RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
  112. func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {
  113. flag := c.Flag(flagName)
  114. if flag == nil {
  115. return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)
  116. }
  117. flagCompletionMutex.Lock()
  118. defer flagCompletionMutex.Unlock()
  119. if _, exists := flagCompletionFunctions[flag]; exists {
  120. return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)
  121. }
  122. flagCompletionFunctions[flag] = f
  123. return nil
  124. }
  125. // GetFlagCompletionFunc returns the completion function for the given flag of the command, if available.
  126. func (c *Command) GetFlagCompletionFunc(flagName string) (func(*Command, []string, string) ([]string, ShellCompDirective), bool) {
  127. flag := c.Flag(flagName)
  128. if flag == nil {
  129. return nil, false
  130. }
  131. flagCompletionMutex.RLock()
  132. defer flagCompletionMutex.RUnlock()
  133. completionFunc, exists := flagCompletionFunctions[flag]
  134. return completionFunc, exists
  135. }
  136. // Returns a string listing the different directive enabled in the specified parameter
  137. func (d ShellCompDirective) string() string {
  138. var directives []string
  139. if d&ShellCompDirectiveError != 0 {
  140. directives = append(directives, "ShellCompDirectiveError")
  141. }
  142. if d&ShellCompDirectiveNoSpace != 0 {
  143. directives = append(directives, "ShellCompDirectiveNoSpace")
  144. }
  145. if d&ShellCompDirectiveNoFileComp != 0 {
  146. directives = append(directives, "ShellCompDirectiveNoFileComp")
  147. }
  148. if d&ShellCompDirectiveFilterFileExt != 0 {
  149. directives = append(directives, "ShellCompDirectiveFilterFileExt")
  150. }
  151. if d&ShellCompDirectiveFilterDirs != 0 {
  152. directives = append(directives, "ShellCompDirectiveFilterDirs")
  153. }
  154. if d&ShellCompDirectiveKeepOrder != 0 {
  155. directives = append(directives, "ShellCompDirectiveKeepOrder")
  156. }
  157. if len(directives) == 0 {
  158. directives = append(directives, "ShellCompDirectiveDefault")
  159. }
  160. if d >= shellCompDirectiveMaxValue {
  161. return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)
  162. }
  163. return strings.Join(directives, ", ")
  164. }
  165. // initCompleteCmd adds a special hidden command that can be used to request custom completions.
  166. func (c *Command) initCompleteCmd(args []string) {
  167. completeCmd := &Command{
  168. Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),
  169. Aliases: []string{ShellCompNoDescRequestCmd},
  170. DisableFlagsInUseLine: true,
  171. Hidden: true,
  172. DisableFlagParsing: true,
  173. Args: MinimumNArgs(1),
  174. Short: "Request shell completion choices for the specified command-line",
  175. Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",
  176. "to request completion choices for the specified command-line.", ShellCompRequestCmd),
  177. Run: func(cmd *Command, args []string) {
  178. finalCmd, completions, directive, err := cmd.getCompletions(args)
  179. if err != nil {
  180. CompErrorln(err.Error())
  181. // Keep going for multiple reasons:
  182. // 1- There could be some valid completions even though there was an error
  183. // 2- Even without completions, we need to print the directive
  184. }
  185. noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd
  186. if !noDescriptions {
  187. if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil {
  188. noDescriptions = !doDescriptions
  189. }
  190. }
  191. noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable
  192. out := finalCmd.OutOrStdout()
  193. for _, comp := range completions {
  194. if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) {
  195. // Remove all activeHelp entries if it's disabled.
  196. continue
  197. }
  198. if noDescriptions {
  199. // Remove any description that may be included following a tab character.
  200. comp = strings.SplitN(comp, "\t", 2)[0]
  201. }
  202. // Make sure we only write the first line to the output.
  203. // This is needed if a description contains a linebreak.
  204. // Otherwise the shell scripts will interpret the other lines as new flags
  205. // and could therefore provide a wrong completion.
  206. comp = strings.SplitN(comp, "\n", 2)[0]
  207. // Finally trim the completion. This is especially important to get rid
  208. // of a trailing tab when there are no description following it.
  209. // For example, a sub-command without a description should not be completed
  210. // with a tab at the end (or else zsh will show a -- following it
  211. // although there is no description).
  212. comp = strings.TrimSpace(comp)
  213. // Print each possible completion to the output for the completion script to consume.
  214. fmt.Fprintln(out, comp)
  215. }
  216. // As the last printout, print the completion directive for the completion script to parse.
  217. // The directive integer must be that last character following a single colon (:).
  218. // The completion script expects :<directive>
  219. fmt.Fprintf(out, ":%d\n", directive)
  220. // Print some helpful info to stderr for the user to understand.
  221. // Output from stderr must be ignored by the completion script.
  222. fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())
  223. },
  224. }
  225. c.AddCommand(completeCmd)
  226. subCmd, _, err := c.Find(args)
  227. if err != nil || subCmd.Name() != ShellCompRequestCmd {
  228. // Only create this special command if it is actually being called.
  229. // This reduces possible side-effects of creating such a command;
  230. // for example, having this command would cause problems to a
  231. // cobra program that only consists of the root command, since this
  232. // command would cause the root command to suddenly have a subcommand.
  233. c.RemoveCommand(completeCmd)
  234. }
  235. }
  236. func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {
  237. // The last argument, which is not completely typed by the user,
  238. // should not be part of the list of arguments
  239. toComplete := args[len(args)-1]
  240. trimmedArgs := args[:len(args)-1]
  241. var finalCmd *Command
  242. var finalArgs []string
  243. var err error
  244. // Find the real command for which completion must be performed
  245. // check if we need to traverse here to parse local flags on parent commands
  246. if c.Root().TraverseChildren {
  247. finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)
  248. } else {
  249. // For Root commands that don't specify any value for their Args fields, when we call
  250. // Find(), if those Root commands don't have any sub-commands, they will accept arguments.
  251. // However, because we have added the __complete sub-command in the current code path, the
  252. // call to Find() -> legacyArgs() will return an error if there are any arguments.
  253. // To avoid this, we first remove the __complete command to get back to having no sub-commands.
  254. rootCmd := c.Root()
  255. if len(rootCmd.Commands()) == 1 {
  256. rootCmd.RemoveCommand(c)
  257. }
  258. finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs)
  259. }
  260. if err != nil {
  261. // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>
  262. return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs)
  263. }
  264. finalCmd.ctx = c.ctx
  265. // These flags are normally added when `execute()` is called on `finalCmd`,
  266. // however, when doing completion, we don't call `finalCmd.execute()`.
  267. // Let's add the --help and --version flag ourselves but only if the finalCmd
  268. // has not disabled flag parsing; if flag parsing is disabled, it is up to the
  269. // finalCmd itself to handle the completion of *all* flags.
  270. if !finalCmd.DisableFlagParsing {
  271. finalCmd.InitDefaultHelpFlag()
  272. finalCmd.InitDefaultVersionFlag()
  273. }
  274. // Check if we are doing flag value completion before parsing the flags.
  275. // This is important because if we are completing a flag value, we need to also
  276. // remove the flag name argument from the list of finalArgs or else the parsing
  277. // could fail due to an invalid value (incomplete) for the flag.
  278. flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)
  279. // Check if interspersed is false or -- was set on a previous arg.
  280. // This works by counting the arguments. Normally -- is not counted as arg but
  281. // if -- was already set or interspersed is false and there is already one arg then
  282. // the extra added -- is counted as arg.
  283. flagCompletion := true
  284. _ = finalCmd.ParseFlags(append(finalArgs, "--"))
  285. newArgCount := finalCmd.Flags().NArg()
  286. // Parse the flags early so we can check if required flags are set
  287. if err = finalCmd.ParseFlags(finalArgs); err != nil {
  288. return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
  289. }
  290. realArgCount := finalCmd.Flags().NArg()
  291. if newArgCount > realArgCount {
  292. // don't do flag completion (see above)
  293. flagCompletion = false
  294. }
  295. // Error while attempting to parse flags
  296. if flagErr != nil {
  297. // If error type is flagCompError and we don't want flagCompletion we should ignore the error
  298. if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) {
  299. return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr
  300. }
  301. }
  302. // Look for the --help or --version flags. If they are present,
  303. // there should be no further completions.
  304. if helpOrVersionFlagPresent(finalCmd) {
  305. return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil
  306. }
  307. // We only remove the flags from the arguments if DisableFlagParsing is not set.
  308. // This is important for commands which have requested to do their own flag completion.
  309. if !finalCmd.DisableFlagParsing {
  310. finalArgs = finalCmd.Flags().Args()
  311. }
  312. if flag != nil && flagCompletion {
  313. // Check if we are completing a flag value subject to annotations
  314. if validExts, present := flag.Annotations[BashCompFilenameExt]; present {
  315. if len(validExts) != 0 {
  316. // File completion filtered by extensions
  317. return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil
  318. }
  319. // The annotation requests simple file completion. There is no reason to do
  320. // that since it is the default behavior anyway. Let's ignore this annotation
  321. // in case the program also registered a completion function for this flag.
  322. // Even though it is a mistake on the program's side, let's be nice when we can.
  323. }
  324. if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {
  325. if len(subDir) == 1 {
  326. // Directory completion from within a directory
  327. return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil
  328. }
  329. // Directory completion
  330. return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil
  331. }
  332. }
  333. var completions []string
  334. var directive ShellCompDirective
  335. // Enforce flag groups before doing flag completions
  336. finalCmd.enforceFlagGroupsForCompletion()
  337. // Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true;
  338. // doing this allows for completion of persistent flag names even for commands that disable flag parsing.
  339. //
  340. // When doing completion of a flag name, as soon as an argument starts with
  341. // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires
  342. // the flag name to be complete
  343. if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion {
  344. // First check for required flags
  345. completions = completeRequireFlags(finalCmd, toComplete)
  346. // If we have not found any required flags, only then can we show regular flags
  347. if len(completions) == 0 {
  348. doCompleteFlags := func(flag *pflag.Flag) {
  349. if !flag.Changed ||
  350. strings.Contains(flag.Value.Type(), "Slice") ||
  351. strings.Contains(flag.Value.Type(), "Array") {
  352. // If the flag is not already present, or if it can be specified multiple times (Array or Slice)
  353. // we suggest it as a completion
  354. completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
  355. }
  356. }
  357. // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands
  358. // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and
  359. // non-inherited flags.
  360. finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
  361. doCompleteFlags(flag)
  362. })
  363. // Try to complete non-inherited flags even if DisableFlagParsing==true.
  364. // This allows programs to tell Cobra about flags for completion even
  365. // if the actual parsing of flags is not done by Cobra.
  366. // For instance, Helm uses this to provide flag name completion for
  367. // some of its plugins.
  368. finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
  369. doCompleteFlags(flag)
  370. })
  371. }
  372. directive = ShellCompDirectiveNoFileComp
  373. if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {
  374. // If there is a single completion, the shell usually adds a space
  375. // after the completion. We don't want that if the flag ends with an =
  376. directive = ShellCompDirectiveNoSpace
  377. }
  378. if !finalCmd.DisableFlagParsing {
  379. // If DisableFlagParsing==false, we have completed the flags as known by Cobra;
  380. // we can return what we found.
  381. // If DisableFlagParsing==true, Cobra may not be aware of all flags, so we
  382. // let the logic continue to see if ValidArgsFunction needs to be called.
  383. return finalCmd, completions, directive, nil
  384. }
  385. } else {
  386. directive = ShellCompDirectiveDefault
  387. if flag == nil {
  388. foundLocalNonPersistentFlag := false
  389. // If TraverseChildren is true on the root command we don't check for
  390. // local flags because we can use a local flag on a parent command
  391. if !finalCmd.Root().TraverseChildren {
  392. // Check if there are any local, non-persistent flags on the command-line
  393. localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()
  394. finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
  395. if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {
  396. foundLocalNonPersistentFlag = true
  397. }
  398. })
  399. }
  400. // Complete subcommand names, including the help command
  401. if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {
  402. // We only complete sub-commands if:
  403. // - there are no arguments on the command-line and
  404. // - there are no local, non-persistent flags on the command-line or TraverseChildren is true
  405. for _, subCmd := range finalCmd.Commands() {
  406. if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {
  407. if strings.HasPrefix(subCmd.Name(), toComplete) {
  408. completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
  409. }
  410. directive = ShellCompDirectiveNoFileComp
  411. }
  412. }
  413. }
  414. // Complete required flags even without the '-' prefix
  415. completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)
  416. // Always complete ValidArgs, even if we are completing a subcommand name.
  417. // This is for commands that have both subcommands and ValidArgs.
  418. if len(finalCmd.ValidArgs) > 0 {
  419. if len(finalArgs) == 0 {
  420. // ValidArgs are only for the first argument
  421. for _, validArg := range finalCmd.ValidArgs {
  422. if strings.HasPrefix(validArg, toComplete) {
  423. completions = append(completions, validArg)
  424. }
  425. }
  426. directive = ShellCompDirectiveNoFileComp
  427. // If no completions were found within commands or ValidArgs,
  428. // see if there are any ArgAliases that should be completed.
  429. if len(completions) == 0 {
  430. for _, argAlias := range finalCmd.ArgAliases {
  431. if strings.HasPrefix(argAlias, toComplete) {
  432. completions = append(completions, argAlias)
  433. }
  434. }
  435. }
  436. }
  437. // If there are ValidArgs specified (even if they don't match), we stop completion.
  438. // Only one of ValidArgs or ValidArgsFunction can be used for a single command.
  439. return finalCmd, completions, directive, nil
  440. }
  441. // Let the logic continue so as to add any ValidArgsFunction completions,
  442. // even if we already found sub-commands.
  443. // This is for commands that have subcommands but also specify a ValidArgsFunction.
  444. }
  445. }
  446. // Find the completion function for the flag or command
  447. var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
  448. if flag != nil && flagCompletion {
  449. flagCompletionMutex.RLock()
  450. completionFn = flagCompletionFunctions[flag]
  451. flagCompletionMutex.RUnlock()
  452. } else {
  453. completionFn = finalCmd.ValidArgsFunction
  454. }
  455. if completionFn != nil {
  456. // Go custom completion defined for this flag or command.
  457. // Call the registered completion function to get the completions.
  458. var comps []string
  459. comps, directive = completionFn(finalCmd, finalArgs, toComplete)
  460. completions = append(completions, comps...)
  461. }
  462. return finalCmd, completions, directive, nil
  463. }
  464. func helpOrVersionFlagPresent(cmd *Command) bool {
  465. if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil &&
  466. len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {
  467. return true
  468. }
  469. if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil &&
  470. len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {
  471. return true
  472. }
  473. return false
  474. }
  475. func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
  476. if nonCompletableFlag(flag) {
  477. return []string{}
  478. }
  479. var completions []string
  480. flagName := "--" + flag.Name
  481. if strings.HasPrefix(flagName, toComplete) {
  482. // Flag without the =
  483. completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
  484. // Why suggest both long forms: --flag and --flag= ?
  485. // This forces the user to *always* have to type either an = or a space after the flag name.
  486. // Let's be nice and avoid making users have to do that.
  487. // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.
  488. // The = form will still work, we just won't suggest it.
  489. // This also makes the list of suggested flags shorter as we avoid all the = forms.
  490. //
  491. // if len(flag.NoOptDefVal) == 0 {
  492. // // Flag requires a value, so it can be suffixed with =
  493. // flagName += "="
  494. // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
  495. // }
  496. }
  497. flagName = "-" + flag.Shorthand
  498. if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {
  499. completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
  500. }
  501. return completions
  502. }
  503. func completeRequireFlags(finalCmd *Command, toComplete string) []string {
  504. var completions []string
  505. doCompleteRequiredFlags := func(flag *pflag.Flag) {
  506. if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {
  507. if !flag.Changed {
  508. // If the flag is not already present, we suggest it as a completion
  509. completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
  510. }
  511. }
  512. }
  513. // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands
  514. // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and
  515. // non-inherited flags.
  516. finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
  517. doCompleteRequiredFlags(flag)
  518. })
  519. finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
  520. doCompleteRequiredFlags(flag)
  521. })
  522. return completions
  523. }
  524. func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {
  525. if finalCmd.DisableFlagParsing {
  526. // We only do flag completion if we are allowed to parse flags
  527. // This is important for commands which have requested to do their own flag completion.
  528. return nil, args, lastArg, nil
  529. }
  530. var flagName string
  531. trimmedArgs := args
  532. flagWithEqual := false
  533. orgLastArg := lastArg
  534. // When doing completion of a flag name, as soon as an argument starts with
  535. // a '-' we know it is a flag. We cannot use isFlagArg() here as that function
  536. // requires the flag name to be complete
  537. if len(lastArg) > 0 && lastArg[0] == '-' {
  538. if index := strings.Index(lastArg, "="); index >= 0 {
  539. // Flag with an =
  540. if strings.HasPrefix(lastArg[:index], "--") {
  541. // Flag has full name
  542. flagName = lastArg[2:index]
  543. } else {
  544. // Flag is shorthand
  545. // We have to get the last shorthand flag name
  546. // e.g. `-asd` => d to provide the correct completion
  547. // https://github.com/spf13/cobra/issues/1257
  548. flagName = lastArg[index-1 : index]
  549. }
  550. lastArg = lastArg[index+1:]
  551. flagWithEqual = true
  552. } else {
  553. // Normal flag completion
  554. return nil, args, lastArg, nil
  555. }
  556. }
  557. if len(flagName) == 0 {
  558. if len(args) > 0 {
  559. prevArg := args[len(args)-1]
  560. if isFlagArg(prevArg) {
  561. // Only consider the case where the flag does not contain an =.
  562. // If the flag contains an = it means it has already been fully processed,
  563. // so we don't need to deal with it here.
  564. if index := strings.Index(prevArg, "="); index < 0 {
  565. if strings.HasPrefix(prevArg, "--") {
  566. // Flag has full name
  567. flagName = prevArg[2:]
  568. } else {
  569. // Flag is shorthand
  570. // We have to get the last shorthand flag name
  571. // e.g. `-asd` => d to provide the correct completion
  572. // https://github.com/spf13/cobra/issues/1257
  573. flagName = prevArg[len(prevArg)-1:]
  574. }
  575. // Remove the uncompleted flag or else there could be an error created
  576. // for an invalid value for that flag
  577. trimmedArgs = args[:len(args)-1]
  578. }
  579. }
  580. }
  581. }
  582. if len(flagName) == 0 {
  583. // Not doing flag completion
  584. return nil, trimmedArgs, lastArg, nil
  585. }
  586. flag := findFlag(finalCmd, flagName)
  587. if flag == nil {
  588. // Flag not supported by this command, the interspersed option might be set so return the original args
  589. return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName}
  590. }
  591. if !flagWithEqual {
  592. if len(flag.NoOptDefVal) != 0 {
  593. // We had assumed dealing with a two-word flag but the flag is a boolean flag.
  594. // In that case, there is no value following it, so we are not really doing flag completion.
  595. // Reset everything to do noun completion.
  596. trimmedArgs = args
  597. flag = nil
  598. }
  599. }
  600. return flag, trimmedArgs, lastArg, nil
  601. }
  602. // InitDefaultCompletionCmd adds a default 'completion' command to c.
  603. // This function will do nothing if any of the following is true:
  604. // 1- the feature has been explicitly disabled by the program,
  605. // 2- c has no subcommands (to avoid creating one),
  606. // 3- c already has a 'completion' command provided by the program.
  607. func (c *Command) InitDefaultCompletionCmd() {
  608. if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {
  609. return
  610. }
  611. for _, cmd := range c.commands {
  612. if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) {
  613. // A completion command is already available
  614. return
  615. }
  616. }
  617. haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions
  618. completionCmd := &Command{
  619. Use: compCmdName,
  620. Short: "Generate the autocompletion script for the specified shell",
  621. Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell.
  622. See each sub-command's help for details on how to use the generated script.
  623. `, c.Root().Name()),
  624. Args: NoArgs,
  625. ValidArgsFunction: NoFileCompletions,
  626. Hidden: c.CompletionOptions.HiddenDefaultCmd,
  627. GroupID: c.completionCommandGroupID,
  628. }
  629. c.AddCommand(completionCmd)
  630. out := c.OutOrStdout()
  631. noDesc := c.CompletionOptions.DisableDescriptions
  632. shortDesc := "Generate the autocompletion script for %s"
  633. bash := &Command{
  634. Use: "bash",
  635. Short: fmt.Sprintf(shortDesc, "bash"),
  636. Long: fmt.Sprintf(`Generate the autocompletion script for the bash shell.
  637. This script depends on the 'bash-completion' package.
  638. If it is not installed already, you can install it via your OS's package manager.
  639. To load completions in your current shell session:
  640. source <(%[1]s completion bash)
  641. To load completions for every new session, execute once:
  642. #### Linux:
  643. %[1]s completion bash > /etc/bash_completion.d/%[1]s
  644. #### macOS:
  645. %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
  646. You will need to start a new shell for this setup to take effect.
  647. `, c.Root().Name()),
  648. Args: NoArgs,
  649. DisableFlagsInUseLine: true,
  650. ValidArgsFunction: NoFileCompletions,
  651. RunE: func(cmd *Command, args []string) error {
  652. return cmd.Root().GenBashCompletionV2(out, !noDesc)
  653. },
  654. }
  655. if haveNoDescFlag {
  656. bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
  657. }
  658. zsh := &Command{
  659. Use: "zsh",
  660. Short: fmt.Sprintf(shortDesc, "zsh"),
  661. Long: fmt.Sprintf(`Generate the autocompletion script for the zsh shell.
  662. If shell completion is not already enabled in your environment you will need
  663. to enable it. You can execute the following once:
  664. echo "autoload -U compinit; compinit" >> ~/.zshrc
  665. To load completions in your current shell session:
  666. source <(%[1]s completion zsh)
  667. To load completions for every new session, execute once:
  668. #### Linux:
  669. %[1]s completion zsh > "${fpath[1]}/_%[1]s"
  670. #### macOS:
  671. %[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s
  672. You will need to start a new shell for this setup to take effect.
  673. `, c.Root().Name()),
  674. Args: NoArgs,
  675. ValidArgsFunction: NoFileCompletions,
  676. RunE: func(cmd *Command, args []string) error {
  677. if noDesc {
  678. return cmd.Root().GenZshCompletionNoDesc(out)
  679. }
  680. return cmd.Root().GenZshCompletion(out)
  681. },
  682. }
  683. if haveNoDescFlag {
  684. zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
  685. }
  686. fish := &Command{
  687. Use: "fish",
  688. Short: fmt.Sprintf(shortDesc, "fish"),
  689. Long: fmt.Sprintf(`Generate the autocompletion script for the fish shell.
  690. To load completions in your current shell session:
  691. %[1]s completion fish | source
  692. To load completions for every new session, execute once:
  693. %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
  694. You will need to start a new shell for this setup to take effect.
  695. `, c.Root().Name()),
  696. Args: NoArgs,
  697. ValidArgsFunction: NoFileCompletions,
  698. RunE: func(cmd *Command, args []string) error {
  699. return cmd.Root().GenFishCompletion(out, !noDesc)
  700. },
  701. }
  702. if haveNoDescFlag {
  703. fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
  704. }
  705. powershell := &Command{
  706. Use: "powershell",
  707. Short: fmt.Sprintf(shortDesc, "powershell"),
  708. Long: fmt.Sprintf(`Generate the autocompletion script for powershell.
  709. To load completions in your current shell session:
  710. %[1]s completion powershell | Out-String | Invoke-Expression
  711. To load completions for every new session, add the output of the above command
  712. to your powershell profile.
  713. `, c.Root().Name()),
  714. Args: NoArgs,
  715. ValidArgsFunction: NoFileCompletions,
  716. RunE: func(cmd *Command, args []string) error {
  717. if noDesc {
  718. return cmd.Root().GenPowerShellCompletion(out)
  719. }
  720. return cmd.Root().GenPowerShellCompletionWithDesc(out)
  721. },
  722. }
  723. if haveNoDescFlag {
  724. powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)
  725. }
  726. completionCmd.AddCommand(bash, zsh, fish, powershell)
  727. }
  728. func findFlag(cmd *Command, name string) *pflag.Flag {
  729. flagSet := cmd.Flags()
  730. if len(name) == 1 {
  731. // First convert the short flag into a long flag
  732. // as the cmd.Flag() search only accepts long flags
  733. if short := flagSet.ShorthandLookup(name); short != nil {
  734. name = short.Name
  735. } else {
  736. set := cmd.InheritedFlags()
  737. if short = set.ShorthandLookup(name); short != nil {
  738. name = short.Name
  739. } else {
  740. return nil
  741. }
  742. }
  743. }
  744. return cmd.Flag(name)
  745. }
  746. // CompDebug prints the specified string to the same file as where the
  747. // completion script prints its logs.
  748. // Note that completion printouts should never be on stdout as they would
  749. // be wrongly interpreted as actual completion choices by the completion script.
  750. func CompDebug(msg string, printToStdErr bool) {
  751. msg = fmt.Sprintf("[Debug] %s", msg)
  752. // Such logs are only printed when the user has set the environment
  753. // variable BASH_COMP_DEBUG_FILE to the path of some file to be used.
  754. if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {
  755. f, err := os.OpenFile(path,
  756. os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  757. if err == nil {
  758. defer f.Close()
  759. WriteStringAndCheck(f, msg)
  760. }
  761. }
  762. if printToStdErr {
  763. // Must print to stderr for this not to be read by the completion script.
  764. fmt.Fprint(os.Stderr, msg)
  765. }
  766. }
  767. // CompDebugln prints the specified string with a newline at the end
  768. // to the same file as where the completion script prints its logs.
  769. // Such logs are only printed when the user has set the environment
  770. // variable BASH_COMP_DEBUG_FILE to the path of some file to be used.
  771. func CompDebugln(msg string, printToStdErr bool) {
  772. CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)
  773. }
  774. // CompError prints the specified completion message to stderr.
  775. func CompError(msg string) {
  776. msg = fmt.Sprintf("[Error] %s", msg)
  777. CompDebug(msg, true)
  778. }
  779. // CompErrorln prints the specified completion message to stderr with a newline at the end.
  780. func CompErrorln(msg string) {
  781. CompError(fmt.Sprintf("%s\n", msg))
  782. }
  783. // These values should not be changed: users will be using them explicitly.
  784. const (
  785. configEnvVarGlobalPrefix = "COBRA"
  786. configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS"
  787. )
  788. var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)
  789. // configEnvVar returns the name of the program-specific configuration environment
  790. // variable. It has the format <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the
  791. // root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.
  792. func configEnvVar(name, suffix string) string {
  793. // This format should not be changed: users will be using it explicitly.
  794. v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix))
  795. v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_")
  796. return v
  797. }
  798. // getEnvConfig returns the value of the configuration environment variable
  799. // <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the root command in upper
  800. // case, with all non-ASCII-alphanumeric characters replaced by `_`.
  801. // If the value is empty or not set, the value of the environment variable
  802. // COBRA_<SUFFIX> is returned instead.
  803. func getEnvConfig(cmd *Command, suffix string) string {
  804. v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix))
  805. if v == "" {
  806. v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix))
  807. }
  808. return v
  809. }