Skip to content

Commit

Permalink
feat: simplify lazy bindings (#489)
Browse files Browse the repository at this point in the history
Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
  • Loading branch information
eddycharly authored Sep 19, 2024
1 parent 7cf1250 commit 42154f1
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 29 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
33 changes: 5 additions & 28 deletions pkg/engine/template/binding.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 42154f1

Please sign in to comment.