From 42154f10dbdcaabb5fee020f3ace4b642bb0cbc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Charles-Edouard=20Br=C3=A9t=C3=A9ch=C3=A9?= Date: Thu, 19 Sep 2024 10:23:55 +0200 Subject: [PATCH] feat: simplify lazy bindings (#489) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Charles-Edouard Brétéché --- go.mod | 2 +- pkg/engine/template/binding.go | 33 +++++---------------------------- 2 files changed, 6 insertions(+), 29 deletions(-) diff --git a/go.mod b/go.mod index 11fa8f10..2b5a774f 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/blang/semver/v4 v4.0.0 github.com/gin-contrib/cors v1.7.2 github.com/gin-gonic/gin v1.10.0 + github.com/google/go-cmp v0.6.0 github.com/jmespath-community/go-jmespath v1.1.2-0.20240117150817-e430401a2172 github.com/kyverno/pkg/ext v0.0.0-20240418121121-df8add26c55c github.com/loopfz/gadgeto v0.11.4 @@ -63,7 +64,6 @@ require ( github.com/google/btree v1.1.2 // indirect github.com/google/cel-go v0.17.8 // indirect github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49 // indirect - github.com/google/go-cmp v0.6.0 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/gxui v0.0.0-20151028112939-f85e0a97b3a4 // indirect github.com/google/uuid v1.6.0 // indirect diff --git a/pkg/engine/template/binding.go b/pkg/engine/template/binding.go index 51be6c32..9a6e4d38 100644 --- a/pkg/engine/template/binding.go +++ b/pkg/engine/template/binding.go @@ -2,37 +2,14 @@ package template import ( "sync" - - "github.com/jmespath-community/go-jmespath/pkg/binding" ) -type resolverFunc = func() (any, error) - -type lazyBinding struct { - resolver resolverFunc -} - -func (b *lazyBinding) Value() (any, error) { - return b.resolver() -} +type lazyBinding func() (any, error) -func NewLazyBinding(resolver resolverFunc) binding.Binding { - binding := &lazyBinding{} - lock := &sync.Mutex{} - binding.resolver = func() (any, error) { - lock.Lock() - defer lock.Unlock() - value, err := resolver() - binding.resolver = func() (any, error) { - return value, err - } - return binding.resolver() - } - return binding +func (b lazyBinding) Value() (any, error) { + return b() } -func NewLazyBindingWithValue(value any) binding.Binding { - return NewLazyBinding(func() (any, error) { - return value, nil - }) +func NewLazyBinding(resolver func() (any, error)) lazyBinding { + return sync.OnceValues(resolver) }