Do not try to load plugins for cobra commands

Cobra adds the commands 'help', '__complete' and '__completeNoDesc'
inside rootCmd.Execute(), however, when kubectl decides if it should
lookup plugins, rootCmd.Execute() had not been called yet.  Therefore,
the call to cmd.Find(cmdPathPieces) done by kubectl does not find the
commands added by Cobra.  To fix this we must check for them explicitly.

Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
This commit is contained in:
Marc Khouzam
2021-09-19 14:34:10 -04:00
parent bbd809cbd0
commit e703b3d253
2 changed files with 24 additions and 3 deletions

View File

@@ -102,9 +102,17 @@ func NewDefaultKubectlCommandWithArgs(pluginHandler PluginHandler, args []string
// only look for suitable extension executables if
// the specified command does not already exist
if _, _, err := cmd.Find(cmdPathPieces); err != nil {
if err := HandlePluginCommand(pluginHandler, cmdPathPieces); err != nil {
fmt.Fprintf(errout, "Error: %v\n", err)
os.Exit(1)
// Also check the commands that will be added by Cobra.
// These commands are only added once rootCmd.Execute() is called, so we
// need to check them explicitly here.
switch cmdPathPieces[0] {
case "help", cobra.ShellCompRequestCmd, cobra.ShellCompNoDescRequestCmd:
// Don't search for a plugin
default:
if err := HandlePluginCommand(pluginHandler, cmdPathPieces); err != nil {
fmt.Fprintf(errout, "Error: %v\n", err)
os.Exit(1)
}
}
}
}

View File

@@ -78,6 +78,19 @@ func TestKubectlCommandHandlesPlugins(t *testing.T) {
name: "test that a plugin does not execute over an existing command by the same name",
args: []string{"kubectl", "version"},
},
// The following tests make sure that commands added by Cobra cannot be shadowed by a plugin
{
name: "test that a plugin does not execute over Cobra's help command",
args: []string{"kubectl", "help"},
},
{
name: "test that a plugin does not execute over Cobra's __complete command",
args: []string{"kubectl", cobra.ShellCompRequestCmd},
},
{
name: "test that a plugin does not execute over Cobra's __completeNoDesc command",
args: []string{"kubectl", cobra.ShellCompNoDescRequestCmd},
},
}
for _, test := range tests {