Skip to content

Commit fd05140

Browse files
GuillaumeBAECHLERsagikazarmark
authored andcommitted
fix(config): get config type from v.configType or config file ext
1 parent c038295 commit fd05140

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

viper.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1535,8 +1535,8 @@ func (v *Viper) MergeInConfig() error {
15351535
func ReadConfig(in io.Reader) error { return v.ReadConfig(in) }
15361536

15371537
func (v *Viper) ReadConfig(in io.Reader) error {
1538-
if v.configType == "" {
1539-
return errors.New("cannot decode configuration: config type is not set")
1538+
if v.getConfigType() == "" {
1539+
return errors.New("cannot decode configuration: unable to get config type from configType or file extension")
15401540
}
15411541

15421542
v.config = make(map[string]any)
@@ -1547,8 +1547,8 @@ func (v *Viper) ReadConfig(in io.Reader) error {
15471547
func MergeConfig(in io.Reader) error { return v.MergeConfig(in) }
15481548

15491549
func (v *Viper) MergeConfig(in io.Reader) error {
1550-
if v.configType == "" {
1551-
return errors.New("cannot decode configuration: config type is not set")
1550+
if v.getConfigType() == "" {
1551+
return errors.New("cannot decode configuration: unable to get config type from configType or file extension")
15521552
}
15531553

15541554
cfg := make(map[string]any)

viper_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,6 +1542,14 @@ func TestReadConfig(t *testing.T) {
15421542
})
15431543
}
15441544

1545+
func TestReadConfigWithSetConfigFile(t *testing.T) {
1546+
v := New()
1547+
v.SetConfigFile("config.yaml") // Dummy value to infer config type from file extension
1548+
err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleSrc))
1549+
require.NoError(t, err)
1550+
assert.Equal(t, 45000, v.GetInt("hello.pop"))
1551+
}
1552+
15451553
func TestIsSet(t *testing.T) {
15461554
v := New()
15471555
v.SetConfigType("yaml")
@@ -2059,6 +2067,14 @@ func TestMergeConfig(t *testing.T) {
20592067
assert.Equal(t, "bar", v.GetString("fu"))
20602068
}
20612069

2070+
func TestMergeConfigWithSetConfigFile(t *testing.T) {
2071+
v := New()
2072+
v.SetConfigFile("config.yaml") // Dummy value to infer config type from file extension
2073+
err := v.MergeConfig(bytes.NewBuffer(yamlMergeExampleSrc))
2074+
require.NoError(t, err)
2075+
assert.Equal(t, 45000, v.GetInt("hello.pop"))
2076+
}
2077+
20622078
func TestMergeConfigOverrideType(t *testing.T) {
20632079
v := New()
20642080
v.SetConfigType("json")

0 commit comments

Comments
 (0)