github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/flatmap/expand.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package flatmap
    19  
    20  import (
    21  	"strings"
    22  
    23  	"github.com/zntrio/harp/v2/pkg/bundle"
    24  )
    25  
    26  // Expand takes a map and a key (prefix) and expands that value into
    27  // a more complex structure. This is the reverse of the Flatten operation.
    28  func Expand(m bundle.KV, key string) interface{} {
    29  	// If the key is exactly a key in the map, just return it
    30  	if v, ok := m[key]; ok {
    31  		if v == "true" {
    32  			return true
    33  		} else if v == "false" {
    34  			return false
    35  		}
    36  
    37  		return v
    38  	}
    39  
    40  	// Check if this is a prefix in the map
    41  	prefix := key
    42  	if key != "" {
    43  		prefix = key + "/"
    44  	}
    45  	for k := range m {
    46  		if strings.HasPrefix(k, prefix) {
    47  			return expandMap(m, prefix)
    48  		}
    49  	}
    50  
    51  	return nil
    52  }
    53  
    54  func expandMap(m bundle.KV, prefix string) bundle.KV {
    55  	result := make(bundle.KV)
    56  	for k := range m {
    57  		if !strings.HasPrefix(k, prefix) {
    58  			// Prefix not found
    59  			continue
    60  		}
    61  
    62  		// Remove the prefix
    63  		key := k[len(prefix):]
    64  		idx := strings.Index(key, "/")
    65  		if idx != -1 {
    66  			key = key[:idx]
    67  		}
    68  		if _, ok := result[key]; ok {
    69  			continue
    70  		}
    71  
    72  		// Recursive call to handle subtree
    73  		result[key] = Expand(m, k[:len(prefix)+len(key)])
    74  	}
    75  
    76  	return result
    77  }