WriteConfig expected file type based on contentType instead of file extension

This commit is contained in:
Greg Szabo 2020-07-05 00:53:00 -04:00
parent 13df721090
commit e0e708a4cd
No known key found for this signature in database
GPG key ID: BD8D70B62C9B581D
2 changed files with 77 additions and 7 deletions

View file

@ -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)

View file

@ -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 {