|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package plugins |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | +) |
| 23 | + |
| 24 | +// Handle provides plugins a set of standard data and tools to work with |
| 25 | +type Handle interface { |
| 26 | + // Context returns a context the plugins can use, if they need one |
| 27 | + Context() context.Context |
| 28 | + |
| 29 | + HandlePlugins |
| 30 | +} |
| 31 | + |
| 32 | +// HandlePlugins defines a set of APIs to work with instantiated plugins |
| 33 | +type HandlePlugins interface { |
| 34 | + // Plugin returns the named plugin instance |
| 35 | + Plugin(name string) Plugin |
| 36 | + |
| 37 | + // AddPlugin adds a plugin to the set of known plugin instances |
| 38 | + AddPlugin(name string, plugin Plugin) |
| 39 | + |
| 40 | + // GetAllPlugins returns all of the known plugins |
| 41 | + GetAllPlugins() []Plugin |
| 42 | + |
| 43 | + // GetAllPluginsWithNames returns all of the known plugins with their names |
| 44 | + GetAllPluginsWithNames() map[string]Plugin |
| 45 | +} |
| 46 | + |
| 47 | +// PluginByType retrieves the specified plugin by name and verifies its type |
| 48 | +func PluginByType[P Plugin](handlePlugins HandlePlugins, name string) (P, error) { |
| 49 | + var zero P |
| 50 | + |
| 51 | + rawPlugin := handlePlugins.Plugin(name) |
| 52 | + if rawPlugin == nil { |
| 53 | + return zero, fmt.Errorf("there is no plugin with the name '%s' defined", name) |
| 54 | + } |
| 55 | + plugin, ok := rawPlugin.(P) |
| 56 | + if !ok { |
| 57 | + return zero, fmt.Errorf("the plugin with the name '%s' is not an instance of %T", name, zero) |
| 58 | + } |
| 59 | + return plugin, nil |
| 60 | +} |
0 commit comments