github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/config/provider.go (about)

     1  package config
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/kyma-incubator/compass/components/director/pkg/apperrors"
     8  
     9  	"github.com/ghodss/yaml"
    10  	"github.com/oliveagle/jsonpath"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  // NewProvider missing godoc
    15  func NewProvider(fileName string) *Provider {
    16  	return &Provider{
    17  		fileName: fileName,
    18  	}
    19  }
    20  
    21  // Provider missing godoc
    22  type Provider struct {
    23  	fileName     string
    24  	cachedConfig map[string]interface{}
    25  }
    26  
    27  // Load missing godoc
    28  func (p *Provider) Load() error {
    29  	b, err := os.ReadFile(p.fileName)
    30  	if err != nil {
    31  		return errors.Wrapf(err, "while reading file %s", p.fileName)
    32  	}
    33  	out := map[string]interface{}{}
    34  	if err := yaml.Unmarshal(b, &out); err != nil {
    35  		return errors.Wrap(err, "while unmarshalling YAML")
    36  	}
    37  	p.cachedConfig = out
    38  
    39  	return nil
    40  }
    41  
    42  func (p *Provider) getValueForJSONPath(path string) (interface{}, error) {
    43  	if p.cachedConfig == nil {
    44  		return nil, apperrors.NewInternalError("required configuration not loaded")
    45  	}
    46  	jPath := fmt.Sprintf("$.%s", path)
    47  	res, err := jsonpath.JsonPathLookup(p.cachedConfig, jPath)
    48  	if err != nil {
    49  		return nil, errors.Wrapf(err, "while searching configuration using path %s", jPath)
    50  	}
    51  
    52  	if res == nil {
    53  		return nil, apperrors.NewValueNotFoundInConfigurationError()
    54  	}
    55  
    56  	return res, nil
    57  }