helperbot/cmd/helper_plugin.go

65 lines
1.3 KiB
Go

package main
import (
"fmt"
"io/ioutil"
"os"
"plugin"
"strings"
"git.bullercodeworks.com/brian/helperbot"
)
type HelperPlugin struct {
p *plugin.Plugin
State helperbot.PluginState
}
func (a *App) LoadPluginsFromDirectory(dir string) error {
fmt.Println("Loading Plugins (", dir, ")")
files, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Println("Error loading plugins")
fmt.Println(err.Error())
os.Exit(1)
}
for _, f := range files {
if !strings.HasSuffix(f.Name(), ".so") {
fmt.Printf("Skipping file (%s)\n", f.Name())
continue
}
p, err := plugin.Open(dir + f.Name())
if err != nil {
fmt.Println(fmt.Sprintf("Error loading plugin (%s)\n", f.Name()))
fmt.Println(err.Error())
os.Exit(1)
}
hp, err := NewHelperPlugin(p)
if err != nil {
fmt.Println(fmt.Sprintf("Error loading plugin (%s)\n", f.Name()))
fmt.Println(err.Error())
os.Exit(1)
}
hp.State.Initialize(a.m)
hp.State.Run()
fmt.Printf("Plugin Loaded (%s)\n", f.Name())
a.plugins = append(a.plugins, *hp)
}
return nil
}
func NewHelperPlugin(p *plugin.Plugin) (*HelperPlugin, error) {
h := &HelperPlugin{
p: p,
}
// Parse the plugin's state
pluginStateSymbol, err := p.Lookup("State")
if err != nil {
return nil, err
}
h.State = pluginStateSymbol.(helperbot.PluginState)
return h, nil
}