Skip to content
Myr

completions.go

This file

Path

completions.go

1,024 lines · 38.1 KiB · Go

Last changed by

fix: prevent completions from mutating os.Args via append side effect (#2356)Varun Chawlabefore adoption746ef07

History of this file

Take it

1// Copyright 2013-2023 The Cobra Authors2//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 at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// 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 and13// limitations under the License.1415package cobra1617import (18	"fmt"19	"os"20	"regexp"21	"strconv"22	"strings"23	"sync"2425	"github.com/spf13/pflag"26)2728const (29	// ShellCompRequestCmd is the name of the hidden command that is used to request30	// completion results from the program.  It is used by the shell completion scripts.31	ShellCompRequestCmd = "__complete"32	// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request33	// completion results without their description.  It is used by the shell completion scripts.34	ShellCompNoDescRequestCmd = "__completeNoDesc"35)3637// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it.38var flagCompletionFunctions = map[*pflag.Flag]CompletionFunc{}3940// lock for reading and writing from flagCompletionFunctions41var flagCompletionMutex = &sync.RWMutex{}4243// ShellCompDirective is a bit map representing the different behaviors the shell44// can be instructed to have once completions have been provided.45type ShellCompDirective int4647type flagCompError struct {48	subCommand string49	flagName   string50}5152func (e *flagCompError) Error() string {53	return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'"54}5556const (57	// ShellCompDirectiveError indicates an error occurred and completions should be ignored.58	ShellCompDirectiveError ShellCompDirective = 1 << iota5960	// ShellCompDirectiveNoSpace indicates that the shell should not add a space61	// after the completion even if there is a single completion provided.62	ShellCompDirectiveNoSpace6364	// ShellCompDirectiveNoFileComp indicates that the shell should not provide65	// file completion even when no completion is provided.66	ShellCompDirectiveNoFileComp6768	// ShellCompDirectiveFilterFileExt indicates that the provided completions69	// should be used as file extension filters.70	// For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()71	// is a shortcut to using this directive explicitly.  The BashCompFilenameExt72	// annotation can also be used to obtain the same behavior for flags.73	ShellCompDirectiveFilterFileExt7475	// ShellCompDirectiveFilterDirs indicates that only directory names should76	// be provided in file completion.  To request directory names within another77	// directory, the returned completions should specify the directory within78	// which to search.  The BashCompSubdirsInDir annotation can be used to79	// obtain the same behavior but only for flags.80	ShellCompDirectiveFilterDirs8182	// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order83	// in which the completions are provided84	ShellCompDirectiveKeepOrder8586	// ===========================================================================8788	// All directives using iota should be above this one.89	// For internal use.90	shellCompDirectiveMaxValue9192	// ShellCompDirectiveDefault indicates to let the shell perform its default93	// behavior after completions have been provided.94	// This one must be last to avoid messing up the iota count.95	ShellCompDirectiveDefault ShellCompDirective = 096)9798const (99	// Constants for the completion command100	compCmdName              = "completion"101	compCmdNoDescFlagName    = "no-descriptions"102	compCmdNoDescFlagDesc    = "disable completion descriptions"103	compCmdNoDescFlagDefault = false104)105106// CompletionOptions are the options to control shell completion107type CompletionOptions struct {108	// DisableDefaultCmd prevents Cobra from creating a default 'completion' command109	DisableDefaultCmd bool110	// DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag111	// for shells that support completion descriptions112	DisableNoDescFlag bool113	// DisableDescriptions turns off all completion descriptions for shells114	// that support them115	DisableDescriptions bool116	// HiddenDefaultCmd makes the default 'completion' command hidden117	HiddenDefaultCmd bool118	// DefaultShellCompDirective sets the ShellCompDirective that is returned119	// if no special directive can be determined120	DefaultShellCompDirective *ShellCompDirective121}122123func (receiver *CompletionOptions) SetDefaultShellCompDirective(directive ShellCompDirective) {124	receiver.DefaultShellCompDirective = &directive125}126127// Completion is a string that can be used for completions128//129// two formats are supported:130//   - the completion choice131//   - the completion choice with a textual description (separated by a TAB).132//133// [CompletionWithDesc] can be used to create a completion string with a textual description.134//135// Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used.136type Completion = string137138// CompletionFunc is a function that provides completion results.139type CompletionFunc = func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)140141// CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format.142func CompletionWithDesc(choice string, description string) Completion {143	return choice + "\t" + description144}145146// NoFileCompletions can be used to disable file completion for commands that should147// not trigger file completions.148//149// This method satisfies [CompletionFunc].150// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].151func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {152	return nil, ShellCompDirectiveNoFileComp153}154155// FixedCompletions can be used to create a completion function which always156// returns the same results.157//158// This method returns a function that satisfies [CompletionFunc]159// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction].160func FixedCompletions(choices []Completion, directive ShellCompDirective) CompletionFunc {161	return func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) {162		return choices, directive163	}164}165166// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.167//168// You can use pre-defined completion functions such as [FixedCompletions] or [NoFileCompletions],169// or you can define your own.170func (c *Command) RegisterFlagCompletionFunc(flagName string, f CompletionFunc) error {171	flag := c.Flag(flagName)172	if flag == nil {173		return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)174	}175	flagCompletionMutex.Lock()176	defer flagCompletionMutex.Unlock()177178	if _, exists := flagCompletionFunctions[flag]; exists {179		return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)180	}181	flagCompletionFunctions[flag] = f182	return nil183}184185// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available.186func (c *Command) GetFlagCompletionFunc(flagName string) (CompletionFunc, bool) {187	flag := c.Flag(flagName)188	if flag == nil {189		return nil, false190	}191192	flagCompletionMutex.RLock()193	defer flagCompletionMutex.RUnlock()194195	completionFunc, exists := flagCompletionFunctions[flag]196	return completionFunc, exists197}198199// Returns a string listing the different directive enabled in the specified parameter200func (d ShellCompDirective) string() string {201	var directives []string202	if d&ShellCompDirectiveError != 0 {203		directives = append(directives, "ShellCompDirectiveError")204	}205	if d&ShellCompDirectiveNoSpace != 0 {206		directives = append(directives, "ShellCompDirectiveNoSpace")207	}208	if d&ShellCompDirectiveNoFileComp != 0 {209		directives = append(directives, "ShellCompDirectiveNoFileComp")210	}211	if d&ShellCompDirectiveFilterFileExt != 0 {212		directives = append(directives, "ShellCompDirectiveFilterFileExt")213	}214	if d&ShellCompDirectiveFilterDirs != 0 {215		directives = append(directives, "ShellCompDirectiveFilterDirs")216	}217	if d&ShellCompDirectiveKeepOrder != 0 {218		directives = append(directives, "ShellCompDirectiveKeepOrder")219	}220	if len(directives) == 0 {221		directives = append(directives, "ShellCompDirectiveDefault")222	}223224	if d >= shellCompDirectiveMaxValue {225		return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)226	}227	return strings.Join(directives, ", ")228}229230// initCompleteCmd adds a special hidden command that can be used to request custom completions.231func (c *Command) initCompleteCmd(args []string) {232	completeCmd := &Command{233		Use:                   fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),234		Aliases:               []string{ShellCompNoDescRequestCmd},235		DisableFlagsInUseLine: true,236		Hidden:                true,237		DisableFlagParsing:    true,238		Args:                  MinimumNArgs(1),239		Short:                 "Request shell completion choices for the specified command-line",240		Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",241			"to request completion choices for the specified command-line.", ShellCompRequestCmd),242		Run: func(cmd *Command, args []string) {243			finalCmd, completions, directive, err := cmd.getCompletions(args)244			if err != nil {245				CompErrorln(err.Error())246				// Keep going for multiple reasons:247				// 1- There could be some valid completions even though there was an error248				// 2- Even without completions, we need to print the directive249			}250251			noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd252			if !noDescriptions {253				if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil {254					noDescriptions = !doDescriptions255				}256			}257			noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable258			out := finalCmd.OutOrStdout()259			for _, comp := range completions {260				if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) {261					// Remove all activeHelp entries if it's disabled.262					continue263				}264				if noDescriptions {265					// Remove any description that may be included following a tab character.266					comp = strings.SplitN(comp, "\t", 2)[0]267				}268269				// Make sure we only write the first line to the output.270				// This is needed if a description contains a linebreak.271				// Otherwise the shell scripts will interpret the other lines as new flags272				// and could therefore provide a wrong completion.273				comp = strings.SplitN(comp, "\n", 2)[0]274275				// Finally trim the completion.  This is especially important to get rid276				// of a trailing tab when there are no description following it.277				// For example, a sub-command without a description should not be completed278				// with a tab at the end (or else zsh will show a -- following it279				// although there is no description).280				comp = strings.TrimSpace(comp)281282				// Print each possible completion to the output for the completion script to consume.283				fmt.Fprintln(out, comp)284			}285286			// As the last printout, print the completion directive for the completion script to parse.287			// The directive integer must be that last character following a single colon (:).288			// The completion script expects :<directive>289			fmt.Fprintf(out, ":%d\n", directive)290291			// Print some helpful info to stderr for the user to understand.292			// Output from stderr must be ignored by the completion script.293			fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())294		},295	}296	c.AddCommand(completeCmd)297	subCmd, _, err := c.Find(args)298	if err != nil || subCmd.Name() != ShellCompRequestCmd {299		// Only create this special command if it is actually being called.300		// This reduces possible side-effects of creating such a command;301		// for example, having this command would cause problems to a302		// cobra program that only consists of the root command, since this303		// command would cause the root command to suddenly have a subcommand.304		c.RemoveCommand(completeCmd)305	}306}307308// SliceValue is a reduced version of [pflag.SliceValue]. It is used to detect309// flags that accept multiple values and therefore can provide completion310// multiple times.311type SliceValue interface {312	// GetSlice returns the flag value list as an array of strings.313	GetSlice() []string314}315316func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCompDirective, error) {317	// The last argument, which is not completely typed by the user,318	// should not be part of the list of arguments319	toComplete := args[len(args)-1]320	// Copy trimmedArgs to a new slice to avoid mutating the caller's321	// backing array (which may be os.Args) when later appending "--".322	trimmedArgs := make([]string, len(args)-1)323	copy(trimmedArgs, args[:len(args)-1])324325	var finalCmd *Command326	var finalArgs []string327	var err error328	// Find the real command for which completion must be performed329	// check if we need to traverse here to parse local flags on parent commands330	if c.Root().TraverseChildren {331		finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)332	} else {333		// For Root commands that don't specify any value for their Args fields, when we call334		// Find(), if those Root commands don't have any sub-commands, they will accept arguments.335		// However, because we have added the __complete sub-command in the current code path, the336		// call to Find() -> legacyArgs() will return an error if there are any arguments.337		// To avoid this, we first remove the __complete command to get back to having no sub-commands.338		rootCmd := c.Root()339		if len(rootCmd.Commands()) == 1 {340			rootCmd.RemoveCommand(c)341		}342343		finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs)344	}345	if err != nil {346		// Unable to find the real command. E.g., <program> someInvalidCmd <TAB>347		return c, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs)348	}349	finalCmd.ctx = c.ctx350351	// These flags are normally added when `execute()` is called on `finalCmd`,352	// however, when doing completion, we don't call `finalCmd.execute()`.353	// Let's add the --help and --version flag ourselves but only if the finalCmd354	// has not disabled flag parsing; if flag parsing is disabled, it is up to the355	// finalCmd itself to handle the completion of *all* flags.356	if !finalCmd.DisableFlagParsing {357		finalCmd.InitDefaultHelpFlag()358		finalCmd.InitDefaultVersionFlag()359	}360361	// Check if we are doing flag value completion before parsing the flags.362	// This is important because if we are completing a flag value, we need to also363	// remove the flag name argument from the list of finalArgs or else the parsing364	// could fail due to an invalid value (incomplete) for the flag.365	flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)366367	// Check if interspersed is false or -- was set on a previous arg.368	// This works by counting the arguments. Normally -- is not counted as arg but369	// if -- was already set or interspersed is false and there is already one arg then370	// the extra added -- is counted as arg.371	flagCompletion := true372	_ = finalCmd.ParseFlags(append(finalArgs, "--"))373	newArgCount := finalCmd.Flags().NArg()374375	// Parse the flags early so we can check if required flags are set376	if err = finalCmd.ParseFlags(finalArgs); err != nil {377		return finalCmd, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())378	}379380	realArgCount := finalCmd.Flags().NArg()381	if newArgCount > realArgCount {382		// don't do flag completion (see above)383		flagCompletion = false384	}385	// Error while attempting to parse flags386	if flagErr != nil {387		// If error type is flagCompError and we don't want flagCompletion we should ignore the error388		if _, ok := flagErr.(*flagCompError); !ok || flagCompletion {389			return finalCmd, []Completion{}, ShellCompDirectiveDefault, flagErr390		}391	}392393	// Look for the --help or --version flags.  If they are present,394	// there should be no further completions.395	if helpOrVersionFlagPresent(finalCmd) {396		return finalCmd, []Completion{}, ShellCompDirectiveNoFileComp, nil397	}398399	// We only remove the flags from the arguments if DisableFlagParsing is not set.400	// This is important for commands which have requested to do their own flag completion.401	if !finalCmd.DisableFlagParsing {402		finalArgs = finalCmd.Flags().Args()403	}404405	if flag != nil && flagCompletion {406		// Check if we are completing a flag value subject to annotations407		if validExts, present := flag.Annotations[BashCompFilenameExt]; present {408			if len(validExts) != 0 {409				// File completion filtered by extensions410				return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil411			}412413			// The annotation requests simple file completion.  There is no reason to do414			// that since it is the default behavior anyway.  Let's ignore this annotation415			// in case the program also registered a completion function for this flag.416			// Even though it is a mistake on the program's side, let's be nice when we can.417		}418419		if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {420			if len(subDir) == 1 {421				// Directory completion from within a directory422				return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil423			}424			// Directory completion425			return finalCmd, []Completion{}, ShellCompDirectiveFilterDirs, nil426		}427	}428429	var completions []Completion430	var directive ShellCompDirective431432	// Enforce flag groups before doing flag completions433	finalCmd.enforceFlagGroupsForCompletion()434435	// Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true;436	// doing this allows for completion of persistent flag names even for commands that disable flag parsing.437	//438	// When doing completion of a flag name, as soon as an argument starts with439	// a '-' we know it is a flag.  We cannot use isFlagArg() here as it requires440	// the flag name to be complete441	if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion {442		// First check for required flags443		completions = completeRequireFlags(finalCmd, toComplete)444445		// If we have not found any required flags, only then can we show regular flags446		if len(completions) == 0 {447			doCompleteFlags := func(flag *pflag.Flag) {448				_, acceptsMultiple := flag.Value.(SliceValue)449				acceptsMultiple = acceptsMultiple ||450					strings.Contains(flag.Value.Type(), "Slice") ||451					strings.Contains(flag.Value.Type(), "Array") ||452					strings.HasPrefix(flag.Value.Type(), "stringTo")453454				if !flag.Changed || acceptsMultiple {455					// If the flag is not already present, or if it can be specified multiple times (Array, Slice, or stringTo)456					// we suggest it as a completion457					completions = append(completions, getFlagNameCompletions(flag, toComplete)...)458				}459			}460461			// We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands462			// that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and463			// non-inherited flags.464			finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {465				doCompleteFlags(flag)466			})467			// Try to complete non-inherited flags even if DisableFlagParsing==true.468			// This allows programs to tell Cobra about flags for completion even469			// if the actual parsing of flags is not done by Cobra.470			// For instance, Helm uses this to provide flag name completion for471			// some of its plugins.472			finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {473				doCompleteFlags(flag)474			})475		}476477		directive = ShellCompDirectiveNoFileComp478		if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {479			// If there is a single completion, the shell usually adds a space480			// after the completion.  We don't want that if the flag ends with an =481			directive = ShellCompDirectiveNoSpace482		}483484		if !finalCmd.DisableFlagParsing {485			// If DisableFlagParsing==false, we have completed the flags as known by Cobra;486			// we can return what we found.487			// If DisableFlagParsing==true, Cobra may not be aware of all flags, so we488			// let the logic continue to see if ValidArgsFunction needs to be called.489			return finalCmd, completions, directive, nil490		}491	} else {492		directive = ShellCompDirectiveDefault493		// check current and parent commands for a custom DefaultShellCompDirective494		for cmd := finalCmd; cmd != nil; cmd = cmd.parent {495			if cmd.CompletionOptions.DefaultShellCompDirective != nil {496				directive = *cmd.CompletionOptions.DefaultShellCompDirective497				break498			}499		}500501		if flag == nil {502			foundLocalNonPersistentFlag := false503			// If TraverseChildren is true on the root command we don't check for504			// local flags because we can use a local flag on a parent command505			if !finalCmd.Root().TraverseChildren {506				// Check if there are any local, non-persistent flags on the command-line507				localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()508				finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {509					if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {510						foundLocalNonPersistentFlag = true511					}512				})513			}514515			// Complete subcommand names, including the help command516			if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {517				// We only complete sub-commands if:518				// - there are no arguments on the command-line and519				// - there are no local, non-persistent flags on the command-line or TraverseChildren is true520				for _, subCmd := range finalCmd.Commands() {521					if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {522						if strings.HasPrefix(subCmd.Name(), toComplete) {523							completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short))524						}525						directive = ShellCompDirectiveNoFileComp526					}527				}528			}529530			// Complete required flags even without the '-' prefix531			completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)532533			// Always complete ValidArgs, even if we are completing a subcommand name.534			// This is for commands that have both subcommands and ValidArgs.535			if len(finalCmd.ValidArgs) > 0 {536				if len(finalArgs) == 0 {537					// ValidArgs are only for the first argument538					for _, validArg := range finalCmd.ValidArgs {539						if strings.HasPrefix(validArg, toComplete) {540							completions = append(completions, validArg)541						}542					}543					directive = ShellCompDirectiveNoFileComp544545					// If no completions were found within commands or ValidArgs,546					// see if there are any ArgAliases that should be completed.547					if len(completions) == 0 {548						for _, argAlias := range finalCmd.ArgAliases {549							if strings.HasPrefix(argAlias, toComplete) {550								completions = append(completions, argAlias)551							}552						}553					}554				}555556				// If there are ValidArgs specified (even if they don't match), we stop completion.557				// Only one of ValidArgs or ValidArgsFunction can be used for a single command.558				return finalCmd, completions, directive, nil559			}560561			// Let the logic continue so as to add any ValidArgsFunction completions,562			// even if we already found sub-commands.563			// This is for commands that have subcommands but also specify a ValidArgsFunction.564		}565	}566567	// Find the completion function for the flag or command568	var completionFn CompletionFunc569	if flag != nil && flagCompletion {570		flagCompletionMutex.RLock()571		completionFn = flagCompletionFunctions[flag]572		flagCompletionMutex.RUnlock()573	} else {574		completionFn = finalCmd.ValidArgsFunction575	}576	if completionFn != nil {577		// Go custom completion defined for this flag or command.578		// Call the registered completion function to get the completions.579		var comps []Completion580		comps, directive = completionFn(finalCmd, finalArgs, toComplete)581		completions = append(completions, comps...)582	}583584	return finalCmd, completions, directive, nil585}586587func helpOrVersionFlagPresent(cmd *Command) bool {588	if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil &&589		len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {590		return true591	}592	if helpFlag := cmd.Flags().Lookup(helpFlagName); helpFlag != nil &&593		len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {594		return true595	}596	return false597}598599func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion {600	if nonCompletableFlag(flag) {601		return []Completion{}602	}603604	var completions []Completion605	flagName := "--" + flag.Name606	if strings.HasPrefix(flagName, toComplete) {607		// Flag without the =608		completions = append(completions, CompletionWithDesc(flagName, flag.Usage))609610		// Why suggest both long forms: --flag and --flag= ?611		// This forces the user to *always* have to type either an = or a space after the flag name.612		// Let's be nice and avoid making users have to do that.613		// Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.614		// The = form will still work, we just won't suggest it.615		// This also makes the list of suggested flags shorter as we avoid all the = forms.616		//617		// if len(flag.NoOptDefVal) == 0 {618		// 	// Flag requires a value, so it can be suffixed with =619		// 	flagName += "="620		// 	completions = append(completions, CompletionWithDesc(flagName, flag.Usage))621		// }622	}623624	flagName = "-" + flag.Shorthand625	if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {626		completions = append(completions, CompletionWithDesc(flagName, flag.Usage))627	}628629	return completions630}631632func completeRequireFlags(finalCmd *Command, toComplete string) []Completion {633	var completions []Completion634635	doCompleteRequiredFlags := func(flag *pflag.Flag) {636		if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {637			if !flag.Changed {638				// If the flag is not already present, we suggest it as a completion639				completions = append(completions, getFlagNameCompletions(flag, toComplete)...)640			}641		}642	}643644	// We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands645	// that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and646	// non-inherited flags.647	finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {648		doCompleteRequiredFlags(flag)649	})650	finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {651		doCompleteRequiredFlags(flag)652	})653654	return completions655}656657func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {658	if finalCmd.DisableFlagParsing {659		// We only do flag completion if we are allowed to parse flags660		// This is important for commands which have requested to do their own flag completion.661		return nil, args, lastArg, nil662	}663664	var flagName string665	trimmedArgs := args666	flagWithEqual := false667	orgLastArg := lastArg668669	// When doing completion of a flag name, as soon as an argument starts with670	// a '-' we know it is a flag.  We cannot use isFlagArg() here as that function671	// requires the flag name to be complete672	if len(lastArg) > 0 && lastArg[0] == '-' {673		if index := strings.Index(lastArg, "="); index >= 0 {674			// Flag with an =675			if strings.HasPrefix(lastArg[:index], "--") {676				// Flag has full name677				flagName = lastArg[2:index]678			} else {679				// Flag is shorthand680				// We have to get the last shorthand flag name681				// e.g. `-asd` => d to provide the correct completion682				// https://github.com/spf13/cobra/issues/1257683				flagName = lastArg[index-1 : index]684			}685			lastArg = lastArg[index+1:]686			flagWithEqual = true687		} else {688			// Normal flag completion689			return nil, args, lastArg, nil690		}691	}692693	if len(flagName) == 0 {694		if len(args) > 0 {695			prevArg := args[len(args)-1]696			if isFlagArg(prevArg) {697				// Only consider the case where the flag does not contain an =.698				// If the flag contains an = it means it has already been fully processed,699				// so we don't need to deal with it here.700				if index := strings.Index(prevArg, "="); index < 0 {701					if strings.HasPrefix(prevArg, "--") {702						// Flag has full name703						flagName = prevArg[2:]704					} else {705						// Flag is shorthand706						// We have to get the last shorthand flag name707						// e.g. `-asd` => d to provide the correct completion708						// https://github.com/spf13/cobra/issues/1257709						flagName = prevArg[len(prevArg)-1:]710					}711					// Remove the uncompleted flag or else there could be an error created712					// for an invalid value for that flag713					trimmedArgs = args[:len(args)-1]714				}715			}716		}717	}718719	if len(flagName) == 0 {720		// Not doing flag completion721		return nil, trimmedArgs, lastArg, nil722	}723724	flag := findFlag(finalCmd, flagName)725	if flag == nil {726		// Flag not supported by this command, the interspersed option might be set so return the original args727		return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName}728	}729730	if !flagWithEqual {731		if len(flag.NoOptDefVal) != 0 {732			// We had assumed dealing with a two-word flag but the flag is a boolean flag.733			// In that case, there is no value following it, so we are not really doing flag completion.734			// Reset everything to do noun completion.735			trimmedArgs = args736			flag = nil737		}738	}739740	return flag, trimmedArgs, lastArg, nil741}742743// InitDefaultCompletionCmd adds a default 'completion' command to c.744// This function will do nothing if any of the following is true:745// 1- the feature has been explicitly disabled by the program,746// 2- c has no subcommands (to avoid creating one),747// 3- c already has a 'completion' command provided by the program.748func (c *Command) InitDefaultCompletionCmd(args ...string) {749	if c.CompletionOptions.DisableDefaultCmd {750		return751	}752753	for _, cmd := range c.commands {754		if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) {755			// A completion command is already available756			return757		}758	}759760	haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions761762	// Special case to know if there are sub-commands or not.763	hasSubCommands := false764	for _, cmd := range c.commands {765		if cmd.Name() != ShellCompRequestCmd && cmd.Name() != helpCommandName {766			// We found a real sub-command (not 'help' or '__complete')767			hasSubCommands = true768			break769		}770	}771772	completionCmd := &Command{773		Use:   compCmdName,774		Short: "Generate the autocompletion script for the specified shell",775		Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell.776See each sub-command's help for details on how to use the generated script.777`, c.Root().Name()),778		Args:              NoArgs,779		ValidArgsFunction: NoFileCompletions,780		Hidden:            c.CompletionOptions.HiddenDefaultCmd,781		GroupID:           c.completionCommandGroupID,782	}783	c.AddCommand(completionCmd)784785	if !hasSubCommands {786		// If the 'completion' command will be the only sub-command,787		// we only create it if it is actually being called.788		// This avoids breaking programs that would suddenly find themselves with789		// a subcommand, which would prevent them from accepting arguments.790		// We also create the 'completion' command if the user is triggering791		// shell completion for it (prog __complete completion '')792		subCmd, cmdArgs, err := c.Find(args)793		if err != nil || subCmd.Name() != compCmdName &&794			(subCmd.Name() != ShellCompRequestCmd || len(cmdArgs) <= 1 || cmdArgs[0] != compCmdName) {795			// The completion command is not being called or being completed so we remove it.796			c.RemoveCommand(completionCmd)797			return798		}799	}800801	out := c.OutOrStdout()802	noDesc := c.CompletionOptions.DisableDescriptions803	shortDesc := "Generate the autocompletion script for %s"804	bash := &Command{805		Use:   "bash",806		Short: fmt.Sprintf(shortDesc, "bash"),807		Long: fmt.Sprintf(`Generate the autocompletion script for the bash shell.808809This script depends on the 'bash-completion' package.810If it is not installed already, you can install it via your OS's package manager.811812To load completions in your current shell session:813814	source <(%[1]s completion bash)815816To load completions for every new session, execute once:817818#### Linux:819820	%[1]s completion bash > /etc/bash_completion.d/%[1]s821822#### macOS:823824	%[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s825826You will need to start a new shell for this setup to take effect.827`, c.Root().Name()),828		Args:                  NoArgs,829		DisableFlagsInUseLine: true,830		ValidArgsFunction:     NoFileCompletions,831		RunE: func(cmd *Command, args []string) error {832			return cmd.Root().GenBashCompletionV2(out, !noDesc)833		},834	}835	if haveNoDescFlag {836		bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)837	}838839	zsh := &Command{840		Use:   "zsh",841		Short: fmt.Sprintf(shortDesc, "zsh"),842		Long: fmt.Sprintf(`Generate the autocompletion script for the zsh shell.843844If shell completion is not already enabled in your environment you will need845to enable it.  You can execute the following once:846847	echo "autoload -U compinit; compinit" >> ~/.zshrc848849To load completions in your current shell session:850851	source <(%[1]s completion zsh)852853To load completions for every new session, execute once:854855#### Linux:856857	%[1]s completion zsh > "${fpath[1]}/_%[1]s"858859#### macOS:860861	%[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s862863You will need to start a new shell for this setup to take effect.864`, c.Root().Name()),865		Args:              NoArgs,866		ValidArgsFunction: NoFileCompletions,867		RunE: func(cmd *Command, args []string) error {868			if noDesc {869				return cmd.Root().GenZshCompletionNoDesc(out)870			}871			return cmd.Root().GenZshCompletion(out)872		},873	}874	if haveNoDescFlag {875		zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)876	}877878	fish := &Command{879		Use:   "fish",880		Short: fmt.Sprintf(shortDesc, "fish"),881		Long: fmt.Sprintf(`Generate the autocompletion script for the fish shell.882883To load completions in your current shell session:884885	%[1]s completion fish | source886887To load completions for every new session, execute once:888889	%[1]s completion fish > ~/.config/fish/completions/%[1]s.fish890891You will need to start a new shell for this setup to take effect.892`, c.Root().Name()),893		Args:              NoArgs,894		ValidArgsFunction: NoFileCompletions,895		RunE: func(cmd *Command, args []string) error {896			return cmd.Root().GenFishCompletion(out, !noDesc)897		},898	}899	if haveNoDescFlag {900		fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)901	}902903	powershell := &Command{904		Use:   "powershell",905		Short: fmt.Sprintf(shortDesc, "powershell"),906		Long: fmt.Sprintf(`Generate the autocompletion script for powershell.907908To load completions in your current shell session:909910	%[1]s completion powershell | Out-String | Invoke-Expression911912To load completions for every new session, add the output of the above command913to your powershell profile.914`, c.Root().Name()),915		Args:              NoArgs,916		ValidArgsFunction: NoFileCompletions,917		RunE: func(cmd *Command, args []string) error {918			if noDesc {919				return cmd.Root().GenPowerShellCompletion(out)920			}921			return cmd.Root().GenPowerShellCompletionWithDesc(out)922923		},924	}925	if haveNoDescFlag {926		powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)927	}928929	completionCmd.AddCommand(bash, zsh, fish, powershell)930}931932func findFlag(cmd *Command, name string) *pflag.Flag {933	flagSet := cmd.Flags()934	if len(name) == 1 {935		// First convert the short flag into a long flag936		// as the cmd.Flag() search only accepts long flags937		if short := flagSet.ShorthandLookup(name); short != nil {938			name = short.Name939		} else {940			set := cmd.InheritedFlags()941			if short = set.ShorthandLookup(name); short != nil {942				name = short.Name943			} else {944				return nil945			}946		}947	}948	return cmd.Flag(name)949}950951// CompDebug prints the specified string to the same file as where the952// completion script prints its logs.953// Note that completion printouts should never be on stdout as they would954// be wrongly interpreted as actual completion choices by the completion script.955func CompDebug(msg string, printToStdErr bool) {956	msg = fmt.Sprintf("[Debug] %s", msg)957958	// Such logs are only printed when the user has set the environment959	// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.960	if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {961		//nolint:gosec // G703:BASH_COMP_DEBUG_FILE intentionally user-controlled for completion debug logging.962		f, err := os.OpenFile(path,963			os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)964		if err == nil {965			defer f.Close()966			WriteStringAndCheck(f, msg)967		}968	}969970	if printToStdErr {971		// Must print to stderr for this not to be read by the completion script.972		fmt.Fprint(os.Stderr, msg)973	}974}975976// CompDebugln prints the specified string with a newline at the end977// to the same file as where the completion script prints its logs.978// Such logs are only printed when the user has set the environment979// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.980func CompDebugln(msg string, printToStdErr bool) {981	CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)982}983984// CompError prints the specified completion message to stderr.985func CompError(msg string) {986	msg = fmt.Sprintf("[Error] %s", msg)987	CompDebug(msg, true)988}989990// CompErrorln prints the specified completion message to stderr with a newline at the end.991func CompErrorln(msg string) {992	CompError(fmt.Sprintf("%s\n", msg))993}994995// These values should not be changed: users will be using them explicitly.996const (997	configEnvVarGlobalPrefix       = "COBRA"998	configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS"999)10001001var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`)10021003// configEnvVar returns the name of the program-specific configuration environment1004// variable.  It has the format <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the1005// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`.1006func configEnvVar(name, suffix string) string {1007	// This format should not be changed: users will be using it explicitly.1008	v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix))1009	v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_")1010	return v1011}10121013// getEnvConfig returns the value of the configuration environment variable1014// <PROGRAM>_<SUFFIX> where <PROGRAM> is the name of the root command in upper1015// case, with all non-ASCII-alphanumeric characters replaced by `_`.1016// If the value is empty or not set, the value of the environment variable1017// COBRA_<SUFFIX> is returned instead.1018func getEnvConfig(cmd *Command, suffix string) string {1019	v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix))1020	if v == "" {1021		v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix))1022	}1023	return v1024}