Skip to content

Commit

Permalink
Add Copy() to structures (#206)
Browse files Browse the repository at this point in the history
  • Loading branch information
wata727 authored Oct 15, 2022
1 parent 91ab697 commit 3a61636
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions hclext/structure.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,21 @@ func (b *BodyContent) IsEmpty() bool {
return len(b.Attributes) == 0 && len(b.Blocks) == 0
}

// Copy returns a new BodyContent based on the original.
func (b *BodyContent) Copy() *BodyContent {
out := &BodyContent{
Attributes: Attributes{},
Blocks: make(Blocks, len(b.Blocks)),
}

for k, v := range b.Attributes {
out.Attributes[k] = v.Copy()
}
copy(out.Blocks, b.Blocks)

return out
}

// AsNative returns self as hcl.Attributes
func (as Attributes) AsNative() hcl.Attributes {
ret := hcl.Attributes{}
Expand All @@ -204,6 +219,18 @@ func (a *Attribute) AsNative() *hcl.Attribute {
}
}

// Copy returns a new Attribute based on the original.
// Note that expr can be a shallow copy. So strictly speaking
// Copy is not a deep copy.
func (a *Attribute) Copy() *Attribute {
return &Attribute{
Name: a.Name,
Expr: a.Expr,
Range: a.Range,
NameRange: a.NameRange,
}
}

// OfType filters the receiving block sequence by block type name,
// returning a new block sequence including only the blocks of the
// requested type.
Expand All @@ -230,3 +257,20 @@ func (els Blocks) ByType() map[string]Blocks {
}
return ret
}

// Copy returns a new Block based on the original.
func (b *Block) Copy() *Block {
out := &Block{
Type: b.Type,
Labels: make([]string, len(b.Labels)),
Body: b.Body.Copy(),
DefRange: b.DefRange,
TypeRange: b.TypeRange,
LabelRanges: make([]hcl.Range, len(b.LabelRanges)),
}

copy(out.Labels, b.Labels)
copy(out.LabelRanges, b.LabelRanges)

return out
}

0 comments on commit 3a61636

Please sign in to comment.