From fb2bc46cdbe36e247dac0c7dc185b34eaeb54c21 Mon Sep 17 00:00:00 2001 From: Danielle Tomlinson Date: Thu, 14 Feb 2019 12:58:25 +0100 Subject: [PATCH] json: Allow null values for block attributes (#87) * json: Handle Null block atttributes * json: Ignore null values when collecting deep attributes --- hcl/json/structure.go | 5 +++++ hcl/json/structure_test.go | 42 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/hcl/json/structure.go b/hcl/json/structure.go index 9312293..73693ee 100644 --- a/hcl/json/structure.go +++ b/hcl/json/structure.go @@ -266,6 +266,9 @@ func (b *body) unpackBlock(v node, typeName string, typeRange *hcl.Range, labels copy(labelR, labelRanges) switch tv := v.(type) { + case *nullVal: + // There is no block content, e.g the value is null. + return case *objectVal: // Single instance of the block *blocks = append(*blocks, &hcl.Block{ @@ -324,6 +327,8 @@ func (b *body) collectDeepAttrs(v node, labelName *string) ([]*objectAttr, hcl.D var attrs []*objectAttr switch tv := v.(type) { + case *nullVal: + // If a value is null, then we don't return any attributes or return an error. case *objectVal: attrs = append(attrs, tv.Attrs...) diff --git a/hcl/json/structure_test.go b/hcl/json/structure_test.go index 4a64a4a..4fe0554 100644 --- a/hcl/json/structure_test.go +++ b/hcl/json/structure_test.go @@ -301,6 +301,48 @@ func TestBodyPartialContent(t *testing.T) { }, 1, }, + { + `{"resource": null}`, + &hcl.BodySchema{ + Blocks: []hcl.BlockHeaderSchema{ + { + Type: "resource", + }, + }, + }, + &hcl.BodyContent{ + Attributes: map[string]*hcl.Attribute{}, + // We don't find any blocks if the value is json null. + Blocks: nil, + MissingItemRange: hcl.Range{ + Filename: "test.json", + Start: hcl.Pos{Line: 1, Column: 18, Byte: 17}, + End: hcl.Pos{Line: 1, Column: 19, Byte: 18}, + }, + }, + 0, + }, + { + `{"resource": { "nested": null }}`, + &hcl.BodySchema{ + Blocks: []hcl.BlockHeaderSchema{ + { + Type: "resource", + LabelNames: []string{"name"}, + }, + }, + }, + &hcl.BodyContent{ + Attributes: map[string]*hcl.Attribute{}, + Blocks: nil, + MissingItemRange: hcl.Range{ + Filename: "test.json", + Start: hcl.Pos{Line: 1, Column: 32, Byte: 31}, + End: hcl.Pos{Line: 1, Column: 33, Byte: 32}, + }, + }, + 0, + }, { `{"resource":{}}`, &hcl.BodySchema{