Skip to content

Commit

Permalink
schemahcl: children (context) can refuse inheritance (#2334)
Browse files Browse the repository at this point in the history
* schemahcl: children (context) can refuse inheritance

* schemahcl: added test for ScopeContextOverride
  • Loading branch information
giautm authored Dec 6, 2023
1 parent 87ead07 commit 12a7448
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
15 changes: 8 additions & 7 deletions schemahcl/schemahcl.go
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,14 @@ func (s *State) mayScopeContext(ctx *hcl.EvalContext, scope []string) *hcl.EvalC
Variables: make(map[string]cty.Value),
Functions: make(map[string]function.Function),
}
for p := ctx; p != nil; p = p.Parent() {
for k, v := range p.Variables {
if isRef(v) {
nctx.Variables[k] = v
}
}
}
// Override the parent context with the scoped variables and functions.
for n, v := range vars {
nctx.Variables[n] = v
}
Expand All @@ -492,13 +500,6 @@ func (s *State) mayScopeContext(ctx *hcl.EvalContext, scope []string) *hcl.EvalC
// A patch from the past. Should be moved
// to specific scopes in the future.
nctx.Functions["sql"] = rawExprFunc
for p := ctx; p != nil; p = p.Parent() {
for k, v := range p.Variables {
if isRef(v) {
nctx.Variables[k] = v
}
}
}
return nctx
}

Expand Down
36 changes: 36 additions & 0 deletions schemahcl/schemahcl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -949,3 +949,39 @@ foo "f1" {
},
}, &e)
}

func Test_ScopeContextOverride(t *testing.T) {
type (
Foo struct {
Name string `spec:",name"`
}
Bar struct {
Name string `spec:",name"`
Attr string `spec:"attr"`
Ref *Ref `spec:"ref"`
}
)
var (
doc struct {
Foo []*Foo `spec:"foo"`
Bar []*Bar `spec:"bar"`
}
b = []byte(`
foo "f1" {}
bar "b1" {
attr = foo
ref = foo.f1
}
`)
)
require.NoError(t, New(
WithScopedEnums("bar.attr", "foo"), // foo is a valid value for bar.attr.
).EvalBytes(b, &doc, nil))
require.Len(t, doc.Foo, 1)
require.Len(t, doc.Bar, 1)
require.Equal(t, &Bar{
Name: "b1",
Attr: "foo",
Ref: &Ref{V: "$foo.f1"},
}, doc.Bar[0])
}

0 comments on commit 12a7448

Please # to comment.