Skip to content

Completion detects non-flag argument as flag #1816

Closed
@oncilla

Description

@oncilla

We have encountered some odd behavior in the auto completion.
It appears that arguments with a dash as the second character are detected as flags by mistake.

The full reproducer with various test cases can be found here:
https://go.dev/play/p/UxqRkMcEX2a

The minimal reproducer is the following:

package main

import "github.com/spf13/cobra"

func main() {
	root := &cobra.Command{
		Use: "root",
	}
	root.SetArgs([]string{"__complete", "1-ff00:0:1", ""})
	root.Execute()
}

which results in the following output:

[Debug] [Error] Subcommand 'root' does not support flag '1'
:0
Completion ended with directive: ShellCompDirectiveDefault

I tracked down the issue and appears that we enter this branch by mistake:

cobra/completions.go

Lines 577 to 595 in fce8d8a

if isFlagArg(prevArg) {
// Only consider the case where the flag does not contain an =.
// If the flag contains an = it means it has already been fully processed,
// so we don't need to deal with it here.
if index := strings.Index(prevArg, "="); index < 0 {
if strings.HasPrefix(prevArg, "--") {
// Flag has full name
flagName = prevArg[2:]
} else {
// Flag is shorthand
// We have to get the last shorthand flag name
// e.g. `-asd` => d to provide the correct completion
// https://github.com/spf13/cobra/issues/1257
flagName = prevArg[len(prevArg)-1:]
}
// Remove the uncompleted flag or else there could be an error created
// for an invalid value for that flag
trimmedArgs = args[:len(args)-1]
}

In particular, it appears that the is isFlagArg classifies the argument as a flag byistake:

cobra/command.go

Lines 629 to 632 in fce8d8a

func isFlagArg(arg string) bool {
return ((len(arg) >= 3 && arg[1] == '-') ||
(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    lifecycle/frozenPrevents GitHub actions from labeling issues / PRs with stale and rotten

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions