From fbaf4f88f7676a25603edf10f8b71447052eeaae Mon Sep 17 00:00:00 2001 From: CrazyMax Date: Tue, 24 Aug 2021 19:04:58 +0200 Subject: [PATCH] `platform` HCL func Signed-off-by: CrazyMax --- bake/hclparser/builtin.go | 21 +++++++++++++++++++++ bake/hclparser/builtin_test.go | 14 ++++++++++++++ bake/hclparser/hclparser.go | 7 ++++++- 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 bake/hclparser/builtin.go create mode 100644 bake/hclparser/builtin_test.go diff --git a/bake/hclparser/builtin.go b/bake/hclparser/builtin.go new file mode 100644 index 000000000000..052f1e842d72 --- /dev/null +++ b/bake/hclparser/builtin.go @@ -0,0 +1,21 @@ +package hclparser + +import ( + "github.com/containerd/containerd/platforms" + "github.com/zclconf/go-cty/cty" + "github.com/zclconf/go-cty/cty/function" +) + +var builtinFunctions = map[string]function.Function{ + "platform": platformFunc, +} + +// platformFunc returns the current platform's default +// platform specification (e.g. linux/amd64). +var platformFunc = function.New(&function.Spec{ + Params: []function.Parameter{}, + Type: function.StaticReturnType(cty.String), + Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { + return cty.StringVal(platforms.DefaultString()), nil + }, +}) diff --git a/bake/hclparser/builtin_test.go b/bake/hclparser/builtin_test.go new file mode 100644 index 000000000000..4c1da0f7929c --- /dev/null +++ b/bake/hclparser/builtin_test.go @@ -0,0 +1,14 @@ +package hclparser + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPlatform(t *testing.T) { + p, err := platformFunc.Call(nil) + require.NoError(t, err) + assert.NotEmpty(t, p) +} diff --git a/bake/hclparser/hclparser.go b/bake/hclparser/hclparser.go index 6438c7eb573c..fcb88d156521 100644 --- a/bake/hclparser/hclparser.go +++ b/bake/hclparser/hclparser.go @@ -262,6 +262,11 @@ func Parse(b hcl.Body, opt Opt, val interface{}) hcl.Diagnostics { } } + funcs := stdlibFunctions + for k, f := range builtinFunctions { + funcs[k] = f + } + p := &parser{ opt: opt, @@ -274,7 +279,7 @@ func Parse(b hcl.Body, opt Opt, val interface{}) hcl.Diagnostics { doneF: map[string]struct{}{}, ectx: &hcl.EvalContext{ Variables: map[string]cty.Value{}, - Functions: stdlibFunctions, + Functions: funcs, }, }