command/format: Render empty JSON object as {}

This commit is contained in:
Radek Simko 2019-01-14 15:29:36 +00:00
parent 0dd2d56f18
commit 09d19ca9d9
No known key found for this signature in database
GPG Key ID: 1F1C84FE689A88D7
2 changed files with 38 additions and 8 deletions

View File

@ -438,11 +438,15 @@ func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, in
jv, err := ctyjson.Unmarshal(src, ty)
if err == nil {
p.buf.WriteString("jsonencode(")
p.buf.WriteByte('\n')
p.buf.WriteString(strings.Repeat(" ", indent+4))
p.writeValue(jv, action, indent+4)
p.buf.WriteByte('\n')
p.buf.WriteString(strings.Repeat(" ", indent))
if jv.LengthInt() == 0 {
p.writeValue(jv, action, 0)
} else {
p.buf.WriteByte('\n')
p.buf.WriteString(strings.Repeat(" ", indent+4))
p.writeValue(jv, action, indent+4)
p.buf.WriteByte('\n')
p.buf.WriteString(strings.Repeat(" ", indent))
}
p.buf.WriteByte(')')
break // don't *also* do the normal behavior below
}
@ -505,7 +509,7 @@ func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, in
}
p.buf.WriteString("}")
case ty.IsObjectType():
p.buf.WriteString("{\n")
p.buf.WriteString("{")
atys := ty.AttributeTypes()
attrNames := make([]string, 0, len(atys))
@ -520,16 +524,20 @@ func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, in
for _, attrName := range attrNames {
val := val.GetAttr(attrName)
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent+2))
p.writeActionSymbol(action)
p.buf.WriteString(attrName)
p.buf.WriteString(strings.Repeat(" ", nameLen-len(attrName)))
p.buf.WriteString(" = ")
p.writeValue(val, action, indent+4)
p.buf.WriteString("\n")
}
p.buf.WriteString(strings.Repeat(" ", indent))
if len(attrNames) > 0 {
p.buf.WriteString("\n")
p.buf.WriteString(strings.Repeat(" ", indent))
}
p.buf.WriteString("}")
}
}

View File

@ -414,6 +414,28 @@ func TestResourceChange_JSON(t *testing.T) {
}
)
}
`,
},
"creation (empty)": {
Action: plans.Create,
Mode: addrs.ManagedResourceMode,
Before: cty.NullVal(cty.EmptyObject),
After: cty.ObjectVal(map[string]cty.Value{
"id": cty.UnknownVal(cty.String),
"json_field": cty.StringVal(`{}`),
}),
Schema: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"id": {Type: cty.String, Optional: true, Computed: true},
"json_field": {Type: cty.String, Optional: true},
},
},
RequiredReplace: cty.NewPathSet(),
ExpectedOutput: ` # test_instance.example will be created
+ resource "test_instance" "example" {
+ id = (known after apply)
+ json_field = jsonencode({})
}
`,
},
}