diff --git a/viper.go b/viper.go index f61f4ed75..2f7a84af7 100644 --- a/viper.go +++ b/viper.go @@ -1443,11 +1443,10 @@ func (v *Viper) writeConfig(filename string, force bool) error { jww.INFO.Println("Attempting to write configuration to file.") var configType string - ext := filepath.Ext(filename) - if ext != "" { - configType = ext[1:] - } else { + if v.configType != "" { configType = v.configType + } else { + configType = strings.TrimPrefix(filepath.Ext(filename), ".") } if configType == "" { return fmt.Errorf("config type could not be determined for %s", filename) diff --git a/viper_test.go b/viper_test.go index fe942de29..8fd402df7 100644 --- a/viper_test.go +++ b/viper_test.go @@ -1326,6 +1326,32 @@ var hclWriteExpected = []byte(`"foos" = { "type" = "donut"`) +var hclWriteExpectedFromJSONExample = []byte(`"batters" = { + "batter" = { + "type" = "Regular" + } + + "batter" = { + "type" = "Chocolate" + } + + "batter" = { + "type" = "Blueberry" + } + + "batter" = { + "type" = "Devil's Food" + } +} + +"id" = "0001" + +"name" = "Cake" + +"ppu" = 0.55 + +"type" = "donut"`) + var jsonWriteExpected = []byte(`{ "batters": { "batter": [ @@ -1349,6 +1375,31 @@ var jsonWriteExpected = []byte(`{ "type": "donut" }`) +var jsonWriteExpectedFromHclExample = []byte(`{ + "foos": [ + { + "foo": [ + { + "key": 1 + }, + { + "key": 2 + }, + { + "key": 3 + }, + { + "key": 4 + } + ] + } + ], + "id": "0001", + "name": "Cake", + "ppu": 0.55, + "type": "donut" +}`) + var propertiesWriteExpected = []byte(`p_id = 0001 p_type = donut p_name = Cake @@ -1372,6 +1423,26 @@ hobbies: name: steve `) +var jsonWriteExpectedFromYamlExample = []byte(`{ + "age": 35, + "beard": true, + "clothing": { + "jacket": "leather", + "pants": { + "size": "large" + }, + "trousers": "denim" + }, + "eyes": "brown", + "hacker": true, + "hobbies": [ + "skateboarding", + "snowboarding", + "go" + ], + "name": "steve" +}`) + func TestWriteConfig(t *testing.T) { fs := afero.NewMemMapFs() testCases := map[string]struct { @@ -1404,7 +1475,7 @@ func TestWriteConfig(t *testing.T) { outConfigType: "json", fileName: "c.hcl", input: hclExample, - expectedContent: hclWriteExpected, + expectedContent: jsonWriteExpectedFromHclExample, }, "json with file extension": { configName: "c", @@ -1428,7 +1499,7 @@ func TestWriteConfig(t *testing.T) { outConfigType: "hcl", fileName: "c.json", input: jsonExample, - expectedContent: jsonWriteExpected, + expectedContent: hclWriteExpectedFromJSONExample, }, "properties with file extension": { configName: "c", @@ -1468,7 +1539,7 @@ func TestWriteConfig(t *testing.T) { outConfigType: "json", fileName: "c.yaml", input: yamlExample, - expectedContent: yamlWriteExpected, + expectedContent: jsonWriteExpectedFromYamlExample, }, } for name, tc := range testCases {