Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix kubectl tab-completion and improve error messages
Browse files Browse the repository at this point in the history
Try to fix the following issues when `kubectl` is an alias for
`minikube kubectl --` and tab-completion for `kubectl` is enabled:

 1. When `--cluster name` form of command-line option is used, it
    conflicts with argument parsing, `name` is interpreted as plugin name.
    Call to `kubectl --cluster test help` leads to error `Error: flags
    cannot be placed before plugin name: --cluster`. Fix this by using
    `--cluster=name` form, which is correctly handled also in call
    `kubectl --cluster=test help`.
 2. When `--cluster=name` is added as first argument (as seen in original
    code), it still leads to error mentioned above when the command is
    unknown like in the call `kubectl --cluster=test unknown`. Fix this by
    inserting `--cluster=name` after all (sub-)commands and before any
    flags/options.
 3. The original code passed `--cluster=name` to normal `kubectl` calls,
    but omitted it for tab-completion calls. This might lead to wrong tab
    suggestions about pods, deployments and the like. Fix this by always
    adding `--cluster=name` option to the command line.
 4. In case of tab-completion, put the `--cluster=name` immediately after
    `__complete` command to prevent any interference with incomplete
    commands (just in case). This works fine and does not generate any
    errors like mentioned in point 2.
oldium committed Apr 8, 2023
1 parent 78d2885 commit c662261
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions cmd/minikube/cmd/kubectl.go
Original file line number Diff line number Diff line change
@@ -21,6 +21,7 @@ import (
"os"
"os/exec"
"path"
"strings"
"syscall"

"github.com/spf13/cobra"
@@ -96,9 +97,24 @@ host. Please be aware that when using --ssh all paths will apply to the remote m
os.Exit(1)
}

if len(args) > 1 && args[0] != "--help" && args[0] != cobra.ShellCompRequestCmd {
cluster := []string{"--cluster", cname}
args = append(cluster, args...)
if len(args) > 0 {
insertIndex := 0
if args[0] == cobra.ShellCompRequestCmd || args[0] == cobra.ShellCompNoDescRequestCmd {
// Insert right after __complete to allow code completion from the correct cluster.
insertIndex = 1
} else {
// Add cluster argument before first flag, but after all commands.
// This improves error message of kubectl in case the command is wrong.
insertIndex = len(args)
for i, arg := range args {
if strings.HasPrefix(arg, "-") {
insertIndex = i
break
}
}
}
clusterArg := "--cluster=" + cname
args = append(append(append([]string{}, args[:insertIndex]...), clusterArg), args[insertIndex:]...)
}

c, err := KubectlCommand(version, binaryMirror, args...)

0 comments on commit c662261

Please sign in to comment.