hclwrite: Support for creating new blocks and clearing bodies

This commit is contained in:
Martin Atkins 2018-11-04 01:13:13 +00:00
parent 361186aad0
commit 8cca983bca
3 changed files with 24 additions and 0 deletions

View File

@ -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) { func (b *Block) init(typeName string, labels []string) {
nameTok := newIdentToken(typeName) nameTok := newIdentToken(typeName)
nameObj := newIdentifier(nameTok) nameObj := newIdentifier(nameTok)

View File

@ -32,6 +32,11 @@ func (b *Body) appendItemNode(nn *node) *node {
return nn 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) { func (b *Body) AppendUnstructuredTokens(ts Tokens) {
b.inTree.children.Append(ts) 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") 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 // AppendNewBlock appends a new nested block to the end of the receiving body
// with the given type name and labels. // with the given type name and labels.
func (b *Body) AppendNewBlock(typeName string, labels []string) *Block { func (b *Body) AppendNewBlock(typeName string, labels []string) *Block {

View File

@ -104,6 +104,11 @@ func (ns *nodes) BuildTokens(to Tokens) Tokens {
return to return to
} }
func (ns *nodes) Clear() {
ns.first = nil
ns.last = nil
}
func (ns *nodes) Append(c nodeContent) *node { func (ns *nodes) Append(c nodeContent) *node {
n := &node{ n := &node{
content: c, content: c,