Skip to content

Commit 3a61636

Browse files
authored
Add Copy() to structures (#206)
1 parent 91ab697 commit 3a61636

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

hclext/structure.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,21 @@ func (b *BodyContent) IsEmpty() bool {
185185
return len(b.Attributes) == 0 && len(b.Blocks) == 0
186186
}
187187

188+
// Copy returns a new BodyContent based on the original.
189+
func (b *BodyContent) Copy() *BodyContent {
190+
out := &BodyContent{
191+
Attributes: Attributes{},
192+
Blocks: make(Blocks, len(b.Blocks)),
193+
}
194+
195+
for k, v := range b.Attributes {
196+
out.Attributes[k] = v.Copy()
197+
}
198+
copy(out.Blocks, b.Blocks)
199+
200+
return out
201+
}
202+
188203
// AsNative returns self as hcl.Attributes
189204
func (as Attributes) AsNative() hcl.Attributes {
190205
ret := hcl.Attributes{}
@@ -204,6 +219,18 @@ func (a *Attribute) AsNative() *hcl.Attribute {
204219
}
205220
}
206221

222+
// Copy returns a new Attribute based on the original.
223+
// Note that expr can be a shallow copy. So strictly speaking
224+
// Copy is not a deep copy.
225+
func (a *Attribute) Copy() *Attribute {
226+
return &Attribute{
227+
Name: a.Name,
228+
Expr: a.Expr,
229+
Range: a.Range,
230+
NameRange: a.NameRange,
231+
}
232+
}
233+
207234
// OfType filters the receiving block sequence by block type name,
208235
// returning a new block sequence including only the blocks of the
209236
// requested type.
@@ -230,3 +257,20 @@ func (els Blocks) ByType() map[string]Blocks {
230257
}
231258
return ret
232259
}
260+
261+
// Copy returns a new Block based on the original.
262+
func (b *Block) Copy() *Block {
263+
out := &Block{
264+
Type: b.Type,
265+
Labels: make([]string, len(b.Labels)),
266+
Body: b.Body.Copy(),
267+
DefRange: b.DefRange,
268+
TypeRange: b.TypeRange,
269+
LabelRanges: make([]hcl.Range, len(b.LabelRanges)),
270+
}
271+
272+
copy(out.Labels, b.Labels)
273+
copy(out.LabelRanges, b.LabelRanges)
274+
275+
return out
276+
}

0 commit comments

Comments
 (0)