Debian Codegraph @

pkg/generators/router.go

raw
1 // Package generators provides a router for creating generator instances by identifier.
2 package generators
3
4 import (
5 "errors"
6 "fmt"
7 "io"
8 "strings"
9
10 "github.com/nicholas-fedor/shoutrrr/pkg/generators/basic"
11 "github.com/nicholas-fedor/shoutrrr/pkg/generators/xoauth2"
12 "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/telegram"
13 "github.com/nicholas-fedor/shoutrrr/pkg/types"
14 )
15
16 // generatorConfig holds configuration options for generator creation.
17 type generatorConfig struct {
18 input io.Reader
19 }
20
21 // GeneratorOption configures how a generator is created.
22 type GeneratorOption func(*generatorConfig)
23
24 // ErrUnknownGenerator is returned when an unknown generator identifier is provided.
25 var ErrUnknownGenerator = errors.New("unknown generator")
26
27 // generatorMap is a registry that maps generator type names to their
28 // factory functions. It is used by NewGenerator to create instances of
29 // specific generator implementations based on the requested type.
30 var generatorMap = map[string]func(config generatorConfig) types.Generator{
31 "basic": func(config generatorConfig) types.Generator {
32 return &basic.Generator{
33 Input: config.input,
34 }
35 },
36 "oauth2": func(config generatorConfig) types.Generator {
37 return &xoauth2.Generator{}
38 },
39 "telegram": func(config generatorConfig) types.Generator {
40 return &telegram.Generator{
41 Reader: config.input,
42 Writer: nil,
43 }
44 },
45 }
46
47 // ListGenerators lists all available generators.
48 func ListGenerators() []string {
49 generators := make([]string, len(generatorMap))
50
51 i := 0
52
53 for key := range generatorMap {
54 generators[i] = key
55 i++
56 }
57
58 return generators
59 }
60
61 // NewGenerator creates an instance of the generator that corresponds to the provided identifier.
62 // Optional GeneratorOption parameters can be used to configure the generator (e.g., WithInput).
63 func NewGenerator(identifier string, opts ...GeneratorOption) (types.Generator, error) {
64 config := generatorConfig{
65 input: nil,
66 }
67 for _, opt := range opts {
68 opt(&config)
69 }
70
71 generatorFactory, valid := generatorMap[strings.ToLower(identifier)]
72 if !valid {
73 return nil, fmt.Errorf("%w: %q", ErrUnknownGenerator, identifier)
74 }
75
76 return generatorFactory(config), nil
77 }
78
79 // WithInput sets the input reader for generators that support it.
80 // This is useful for dependency injection in tests or for providing
81 // input from sources other than os.Stdin.
82 func WithInput(reader io.Reader) GeneratorOption {
83 return func(c *generatorConfig) {
84 c.input = reader
85 }
86 }