HandlePluginCommand receives a pluginHandler and command-line arguments and attempts to find a plugin executable on the PATH that satisfies the given arguments.
(pluginHandler PluginHandler, cmdArgs []string, minArgs int)
| 107 | // HandlePluginCommand receives a pluginHandler and command-line arguments and attempts to find |
| 108 | // a plugin executable on the PATH that satisfies the given arguments. |
| 109 | func HandlePluginCommand(pluginHandler PluginHandler, cmdArgs []string, minArgs int) error { |
| 110 | var remainingArgs []string // all "non-flag" arguments |
| 111 | for _, arg := range cmdArgs { |
| 112 | if strings.HasPrefix(arg, "-") { |
| 113 | break |
| 114 | } |
| 115 | remainingArgs = append(remainingArgs, strings.Replace(arg, "-", "_", -1)) |
| 116 | } |
| 117 | |
| 118 | if len(remainingArgs) == 0 { |
| 119 | // the length of cmdArgs is at least 1 |
| 120 | return fmt.Errorf("flags cannot be placed before plugin name: %s", cmdArgs[0]) |
| 121 | } |
| 122 | |
| 123 | foundBinaryPath := "" |
| 124 | |
| 125 | // attempt to find binary, starting at longest possible name with given cmdArgs |
| 126 | for len(remainingArgs) > 0 { |
| 127 | path, found := pluginHandler.Lookup(strings.Join(remainingArgs, "-")) |
| 128 | if !found { |
| 129 | remainingArgs = remainingArgs[:len(remainingArgs)-1] |
| 130 | if len(remainingArgs) < minArgs { |
| 131 | // we shouldn't continue searching with shorter names. |
| 132 | // this is especially for not searching kubectl-create plugin |
| 133 | // when kubectl-create-foo plugin is not found. |
| 134 | break |
| 135 | } |
| 136 | |
| 137 | continue |
| 138 | } |
| 139 | |
| 140 | foundBinaryPath = path |
| 141 | break |
| 142 | } |
| 143 | |
| 144 | if len(foundBinaryPath) == 0 { |
| 145 | return nil |
| 146 | } |
| 147 | |
| 148 | // invoke cmd binary relaying the current environment and args given |
| 149 | if err := pluginHandler.Execute(foundBinaryPath, cmdArgs[len(remainingArgs):], os.Environ()); err != nil { |
| 150 | return err |
| 151 | } |
| 152 | |
| 153 | return nil |
| 154 | } |
| 155 | |
| 156 | // IsSubcommandPluginAllowed returns the given command is allowed |
| 157 | // to use plugin as subcommand if the subcommand does not exist as builtin. |
no test coverage detected
searching dependent graphs…