1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-09-09 19:32:24 +08:00

fix(config): avoid clobbering user-provided key value pairs

let me know if this looks off @whyrusleeping @jbenet
This commit is contained in:
Brian Tiger Chow
2015-01-12 18:31:42 -08:00
parent 196bc04541
commit e84fc5df22
2 changed files with 29 additions and 3 deletions

View File

@ -219,3 +219,15 @@ func FromMap(v map[string]interface{}) (*Config, error) {
}
return &conf, nil
}
func ToMap(conf *Config) (map[string]interface{}, error) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(conf); err != nil {
return nil, err
}
var m map[string]interface{}
if err := json.NewDecoder(&buf).Decode(&m); err != nil {
return nil, fmt.Errorf("Failure to decode config: %s", err)
}
return m, nil
}

View File

@ -99,7 +99,7 @@ func (r *FSRepo) Config() *config.Config {
}
// SetConfig updates the FSRepo's config.
func (r *FSRepo) SetConfig(conf *config.Config) error {
func (r *FSRepo) SetConfig(updated *config.Config) error {
if r.state != opened {
panic(fmt.Sprintln("repo is", r.state))
}
@ -107,10 +107,24 @@ func (r *FSRepo) SetConfig(conf *config.Config) error {
if err != nil {
return err
}
if err := writeConfigFile(configFilename, conf); err != nil {
// to avoid clobbering user-provided keys, must read the config from disk
// as a map, write the updated struct values to the map and write the map
// to disk.
var mapconf map[string]interface{}
if err := readConfigFile(configFilename, &mapconf); err != nil {
return err
}
*r.config = *conf // copy so caller cannot modify the private config
m, err := config.ToMap(updated)
if err != nil {
return err
}
for k, v := range m {
mapconf[k] = v
}
if err := writeConfigFile(configFilename, mapconf); err != nil {
return err
}
*r.config = *updated // copy so caller cannot modify this private config
return nil
}