103 lines
2.5 KiB
Go
103 lines
2.5 KiB
Go
package pipeline
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
|
)
|
|
|
|
type MergerConstructor func() (contracts.Merger, error)
|
|
|
|
type MergerRegistry struct {
|
|
constructors map[string]MergerConstructor
|
|
specs map[string]ModuleSpec
|
|
}
|
|
|
|
func NewMergerRegistry() *MergerRegistry {
|
|
return &MergerRegistry{
|
|
constructors: make(map[string]MergerConstructor),
|
|
specs: make(map[string]ModuleSpec),
|
|
}
|
|
}
|
|
|
|
func (r *MergerRegistry) Register(key string, constructor MergerConstructor) error {
|
|
return r.RegisterWithSpec(defaultModuleSpec(key, StageMerge), constructor)
|
|
}
|
|
|
|
func (r *MergerRegistry) RegisterWithSpec(spec ModuleSpec, constructor MergerConstructor) error {
|
|
if r == nil {
|
|
return fmt.Errorf("merger registry must not be nil")
|
|
}
|
|
|
|
normalizedSpec := normalizeModuleSpec(spec)
|
|
if err := validateModuleSpec("merger", StageMerge, normalizedSpec); err != nil {
|
|
return err
|
|
}
|
|
if constructor == nil {
|
|
return fmt.Errorf("merger constructor for %q must not be nil", normalizedSpec.Key)
|
|
}
|
|
if _, ok := r.constructors[normalizedSpec.Key]; ok {
|
|
return fmt.Errorf("merger %q is already registered", normalizedSpec.Key)
|
|
}
|
|
|
|
if r.constructors == nil {
|
|
r.constructors = make(map[string]MergerConstructor)
|
|
}
|
|
if r.specs == nil {
|
|
r.specs = make(map[string]ModuleSpec)
|
|
}
|
|
r.constructors[normalizedSpec.Key] = constructor
|
|
r.specs[normalizedSpec.Key] = cloneModuleSpec(normalizedSpec)
|
|
return nil
|
|
}
|
|
|
|
func (r *MergerRegistry) Build(key string) (contracts.Merger, error) {
|
|
if r == nil {
|
|
return nil, fmt.Errorf("merger registry must not be nil")
|
|
}
|
|
|
|
normalizedKey := strings.TrimSpace(key)
|
|
if normalizedKey == "" {
|
|
return nil, fmt.Errorf("merger key must not be empty")
|
|
}
|
|
|
|
constructor, ok := r.constructors[normalizedKey]
|
|
if !ok {
|
|
return nil, fmt.Errorf("merger %q is not registered", normalizedKey)
|
|
}
|
|
|
|
merger, err := constructor()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("build merger %q: %w", normalizedKey, err)
|
|
}
|
|
if merger == nil {
|
|
return nil, fmt.Errorf("merger %q constructor returned nil", normalizedKey)
|
|
}
|
|
if merger.Key() != normalizedKey {
|
|
return nil, fmt.Errorf("merger %q returned key %q", normalizedKey, merger.Key())
|
|
}
|
|
|
|
return merger, nil
|
|
}
|
|
|
|
func (r *MergerRegistry) Spec(key string) (ModuleSpec, bool) {
|
|
if r == nil {
|
|
return ModuleSpec{}, false
|
|
}
|
|
|
|
spec, ok := r.specs[strings.TrimSpace(key)]
|
|
if !ok {
|
|
return ModuleSpec{}, false
|
|
}
|
|
return cloneModuleSpec(spec), true
|
|
}
|
|
|
|
func (r *MergerRegistry) RegisteredKeys() []string {
|
|
if r == nil {
|
|
return nil
|
|
}
|
|
|
|
return sortedRegistryKeys(r.constructors)
|
|
}
|