github.com/yandex/pandora@v0.5.32/core/plugin/plugin.go (about) 1 package plugin 2 3 import ( 4 "fmt" 5 "reflect" 6 ) 7 8 // DefaultRegistry returns default Registry used for package *Registry methods like functions. 9 func DefaultRegistry() *Registry { 10 return defaultRegistry 11 } 12 13 // SetDefaultRegistry sets default Registry used for package *Registry methods like functions. 14 func SetDefaultRegistry(registry *Registry) { 15 defaultRegistry = registry 16 } 17 18 // Register is DefaultRegistry().Register shortcut. 19 func Register( 20 pluginType reflect.Type, 21 name string, 22 newPluginImpl interface{}, 23 defaultConfigOptional ...interface{}, 24 ) { 25 DefaultRegistry().Register(pluginType, name, newPluginImpl, defaultConfigOptional...) 26 } 27 28 // Lookup is DefaultRegistry().Lookup shortcut. 29 func Lookup(pluginType reflect.Type) bool { 30 return DefaultRegistry().Lookup(pluginType) 31 } 32 33 // LookupFactory is DefaultRegistry().LookupFactory shortcut. 34 func LookupFactory(factoryType reflect.Type) bool { 35 return DefaultRegistry().LookupFactory(factoryType) 36 } 37 38 // New is DefaultRegistry().New shortcut. 39 func New(pluginType reflect.Type, name string, fillConfOptional ...func(conf interface{}) error) (plugin interface{}, err error) { 40 return defaultRegistry.New(pluginType, name, fillConfOptional...) 41 } 42 43 // NewFactory is DefaultRegistry().NewFactory shortcut. 44 func NewFactory(factoryType reflect.Type, name string, fillConfOptional ...func(conf interface{}) error) (factory interface{}, err error) { 45 return defaultRegistry.NewFactory(factoryType, name, fillConfOptional...) 46 } 47 48 // PtrType is helper to extract plugin types. 49 // Example: plugin.PtrType((*PluginInterface)(nil)) instead of 50 // reflect.TypeOf((*PluginInterface)(nil)).Elem() 51 func PtrType(ptr interface{}) reflect.Type { 52 t := reflect.TypeOf(ptr) 53 if t.Kind() != reflect.Ptr { 54 panic("passed value is not pointer") 55 } 56 return t.Elem() 57 } 58 59 // FactoryPluginType returns (SomeInterface, true) if factoryType looks like func() (SomeInterface[, error]) 60 // or (nil, false) otherwise. 61 func FactoryPluginType(factoryType reflect.Type) (plugin reflect.Type, ok bool) { 62 if isFactoryType(factoryType) { 63 return factoryType.Out(0), true 64 } 65 return 66 } 67 68 // isFactoryType returns true, if type looks like func() (SomeInterface[, error]) 69 func isFactoryType(t reflect.Type) bool { 70 hasProperParamsNum := t.Kind() == reflect.Func && 71 t.NumIn() == 0 && 72 (t.NumOut() == 1 || t.NumOut() == 2) 73 if !hasProperParamsNum { 74 return false 75 } 76 if t.Out(0).Kind() != reflect.Interface { 77 return false 78 } 79 if t.NumOut() == 1 { 80 return true 81 } 82 return t.Out(1) == errorType 83 } 84 85 var defaultRegistry = NewRegistry() 86 87 var errorType = reflect.TypeOf((*error)(nil)).Elem() 88 89 func expect(b bool, msg string, args ...interface{}) { 90 if !b { 91 panic(fmt.Sprintf("expectation failed: "+msg, args...)) 92 } 93 }