Debian Codegraph @

pkg/generators/basic/basic.go

raw
1 // Package basic provides a basic generator implementation for creating service configurations.
2 package basic
3
4 import (
5 "bufio"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "reflect"
11 "strconv"
12 "strings"
13 "time"
14
15 "github.com/nicholas-fedor/shoutrrr/pkg/color"
16 "github.com/nicholas-fedor/shoutrrr/pkg/format"
17 "github.com/nicholas-fedor/shoutrrr/pkg/types"
18 )
19
20 // Generator is the Basic Generator implementation for creating service configurations.
21 type Generator struct {
22 // Input is the reader used for user input during configuration generation.
23 // If nil, os.Stdin is used by default.
24 Input io.Reader
25 }
26
27 // Errors defined as static variables for better error handling.
28 var (
29 ErrInvalidConfigType = errors.New("config does not implement types.ServiceConfig")
30 ErrInvalidConfigField = errors.New("config field is invalid or nil")
31 ErrRequiredFieldMissing = errors.New("field is required and has no default value")
32 )
33
34 // Generate creates a service configuration by prompting the user for field values or using provided properties.
35 func (g *Generator) Generate(
36 service types.Service,
37 props map[string]string,
38 _ []string,
39 ) (types.ServiceConfig, error) {
40 // Get the Config field from the service using reflection
41 configPtr := reflect.ValueOf(service).Elem().FieldByName("Config")
42 if !configPtr.IsValid() {
43 return nil, ErrInvalidConfigField
44 }
45
46 // If Config is nil, initialize it with a new Config instance, as services
47 // created via NewService() are not initialized and have their Config
48 // field set to nil
49 // Only check IsNil() if Config is a pointer to avoid panic on non-pointer kinds
50 if configPtr.Kind() == reflect.Pointer && configPtr.IsNil() {
51 // Get the type of the pointer (Config) and create a new instance
52 newConfig := reflect.New(configPtr.Type().Elem())
53 configPtr.Set(newConfig)
54 }
55
56 // Use injected Input if provided, otherwise fall back to os.Stdin
57 reader := g.Input
58 if reader == nil {
59 reader = os.Stdin
60 }
61
62 scanner := bufio.NewScanner(reader)
63 if err := g.promptUserForFields(configPtr, props, scanner); err != nil {
64 return nil, err
65 }
66
67 if config, ok := reflect.TypeAssert[types.ServiceConfig](configPtr); ok {
68 return config, nil
69 }
70
71 return nil, ErrInvalidConfigType
72 }
73
74 // formatPrompt creates a user prompt based on the field’s name and default value.
75 func (g *Generator) formatPrompt(field *format.FieldInfo) string {
76 if field.DefaultValue != "" {
77 return fmt.Sprintf("%s[%s]: ", color.HiWhiteString(field.Name), field.DefaultValue)
78 }
79
80 return color.HiWhiteString(field.Name) + ": "
81 }
82
83 // getInputValue retrieves the value for a field from props or user input.
84 func (g *Generator) getInputValue(
85 field *format.FieldInfo,
86 propKey string,
87 props map[string]string,
88 consumed map[string]struct{},
89 scanner *bufio.Scanner,
90 ) (string, error) {
91 cfg := color.DefaultConfig()
92
93 if propValue, ok := props[propKey]; ok && propValue != "" {
94 _, _ = fmt.Fprint(
95 cfg.Output,
96 "Using property ",
97 color.HiCyanString(propValue),
98 " for ",
99 color.HiMagentaString(field.Name),
100 " field\n",
101 )
102 // Mark this prop as consumed instead of mutating the original map
103 consumed[propKey] = struct{}{}
104
105 return propValue, nil
106 }
107
108 prompt := g.formatPrompt(field)
109 _, _ = fmt.Fprint(cfg.Output, prompt)
110
111 if scanner.Scan() {
112 input := scanner.Text()
113 if input == "" {
114 if field.DefaultValue != "" {
115 return field.DefaultValue, nil
116 }
117
118 if field.Required {
119 return "", fmt.Errorf("%s: %w", field.Name, ErrRequiredFieldMissing)
120 }
121
122 return "", nil
123 }
124
125 // More specific type validation
126 if field.Type != nil {
127 kind := field.Type.Kind()
128
129 switch {
130 case field.Type == reflect.TypeFor[time.Duration]():
131 if _, err := time.ParseDuration(input); err != nil {
132 return "", fmt.Errorf("invalid duration value for %s: %w", field.Name, err)
133 }
134 case kind == reflect.Int || kind == reflect.Int8 || kind == reflect.Int16 ||
135 kind == reflect.Int32 || kind == reflect.Int64:
136 if _, err := strconv.ParseInt(input, 10, field.Type.Bits()); err != nil {
137 return "", fmt.Errorf("invalid integer value for %s: %w", field.Name, err)
138 }
139 }
140 }
141
142 return input, nil
143 } else if scanErr := scanner.Err(); scanErr != nil {
144 return "", fmt.Errorf("scanner error: %w", scanErr)
145 }
146
147 return field.DefaultValue, nil
148 }
149
150 // printError displays an error message for an invalid field value.
151 func (g *Generator) printError(fieldName, errorMsg string) {
152 cfg := color.DefaultConfig()
153 _, _ = fmt.Fprint(
154 cfg.Output,
155 "Invalid format for field ",
156 color.HiCyanString(fieldName),
157 ": ",
158 errorMsg,
159 "\n\n",
160 )
161 }
162
163 // printInvalidType displays a type mismatch error for a field.
164 func (g *Generator) printInvalidType(fieldName, typeName string) {
165 cfg := color.DefaultConfig()
166 _, _ = fmt.Fprint(
167 cfg.Output,
168 "Invalid type ",
169 color.HiYellowString(typeName),
170 " for field ",
171 color.HiCyanString(fieldName),
172 "\n\n",
173 )
174 }
175
176 // promptUserForFields iterates over config fields, prompting the user or using props to set values.
177 func (g *Generator) promptUserForFields(
178 configPtr reflect.Value,
179 props map[string]string,
180 scanner *bufio.Scanner,
181 ) error {
182 serviceConfig, ok := reflect.TypeAssert[types.ServiceConfig](configPtr)
183 if !ok {
184 return ErrInvalidConfigType
185 }
186
187 configNode := format.GetConfigFormat(serviceConfig)
188 config := configPtr.Elem() // Dereference for setting fields
189
190 // Track which props have been consumed to avoid mutating the input map
191 consumed := make(map[string]struct{})
192
193 for _, item := range configNode.Items {
194 field := item.Field()
195 propKey := strings.ToLower(field.Name)
196
197 for {
198 inputValue, err := g.getInputValue(field, propKey, props, consumed, scanner)
199 if err != nil {
200 return err // Propagate the error immediately
201 }
202
203 if valid, err := g.setFieldValue(config, field, inputValue); valid {
204 break
205 } else if err != nil {
206 g.printError(field.Name, err.Error())
207 } else {
208 g.printInvalidType(field.Name, field.Type.Kind().String())
209 }
210 }
211 }
212
213 return nil
214 }
215
216 // setFieldValue attempts to set a field's value and handles required field validation.
217 func (g *Generator) setFieldValue(
218 config reflect.Value,
219 field *format.FieldInfo,
220 inputValue string,
221 ) (bool, error) {
222 cfg := color.DefaultConfig()
223
224 if inputValue == "" {
225 if field.Required {
226 _, _ = fmt.Fprint(
227 cfg.Output,
228 "Field ",
229 color.HiCyanString(field.Name),
230 " is required!\n\n",
231 )
232
233 return false, nil
234 }
235
236 if field.DefaultValue == "" {
237 return true, nil
238 }
239
240 inputValue = field.DefaultValue
241 }
242
243 valid, err := format.SetConfigField(config, field, inputValue)
244 if err != nil {
245 return false, fmt.Errorf("failed to set field %s: %w", field.Name, err)
246 }
247
248 return valid, nil
249 }