Skip to content

Commit 024f6f8

Browse files
committed
Update Get interface to GetSingle
Remove the `Get` which just returns the first instance while ignoring other instances. GetSingle will ensure that there is only a single instance of a plugin and allow dependencies to enforce it or have logic to select the right plugin. Signed-off-by: Derek McGowan <derek@mcg.dev>
1 parent cc7b82b commit 024f6f8

2 files changed

Lines changed: 20 additions & 5 deletions

File tree

context.go

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,12 +128,25 @@ func (ps *Set) GetAll() []*Plugin {
128128
return ps.ordered
129129
}
130130

131-
// Get returns the first plugin by its type
132-
func (i *InitContext) Get(t Type) (interface{}, error) {
133-
for _, v := range i.plugins.byTypeAndID[t] {
134-
return v.Instance()
131+
// GetSingle returns a plugin instance of the given type when only a single instance
132+
// of that type is expected. Throws an ErrPluginNotFound if no plugin is found and
133+
// ErrPluginMultipleInstances when multiple instances are found.
134+
// Since plugins are not ordered, if multiple instances is suported then
135+
// GetByType should be used. If only one is expected, then to switch plugins,
136+
// disable or remove the unused plugins of the same type.
137+
func (i *InitContext) GetSingle(t Type) (interface{}, error) {
138+
pt, ok := i.plugins.byTypeAndID[t]
139+
if !ok || len(pt) == 0 {
140+
return nil, fmt.Errorf("no plugins registered for %s: %w", t, ErrPluginNotFound)
141+
}
142+
if len(pt) > 1 {
143+
return nil, fmt.Errorf("multiple plugins registered for %s: %w", t, ErrPluginMultipleInstances)
135144
}
136-
return nil, fmt.Errorf("no plugins registered for %s: %w", t, ErrPluginNotFound)
145+
var p *Plugin
146+
for _, v := range pt {
147+
p = v
148+
}
149+
return p.Instance()
137150
}
138151

139152
// Plugins returns plugin set

plugin.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ var (
3737
ErrPluginInitialized = errors.New("plugin: already initialized")
3838
// ErrPluginNotFound is used when a plugin is looked up but not found
3939
ErrPluginNotFound = errors.New("plugin: not found")
40+
// ErrPluginMultipleInstances is used when a plugin is expected a single instance but has multiple
41+
ErrPluginMultipleInstances = errors.New("plugin: multiple instances")
4042

4143
// ErrInvalidRequires will be thrown if the requirements for a plugin are
4244
// defined in an invalid manner.

0 commit comments

Comments
 (0)