Skip to content

Commit

Permalink
Update Get interface to GetSingle
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
dmcgowan committed Oct 25, 2023
1 parent cc7b82b commit 024f6f8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
23 changes: 18 additions & 5 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,25 @@ func (ps *Set) GetAll() []*Plugin {
return ps.ordered
}

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

// Plugins returns plugin set
Expand Down
2 changes: 2 additions & 0 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ var (
ErrPluginInitialized = errors.New("plugin: already initialized")
// ErrPluginNotFound is used when a plugin is looked up but not found
ErrPluginNotFound = errors.New("plugin: not found")
// ErrPluginMultipleInstances is used when a plugin is expected a single instance but has multiple
ErrPluginMultipleInstances = errors.New("plugin: multiple instances")

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

0 comments on commit 024f6f8

Please sign in to comment.