completions.go 33 KB

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