From 8cca983bcabc5aa851b60c6dd812179683b4c153 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Sun, 4 Nov 2018 01:13:13 +0000 Subject: [PATCH] hclwrite: Support for creating new blocks and clearing bodies --- hclwrite/ast_block.go | 7 +++++++ hclwrite/ast_body.go | 12 ++++++++++++ hclwrite/node.go | 5 +++++ 3 files changed, 24 insertions(+) diff --git a/hclwrite/ast_block.go b/hclwrite/ast_block.go index e12d20b..d5fd32b 100644 --- a/hclwrite/ast_block.go +++ b/hclwrite/ast_block.go @@ -23,6 +23,13 @@ func newBlock() *Block { } } +// NewBlock constructs a new, empty block with the given type name and labels. +func NewBlock(typeName string, labels []string) *Block { + block := newBlock() + block.init(typeName, labels) + return block +} + func (b *Block) init(typeName string, labels []string) { nameTok := newIdentToken(typeName) nameObj := newIdentifier(nameTok) diff --git a/hclwrite/ast_body.go b/hclwrite/ast_body.go index 3eda787..e98e133 100644 --- a/hclwrite/ast_body.go +++ b/hclwrite/ast_body.go @@ -32,6 +32,11 @@ func (b *Body) appendItemNode(nn *node) *node { return nn } +// Clear removes all of the items from the body, making it empty. +func (b *Body) Clear() { + b.children.Clear() +} + func (b *Body) AppendUnstructuredTokens(ts Tokens) { b.inTree.children.Append(ts) } @@ -85,6 +90,13 @@ func (b *Body) SetAttributeTraversal(name string, traversal hcl.Traversal) *Attr panic("Body.SetAttributeTraversal not yet implemented") } +// AppendBlock appends an existing block (which must not be already attached +// to a body) to the end of the receiving body. +func (b *Body) AppendBlock(block *Block) *Block { + b.appendItem(block) + return block +} + // AppendNewBlock appends a new nested block to the end of the receiving body // with the given type name and labels. func (b *Body) AppendNewBlock(typeName string, labels []string) *Block { diff --git a/hclwrite/node.go b/hclwrite/node.go index 674b830..71fd00f 100644 --- a/hclwrite/node.go +++ b/hclwrite/node.go @@ -104,6 +104,11 @@ func (ns *nodes) BuildTokens(to Tokens) Tokens { return to } +func (ns *nodes) Clear() { + ns.first = nil + ns.last = nil +} + func (ns *nodes) Append(c nodeContent) *node { n := &node{ content: c,