config.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package config
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log/slog"
  6. "os"
  7. "github.com/BurntSushi/toml"
  8. )
  9. type Config struct {
  10. Theme string `toml:"Theme"`
  11. Provider string `toml:"Provider"`
  12. Model string `toml:"Model"`
  13. }
  14. // NewConfig creates a new Config instance with default values.
  15. // This can be useful for initializing a new configuration file.
  16. func NewConfig(theme, provider, model string) *Config {
  17. return &Config{
  18. Theme: theme,
  19. Provider: provider,
  20. Model: model,
  21. }
  22. }
  23. // SaveConfig writes the provided Config struct to the specified TOML file.
  24. // It will create the file if it doesn't exist, or overwrite it if it does.
  25. func SaveConfig(filePath string, config *Config) error {
  26. file, err := os.Create(filePath)
  27. if err != nil {
  28. return fmt.Errorf("failed to create/open config file %s: %w", filePath, err)
  29. }
  30. defer file.Close()
  31. writer := bufio.NewWriter(file)
  32. encoder := toml.NewEncoder(writer)
  33. if err := encoder.Encode(config); err != nil {
  34. return fmt.Errorf("failed to encode config to TOML file %s: %w", filePath, err)
  35. }
  36. if err := writer.Flush(); err != nil {
  37. return fmt.Errorf("failed to flush writer for config file %s: %w", filePath, err)
  38. }
  39. slog.Debug("Configuration saved to file", "file", filePath)
  40. return nil
  41. }
  42. // LoadConfig reads a Config struct from the specified TOML file.
  43. // It returns a pointer to the Config struct and an error if any issues occur.
  44. func LoadConfig(filePath string) (*Config, error) {
  45. var config Config
  46. if _, err := toml.DecodeFile(filePath, &config); err != nil {
  47. if _, statErr := os.Stat(filePath); os.IsNotExist(statErr) {
  48. return nil, fmt.Errorf("config file not found at %s: %w", filePath, statErr)
  49. }
  50. return nil, fmt.Errorf("failed to decode TOML from file %s: %w", filePath, err)
  51. }
  52. return &config, nil
  53. }