From 70dad8451dfc7fdb66bf6c01367fbf781dc8fe1e Mon Sep 17 00:00:00 2001 From: CrazyMax <1951866+crazy-max@users.noreply.github.com> Date: Mon, 17 Jun 2024 10:38:33 +0200 Subject: [PATCH] bake: default variable to null if not defined Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com> --- bake/hcl_test.go | 38 +++++++++++++++++++++++++++++++++++++ bake/hclparser/hclparser.go | 7 ++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/bake/hcl_test.go b/bake/hcl_test.go index f33722c7..9343b44e 100644 --- a/bake/hcl_test.go +++ b/bake/hcl_test.go @@ -394,6 +394,44 @@ func TestHCLTypedVariables(t *testing.T) { require.Contains(t, err.Error(), "failed to parse IS_FOO as bool") } +func TestHCLNullVariableDefault(t *testing.T) { + dt := []byte(` + variable "FOO" {} + target "default" { + args = { + isNull = equal(FOO, null) + isEmptyString = equal(FOO, "") + } + }`) + + c, err := ParseFile(dt, "docker-bake.hcl") + require.NoError(t, err) + require.Len(t, c.Targets, 1) + require.Len(t, c.Targets[0].Args, 2) + require.Equal(t, "true", *c.Targets[0].Args["isNull"]) + require.Equal(t, "false", *c.Targets[0].Args["isEmptyString"]) +} + +func TestHCLEmptyVariable(t *testing.T) { + dt := []byte(` + variable "FOO" { + default = "" + } + target "default" { + args = { + isNull = equal(FOO, null) + isEmptyString = equal(FOO, "") + } + }`) + + c, err := ParseFile(dt, "docker-bake.hcl") + require.NoError(t, err) + require.Len(t, c.Targets, 1) + require.Len(t, c.Targets[0].Args, 2) + require.Equal(t, "false", *c.Targets[0].Args["isNull"]) + require.Equal(t, "true", *c.Targets[0].Args["isEmptyString"]) +} + func TestHCLNullVariables(t *testing.T) { dt := []byte(` variable "FOO" { diff --git a/bake/hclparser/hclparser.go b/bake/hclparser/hclparser.go index 7efdc9f6..bc5d32ff 100644 --- a/bake/hclparser/hclparser.go +++ b/bake/hclparser/hclparser.go @@ -266,7 +266,12 @@ func (p *parser) resolveValue(ectx *hcl.EvalContext, name string) (err error) { if def == nil { val, ok := p.opt.Vars[name] if !ok { - val, _ = p.opt.LookupVar(name) + val, ok = p.opt.LookupVar(name) + if !ok { + vv := cty.NullVal(cty.DynamicPseudoType) + v = &vv + return + } } vv := cty.StringVal(val) v = &vv