birdbot/app/plugins.go

60 lines
1.3 KiB
Go
Raw Normal View History

2023-03-31 22:21:49 +02:00
package app
import (
"log"
"os"
"path/filepath"
2023-03-31 22:21:49 +02:00
"plugin"
"github.com/yeslayla/birdbot-common/common"
2023-03-31 22:21:49 +02:00
)
2023-03-31 22:49:50 +02:00
// LoadPlugin loads a plugin and returns its component if successful
func LoadPlugin(pluginPath string) common.Module {
2023-03-31 22:21:49 +02:00
plug, err := plugin.Open(pluginPath)
if err != nil {
log.Printf("Failed to load plugin '%s': %s", pluginPath, err)
return nil
}
2023-03-31 22:49:50 +02:00
// Lookup component symbol
2023-03-31 22:21:49 +02:00
sym, err := plug.Lookup("Component")
if err != nil {
log.Printf("Failed to load plugin '%s': failed to get Component: %s", pluginPath, err)
return nil
}
2023-03-31 22:49:50 +02:00
// Validate component type
var component common.Module
component, ok := sym.(common.Module)
2023-03-31 22:21:49 +02:00
if !ok {
log.Printf("Failed to load plugin '%s': Plugin component does not properly implement interface!", pluginPath)
}
return component
}
2023-03-31 22:49:50 +02:00
// LoadPlugins loads all plugins and componenets in a directory
func LoadPlugins(directory string) []common.Module {
2023-03-31 22:21:49 +02:00
paths, err := os.ReadDir(directory)
if err != nil {
log.Printf("Failed to load plugins: %s", err)
return []common.Module{}
2023-03-31 22:21:49 +02:00
}
var components []common.Module = make([]common.Module, 0)
2023-03-31 22:21:49 +02:00
for _, path := range paths {
if path.IsDir() {
continue
}
if comp := LoadPlugin(filepath.Join(directory, path.Name())); comp != nil {
2023-03-31 22:21:49 +02:00
components = append(components, comp)
}
}
return components
}