Skip to content
Snippets Groups Projects
Select Git revision
  • 385a2069fb716b77f0ddc9eff76329ce48861790
  • master default protected
2 results

plugin.go

Blame
  • plugin.go 1.63 KiB
    package partial
    
    import (
    	"errors"
    	"plugin"
    	"strings"
    )
    
    var (
    	ErrOpened       = errors.New("plugin already opened")
    	ErrIncompatible = errors.New("plugin incompatible")
    	ErrBadSetup     = errors.New("plugin has invalid setup")
    )
    
    var plugins map[string]*Plugin
    
    // NewPlugin returns pointer to a new Plugin.
    func NewPlugin(name string) *Plugin {
    	return &Plugin{Name: name}
    }
    
    // Plugins return a slice of registered plugin names.
    func Plugins() []string {
    	pls := make([]string, len(plugins))
    	var i int
    	for name := range plugins {
    		pls[i] = name
    		i++
    	}
    	return pls
    }
    
    // GetPlugin gets plugin with specific name.
    func GetPlugin(name string) *Plugin {
    	return plugins[name]
    }
    
    // Plugin holds information on a plugin.
    type Plugin struct {
    	Name    string   `json:"name"`
    	Valid   bool     `json:"valid"`
    	Partial *Partial `json:"-"`
    	plugin  *plugin.Plugin
    }
    
    // Register registers the plugin.
    func (p *Plugin) Register() bool {
    	if _, ok := plugins[p.Name]; !ok {
    		plugins[p.Name] = p
    		return true
    	} else {
    		return false
    	}
    }
    
    // Open opens the plugin.
    func (p *Plugin) Open() error {
    	if p.plugin == nil {
    		return ErrOpened
    	}
    
    	if pl, err := plugin.Open("plugins/" + p.Name); err != nil {
    		if strings.Contains(err.Error(), "plugin was built with a different version of package") {
    			return ErrIncompatible
    		} else {
    			return err
    		}
    	} else {
    		p.plugin = pl
    	}