github.com/yanndegat/hiera@v0.6.8/internal/datadigprovider.go (about)

     1  package internal
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/lyraproj/dgo/dgo"
     7  	"github.com/lyraproj/dgo/vf"
     8  	"github.com/lyraproj/hierasdk/hiera"
     9  	"github.com/yanndegat/hiera/api"
    10  )
    11  
    12  type dataDigProvider struct {
    13  	hierarchyEntry api.Entry
    14  	providerFunc   hiera.DataDig
    15  }
    16  
    17  func (dh *dataDigProvider) Hierarchy() api.Entry {
    18  	return dh.hierarchyEntry
    19  }
    20  
    21  func (dh *dataDigProvider) LookupKey(key api.Key, ic api.Invocation, location api.Location) dgo.Value {
    22  	opts := dh.hierarchyEntry.Options()
    23  	if location != nil {
    24  		opts = optionsWithLocation(opts, location.Resolved())
    25  	}
    26  	value := dh.providerFunction(ic)(ic.ServerContext(opts), vf.Values(key.Parts()...))
    27  	if value != nil {
    28  		ic.ReportFound(key.Source(), value)
    29  		value = ic.Interpolate(value, true)
    30  		value = key.Bury(value)
    31  	} else {
    32  		ic.ReportNotFound(key)
    33  	}
    34  	return value
    35  }
    36  
    37  func (dh *dataDigProvider) providerFunction(ic api.Invocation) (pf hiera.DataDig) {
    38  	if dh.providerFunc == nil {
    39  		dh.providerFunc = dh.loadFunction(ic)
    40  	}
    41  	return dh.providerFunc
    42  }
    43  
    44  func (dh *dataDigProvider) loadFunction(ic api.Invocation) (pf hiera.DataDig) {
    45  	he := dh.hierarchyEntry
    46  	if f, ok := ic.LoadFunction(he); ok {
    47  		return func(pc hiera.ProviderContext, key dgo.Array) dgo.Value {
    48  			return f.(dgo.Function).Call(vf.Values(ic, key))[0]
    49  		}
    50  	}
    51  	ic.ReportText(func() string { return fmt.Sprintf(`unresolved function '%s'`, he.Function().Name()) })
    52  	return func(hiera.ProviderContext, dgo.Array) dgo.Value { return nil }
    53  }
    54  
    55  func (dh *dataDigProvider) FullName() string {
    56  	return fmt.Sprintf(`data_dig function '%s'`, dh.hierarchyEntry.Function().Name())
    57  }
    58  
    59  // NewDataDigProvider creates a new provider with a data_dig function configured from the given entry
    60  func NewDataDigProvider(he api.Entry) api.DataProvider {
    61  	return &dataDigProvider{hierarchyEntry: he}
    62  }