Skip to content

Commit

Permalink
feat(terraform): add a method to replace the value in the context (#1504
Browse files Browse the repository at this point in the history
)
  • Loading branch information
nikpivkin authored Dec 8, 2023
1 parent 455085f commit 318642a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/terraform/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ func (c *Context) Set(val cty.Value, parts ...string) {
c.ctx.Variables[parts[0]] = v
}

func (c *Context) Replace(val cty.Value, path string) {
parts := strings.Split(path, ".")
if len(parts) == 0 {
return
}

delete(c.ctx.Variables, parts[0])
c.Set(val, parts...)
}

func mergeVars(src cty.Value, parts []string, value cty.Value) cty.Value {

if len(parts) == 0 {
Expand Down
25 changes: 25 additions & 0 deletions pkg/terraform/context/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com/hashicorp/hcl/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/gocty"
)
Expand Down Expand Up @@ -211,3 +212,27 @@ func Test_IsNotEmptyObject(t *testing.T) {
})
}
}

func TestReplace(t *testing.T) {
t.Run("replacement of an existing value", func(t *testing.T) {
underlying := &hcl.EvalContext{}
ctx := NewContext(underlying, nil)
ctx.SetByDot(cty.StringVal("some-value"), "my.value")
require.NotEqual(t, cty.NilVal, ctx.GetByDot("my.value"))
ctx.Replace(cty.NumberIntVal(-1), "my.value")
assert.Equal(t, cty.NumberIntVal(-1), ctx.GetByDot("my.value"))
})

t.Run("replacement of a non-existing value", func(t *testing.T) {
underlying := &hcl.EvalContext{}
ctx := NewContext(underlying, nil)
ctx.Replace(cty.NumberIntVal(-1), "my.value")
assert.Equal(t, cty.NumberIntVal(-1), ctx.GetByDot("my.value"))
})

t.Run("empty path", func(t *testing.T) {
underlying := &hcl.EvalContext{}
ctx := NewContext(underlying, nil)
ctx.Replace(cty.NumberIntVal(-1), "")
})
}

0 comments on commit 318642a

Please sign in to comment.