History

feat(config): Gracefully handle empty or invalid optional config

hkfires committed 1 year ago

Commit fc6aa8e1 parent c3f88121 file · +10 −0Browse files

Unified · Split

internal/config/config.go+10−0
@@ -158,6 +158,7 @@ func LoadConfig(configFile string) (*Config, error) { · 157 unmodified lines
158 158
159// LoadConfigOptional reads YAML from configFile.159// LoadConfigOptional reads YAML from configFile.
160// If optional is true and the file is missing, it returns an empty Config.160// If optional is true and the file is missing, it returns an empty Config.
161// If optional is true and the file is empty or invalid, it returns an empty Config.
161func LoadConfigOptional(configFile string, optional bool) (*Config, error) {162func LoadConfigOptional(configFile string, optional bool) (*Config, error) {
162 // Read the entire configuration file into memory.163 // Read the entire configuration file into memory.
163 data, err := os.ReadFile(configFile)164 data, err := os.ReadFile(configFile)
@@ -171,12 +172,21 @@ func LoadConfigOptional(configFile string, optional bool) (*Config, error) { · 7 unmodified lines
171 return nil, fmt.Errorf("failed to read config file: %w", err)172 return nil, fmt.Errorf("failed to read config file: %w", err)
172 }173 }
173 174
175 // In cloud deploy mode (optional=true), if file is empty or contains only whitespace, return empty config.
176 if optional && len(data) == 0 {
177 return &Config{}, nil
178 }
179
174 // Unmarshal the YAML data into the Config struct.180 // Unmarshal the YAML data into the Config struct.
175 var cfg Config181 var cfg Config
176 // Set defaults before unmarshal so that absent keys keep defaults.182 // Set defaults before unmarshal so that absent keys keep defaults.
177 cfg.LoggingToFile = true183 cfg.LoggingToFile = true
178 cfg.UsageStatisticsEnabled = true184 cfg.UsageStatisticsEnabled = true
179 if err = yaml.Unmarshal(data, &cfg); err != nil {185 if err = yaml.Unmarshal(data, &cfg); err != nil {
186 if optional {
187 // In cloud deploy mode, if YAML parsing fails, return empty config instead of error.
188 return &Config{}, nil
189 }
180 return nil, fmt.Errorf("failed to parse config file: %w", err)190 return nil, fmt.Errorf("failed to parse config file: %w", err)
181 }191 }
182 192