Improve config handling

- Backup existing config if we're saving it to add configuration
  defaults
- Output messages when saving/backing up the configuration file
This commit is contained in:
Matt Low 2023-11-29 05:54:05 +00:00
parent c46500de4e
commit 5615051637

View File

@ -44,9 +44,10 @@ func NewConfig() (*Config, error) {
shouldWriteDefaults := false shouldWriteDefaults := false
c := &Config{} c := &Config{}
configExists := true
configBytes, err := os.ReadFile(configFile) configBytes, err := os.ReadFile(configFile)
if os.IsNotExist(err) { if os.IsNotExist(err) {
shouldWriteDefaults = true configExists = false
} else if err != nil { } else if err != nil {
return nil, fmt.Errorf("Could not read config file: %v", err) return nil, fmt.Errorf("Could not read config file: %v", err)
} else { } else {
@ -54,7 +55,12 @@ func NewConfig() (*Config, error) {
} }
shouldWriteDefaults = SetStructDefaults(c) shouldWriteDefaults = SetStructDefaults(c)
if shouldWriteDefaults { if !configExists || shouldWriteDefaults {
if configExists {
fmt.Printf("Saving new defaults to configuration, backing up existing configuration to %s\n", configFile + ".bak")
os.Rename(configFile, configFile + ".bak")
}
fmt.Printf("Writing configuration file to %s\n", configFile)
file, err := os.Create(configFile) file, err := os.Create(configFile)
if err != nil { if err != nil {
return nil, fmt.Errorf("Could not open config file for writing: %v", err) return nil, fmt.Errorf("Could not open config file for writing: %v", err)