SaveConfigFile saves the config to a file with optional encryption (if not using SOPS). This is a lower-level function that can be used from packages that can't import UI components.
(cfg *Config, path string)
| 266 | // SaveConfigFile saves the config to a file with optional encryption (if not using SOPS). |
| 267 | // This is a lower-level function that can be used from packages that can't import UI components. |
| 268 | func SaveConfigFile(cfg *Config, path string) error { |
| 269 | // Check if SOPS is being used |
| 270 | data, err := os.ReadFile(path) |
| 271 | isSOPS := false |
| 272 | if err == nil { |
| 273 | isSOPS = IsSOPSEncrypted(path, data) |
| 274 | } |
| 275 | |
| 276 | // If not using SOPS, encrypt sensitive fields before saving |
| 277 | if !isSOPS { |
| 278 | if err := EncryptConfigSensitiveFields(cfg); err != nil { |
| 279 | // Log warning but continue - allow saving even if encryption fails |
| 280 | if DebugEnabled { |
| 281 | fmt.Printf("Warning: Failed to encrypt some fields: %v\n", err) |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | // Marshal to YAML |
| 287 | data, err = yaml.Marshal(cfg) |
| 288 | if err != nil { |
| 289 | return fmt.Errorf("marshal config to YAML: %w", err) |
| 290 | } |
| 291 | |
| 292 | // Ensure the target directory exists |
| 293 | dir := filepath.Dir(path) |
| 294 | if err := os.MkdirAll(dir, 0o750); err != nil { |
| 295 | return fmt.Errorf("create config directory: %w", err) |
| 296 | } |
| 297 | |
| 298 | // Write file |
| 299 | if err := os.WriteFile(path, data, 0o600); err != nil { |
| 300 | return fmt.Errorf("write config file: %w", err) |
| 301 | } |
| 302 | |
| 303 | if cfg != nil { |
| 304 | cfg.hasCleartextSensitive = false |
| 305 | } |
| 306 | |
| 307 | return nil |
| 308 | } |
no test coverage detected