Skip to content

Commit

Permalink
Cleanup plugin interface
Browse files Browse the repository at this point in the history
Separate Get for set and init context, which are used differently.
Ensure init context always returns instances and does not return an
underlying map.

Signed-off-by: Derek McGowan <[email protected]>
  • Loading branch information
dmcgowan committed Oct 25, 2023
1 parent 832b974 commit 011f099
Showing 1 changed file with 29 additions and 20 deletions.
49 changes: 29 additions & 20 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,6 @@ func NewContext(ctx context.Context, plugins *Set, properties map[string]string)
}
}

// Get returns the first plugin by its type
func (i *InitContext) Get(t Type) (interface{}, error) {
return i.plugins.Get(t)
}

// Meta contains information gathered from the registration and initialization
// process.
type Meta struct {
Expand Down Expand Up @@ -119,19 +114,28 @@ func (ps *Set) Add(p *Plugin) error {
return nil
}

// Get returns the first plugin by its type
func (ps *Set) Get(t Type) (interface{}, error) {
for _, v := range ps.byTypeAndID[t] {
return v.Instance()
// Get returns the plugin with the given type and id
func (ps *Set) Get(t Type, id string) *Plugin {
p, ok := ps.byTypeAndID[t]
if !ok {
return nil
}
return nil, fmt.Errorf("no plugins registered for %s: %w", t, ErrPluginNotFound)
return p[id]
}

// GetAll returns all initialized plugins
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()
}
return nil, fmt.Errorf("no plugins registered for %s: %w", t, ErrPluginNotFound)
}

// Plugins returns plugin set
func (i *InitContext) Plugins() *Set {
return i.plugins
Expand All @@ -144,23 +148,28 @@ func (i *InitContext) GetAll() []*Plugin {

// GetByID returns the plugin of the given type and ID
func (i *InitContext) GetByID(t Type, id string) (interface{}, error) {
ps, err := i.GetByType(t)
if err != nil {
return nil, err
}
p, ok := ps[id]
if !ok {
return nil, fmt.Errorf("no %s plugins with id %s: %w", t, id, ErrPluginNotFound)
p := i.plugins.Get(t, id)
if p == nil {
return nil, fmt.Errorf("no plugins registered for %s: %w", t, ErrPluginNotFound)
}
return p.Instance()
}

// GetByType returns all plugins with the specific type.
func (i *InitContext) GetByType(t Type) (map[string]*Plugin, error) {
p, ok := i.plugins.byTypeAndID[t]
func (i *InitContext) GetByType(t Type) (map[string]interface{}, error) {
pt, ok := i.plugins.byTypeAndID[t]
if !ok {
return nil, fmt.Errorf("no plugins registered for %s: %w", t, ErrPluginNotFound)
}

return p, nil
pi := make(map[string]interface{}, len(pt))
for id, p := range pt {
i, err := p.Instance()
if err != nil {
return nil, err
}
pi[id] = i
}

return pi, nil
}

0 comments on commit 011f099

Please sign in to comment.