github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/config/validator.go (about)

     1  package config
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  	"strings"
     7  
     8  	"gopkg.in/yaml.v2"
     9  )
    10  
    11  // comma separated list of required fields
    12  const requiredFields = "additional-components"
    13  
    14  type ConfigMapKeysValidator struct{}
    15  
    16  func NewConfigMapKeysValidator() *ConfigMapKeysValidator {
    17  	return &ConfigMapKeysValidator{}
    18  }
    19  
    20  func (v *ConfigMapKeysValidator) Validate(cfgString string) error {
    21  	reqs := strings.Split(requiredFields, ",")
    22  	keys, err := v.getKeysFromConfigString(cfgString)
    23  	if err != nil {
    24  		return err
    25  	}
    26  	sort.Strings(reqs)
    27  	sort.Strings(keys)
    28  
    29  	var missingConfigs []string
    30  	keysString := strings.Join(keys, ",")
    31  	for _, req := range reqs {
    32  		if !strings.Contains(keysString, req) {
    33  			missingConfigs = append(missingConfigs, req)
    34  		}
    35  	}
    36  
    37  	if len(missingConfigs) > 0 {
    38  		return fmt.Errorf("missing required configuration entires: %s", strings.Join(missingConfigs, ","))
    39  	}
    40  	return nil
    41  }
    42  
    43  func (v *ConfigMapKeysValidator) getKeysFromConfigString(cfgString string) ([]string, error) {
    44  	keysAndValues := make(map[string]interface{}, 0)
    45  	if err := yaml.Unmarshal([]byte(cfgString), keysAndValues); err != nil {
    46  		return nil, err
    47  	}
    48  
    49  	keys := make([]string, 0)
    50  	for k, _ := range keysAndValues {
    51  		keys = append(keys, k)
    52  	}
    53  
    54  	return keys, nil
    55  }