diff --git a/fs/configmap.go b/fs/configmap.go index ae48189c3..f55186cc0 100644 --- a/fs/configmap.go +++ b/fs/configmap.go @@ -83,7 +83,15 @@ func (r *regInfoValues) Get(key string) (value string, ok bool) { type setConfigFile string // Set a config item into the config file +// +// The item is only saved if the remote is defined in the config file, +// so remotes defined on the fly or with environment variables aren't +// written to it. func (section setConfigFile) Set(key, value string) { + if !ConfigFileHasSection(string(section)) { + Debugf(nil, "Not saving config %q as section %q is not in the config file", key, section) + return + } Debugf(nil, "Saving config %q in section %q of the config file", key, section) err := ConfigFileSet(string(section), key, value) if err != nil { diff --git a/fs/configmap_test.go b/fs/configmap_test.go index 89b717e41..9f241b5a4 100644 --- a/fs/configmap_test.go +++ b/fs/configmap_test.go @@ -91,3 +91,22 @@ func TestOptionEnvVarsRedactsPassword(t *testing.T) { assert.Equal(t, "obscured_pass", value) assert.NotContains(t, buf.String(), "obscured_pass") } + +// TestSetConfigFileOnlyExistingSection checks that config is only +// saved to sections which exist in the config file. +func TestSetConfigFileOnlyExistingSection(t *testing.T) { + oldHasSection, oldSet := ConfigFileHasSection, ConfigFileSet + t.Cleanup(func() { ConfigFileHasSection, ConfigFileSet = oldHasSection, oldSet }) + ConfigFileHasSection = func(section string) bool { return section == "remote" } + saved := map[string]string{} + ConfigFileSet = func(section, key, value string) error { + saved[section+"."+key] = value + return nil + } + + setConfigFile("remote").Set("key", "value") + setConfigFile(":backend").Set("key", "value") + setConfigFile("envremote").Set("key", "value") + + assert.Equal(t, map[string]string{"remote.key": "value"}, saved) +}