diff --git a/cmd/profile.go b/cmd/profile.go index 465549e..a46e8b4 100644 --- a/cmd/profile.go +++ b/cmd/profile.go @@ -138,7 +138,13 @@ var AddProfileCmd = &cobra.Command{ if fileConfig.DefaultProfile == "" { fileConfig.DefaultProfile = name } - config.WriteConfigToFile(fileConfig) + + err = config.WriteConfigToFile(fileConfig) + if err != nil { + fmt.Printf("add profile %s failed\n, err: %v\n", StyleBold.Render(name), err) + return err + } + fmt.Printf("Added profile %s\n", StyleBold.Render(name)) if outputFormat == "json" { return outputResult(profile) @@ -168,6 +174,7 @@ var RemoveProfileCmd = &cobra.Command{ if len(fileConfig.Profiles) == 0 { fileConfig.DefaultProfile = "" } + config.WriteConfigToFile(fileConfig) if outputFormat == "json" { return outputResult(fmt.Sprintf("Deleted profile %s", name)) diff --git a/main.go b/main.go index 9430448..c7b9e49 100644 --- a/main.go +++ b/main.go @@ -18,6 +18,7 @@ package main import ( "errors" + "fmt" "os" "pb/cmd" "pb/pkg/config" @@ -140,18 +141,31 @@ func main() { Profiles: map[string]config.Profile{"demo": defaultInitialProfile()}, DefaultProfile: "demo", } - config.WriteConfigToFile(&conf) + err = config.WriteConfigToFile(&conf) + if err != nil { + fmt.Printf("failed to write to file %v\n", err) + os.Exit(1) + } } else { - // updates the demo profile for existing users - _, exists := previousConfig.Profiles["demo"] + // Only update the "demo" profile without overwriting other profiles + demoProfile, exists := previousConfig.Profiles["demo"] if exists { - conf := config.Profile{ - URL: "http://demo.parseable.com", - Username: "admin", - Password: "admin", - } - previousConfig.Profiles["demo"] = conf - config.WriteConfigToFile(previousConfig) + // Update fields in the demo profile only + demoProfile.URL = "http://demo.parseable.com" + demoProfile.Username = "admin" + demoProfile.Password = "admin" + previousConfig.Profiles["demo"] = demoProfile + } else { + // Add the "demo" profile if it doesn't exist + previousConfig.Profiles["demo"] = defaultInitialProfile() + previousConfig.DefaultProfile = "demo" // Optional: set as default if needed + } + + // Write the updated configuration back to file + err = config.WriteConfigToFile(previousConfig) + if err != nil { + fmt.Printf("failed to write to existing file %v\n", err) + os.Exit(1) } } diff --git a/pkg/config/config.go b/pkg/config/config.go index c867124..434113d 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -90,12 +90,18 @@ func WriteConfigToFile(config *Config) error { func ReadConfigFromFile() (config *Config, err error) { filePath, err := Path() if err != nil { - return + return &Config{}, err } + data, err := os.ReadFile(filePath) if err != nil { - return + return &Config{}, err } - toml.Unmarshal(data, &config) - return + + err = toml.Unmarshal(data, &config) + if err != nil { + return &Config{}, err + } + + return config, nil }