Skip to content

Impossible to provide completions for combined syntax of string-to-string flags #2309

@Airblader

Description

@Airblader

Let's say we have a --set=key=value flag that can be repeated, e.g. --set=k1=v1 --set=k2=v2. The string-to-string flag also supports a shorter syntax of --set=k1=v1,k2=v2. However, it appears to be impossible to provide completions for this combined syntax.

This is related to #1981, but there it was about string slice flags (where this does work); I cannot get the same to work for string-to-string flags.

If I ignore the prefix (everything up until the comma), completions just get filtered out. But if I try to provide the full prefix:

possibleCompletions := []string{"k2=v2", "k2=v3"}

func(cmd *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
	commaLastIndex := strings.LastIndex(toComplete, ",")

	var prefix string
	if commaLastIndex > -1 {
		prefix = toComplete[:commaLastIndex+1]
		toComplete = toComplete[commaLastIndex+1:]
	}

	out := make([]string, 0)
	for _, possibleCompletion := range possibleCompletions {
		out = append(out, prefix+possibleCompletion)
	}

	return out, cobra.ShellCompDirectiveNoFileComp
}

then completing cli --set=k1=v1,<TAB> results in cli --set=k1=k1=v1,k2=v.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions