Skip to content

Commit

Permalink
hclwrite: Add (*Attribute).SetName() method
Browse files Browse the repository at this point in the history
Reference: #340
Reference: #680

Similar to `(*hclwrite.Block).SetType()`, this new method enables in-place renaming of an attribute.
  • Loading branch information
bflad committed May 23, 2024
1 parent 212a40e commit f76498f
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
7 changes: 7 additions & 0 deletions hclwrite/ast_attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,10 @@ func (a *Attribute) init(name string, expr *Expression) {
func (a *Attribute) Expr() *Expression {
return a.expr.content.(*Expression)
}

// SetName updates the name of the attribute to a given name.
func (a *Attribute) SetName(name string) {
nameTok := newIdentToken(name)
nameObj := newIdentifier(nameTok)
a.name.ReplaceWith(nameObj)
}
78 changes: 78 additions & 0 deletions hclwrite/ast_attribute_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package hclwrite

import (
"fmt"
"reflect"
"testing"

"github.com/davecgh/go-spew/spew"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
)

func TestAttributeSetName(t *testing.T) {
t.Parallel()

tests := []struct {
src string
oldName string
newName string
want Tokens
}{
{
"old = 123",
"old",
"new",
Tokens{
{
Type: hclsyntax.TokenIdent,
Bytes: []byte(`new`),
SpacesBefore: 0,
},
{
Type: hclsyntax.TokenEqual,
Bytes: []byte{'='},
SpacesBefore: 1,
},
{
Type: hclsyntax.TokenNumberLit,
Bytes: []byte(`123`),
SpacesBefore: 1,
},
{
Type: hclsyntax.TokenEOF,
Bytes: []byte{},
SpacesBefore: 0,
},
},
},
}

for _, test := range tests {
test := test

t.Run(fmt.Sprintf("%s %s in %s", test.oldName, test.newName, test.src), func(t *testing.T) {
t.Parallel()

f, diags := ParseConfig([]byte(test.src), "", hcl.Pos{Line: 1, Column: 1})

if len(diags) != 0 {
for _, diag := range diags {
t.Logf("- %s", diag.Error())
}
t.Fatalf("unexpected diagnostics")
}

attr := f.Body().GetAttribute(test.oldName)
attr.SetName(test.newName)
got := f.BuildTokens(nil)
format(got)

if !reflect.DeepEqual(got, test.want) {
diff := cmp.Diff(test.want, got)
t.Errorf("wrong result\ngot: %s\nwant: %s\ndiff:\n%s", spew.Sdump(got), spew.Sdump(test.want), diff)
}
})
}
}

0 comments on commit f76498f

Please sign in to comment.