Skip to content

Commit

Permalink
document jsonToConfigContext
Browse files Browse the repository at this point in the history
  • Loading branch information
dwelch-spike committed Mar 27, 2024
1 parent 0c4db9e commit 126bd71
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions conf/config_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,50 +135,80 @@ func (o ValidationErrors) Error() string {
return errString
}

// jsonToConfigContext takes a json config and a context string and returns a copy
// of the context string with the field names instead of list indexes.
// For example, if the context is "namespaces.0", and the json config is:
//
// {
// "namespaces": [
// {
// "name": "test"
// }
// ]
// }
//
// The function will return "namespaces.test"
// An error is returned if the json or context are not in the expected management lib format.
func jsonToConfigContext(jsonConfig any, context string) (string, error) {
split := strings.SplitN(context, ".", 2)
key := split[0]

var res string

// check if key is an index
if index, err := strconv.Atoi(key); err == nil {
// if key is an index, then context should be a slice
jsonSlice, ok := jsonConfig.([]any)
if !ok {
return "", fmt.Errorf("context is not a slice in json config at: %s", context)
}

// check if index is out of bounds
if len(jsonSlice) <= index {
return "", fmt.Errorf("index out of bounds json config at: %s", context)
}

// the indexed object should be a map
indexedMap, ok := jsonSlice[index].(map[string]any)
if !ok {
return "", fmt.Errorf("context is not a map in json config at: %s", context)
}

// get the name field from the indexed object
name, ok := indexedMap["name"]
if !ok {
return "", fmt.Errorf("name not found in json config at: %s", context)
}

// name should be a string
if nameStr, ok := name.(string); !ok {
return "", fmt.Errorf("name is not a string in json config at: %v", context)
} else {
// set res to the name instead of the index
res = nameStr
}

// set jsonConfig to the indexed object
jsonConfig = indexedMap
} else {
// if key is not an index, then context should be a map
jsonMap, ok := jsonConfig.(map[string]any)
if !ok {
return "", fmt.Errorf("context is not a map in json config at: %s", context)
}

// set jsonConfig to the object at key
jsonConfig, ok = jsonMap[key]
if !ok {
return "", fmt.Errorf("context not found in json config at: %s", key)
}

// set res to the context key
res = key
}

if len(split) > 1 {
// if we have more context to parse, recurse
val, err := jsonToConfigContext(jsonConfig, split[1])
if err != nil {
return "", err
Expand Down

0 comments on commit 126bd71

Please sign in to comment.