package extractorregistry import ( "fmt" "sort" "strings" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" ) type Constructor func() (contracts.Extractor, error) type Registry struct { constructors map[string]Constructor } func New() *Registry { return &Registry{ constructors: make(map[string]Constructor), } } func (r *Registry) Register(key string, constructor Constructor) error { if r == nil { return fmt.Errorf("extractor registry must not be nil") } normalizedKey := strings.TrimSpace(key) if normalizedKey == "" { return fmt.Errorf("extractor key must not be empty") } if constructor == nil { return fmt.Errorf("extractor constructor for %q must not be nil", normalizedKey) } if _, ok := r.constructors[normalizedKey]; ok { return fmt.Errorf("extractor %q is already registered", normalizedKey) } r.constructors[normalizedKey] = constructor return nil } func (r *Registry) Build(key string) (contracts.Extractor, error) { if r == nil { return nil, fmt.Errorf("extractor registry must not be nil") } normalizedKey := strings.TrimSpace(key) if normalizedKey == "" { return nil, fmt.Errorf("extractor key must not be empty") } constructor, ok := r.constructors[normalizedKey] if !ok { return nil, fmt.Errorf("extractor %q is not registered", normalizedKey) } extractor, err := constructor() if err != nil { return nil, fmt.Errorf("build extractor %q: %w", normalizedKey, err) } if extractor == nil { return nil, fmt.Errorf("extractor %q constructor returned nil", normalizedKey) } if extractor.Key() != normalizedKey { return nil, fmt.Errorf("extractor %q returned key %q", normalizedKey, extractor.Key()) } return extractor, nil } func (r *Registry) RegisteredKeys() []string { if r == nil { return nil } keys := make([]string, 0, len(r.constructors)) for key := range r.constructors { keys = append(keys, key) } sort.Strings(keys) return keys }