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