istio.io/istio@v0.0.0-20240520182934-d79c90f27776/operator/pkg/translate/yaml_tree.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package translate
    16  
    17  import (
    18  	"gopkg.in/yaml.v2"
    19  
    20  	"istio.io/istio/operator/pkg/tpath"
    21  	"istio.io/istio/operator/pkg/util"
    22  )
    23  
    24  // YAMLTree takes an input tree inTreeStr, a partially constructed output tree outTreeStr, and a map of
    25  // translations of source-path:dest-path in pkg/tpath format. It returns an output tree with paths from the input
    26  // tree, translated and overlaid on the output tree.
    27  func YAMLTree(inTreeStr, outTreeStr string, translations map[string]string) (string, error) {
    28  	inTree := make(map[string]any)
    29  	if err := yaml.Unmarshal([]byte(inTreeStr), &inTree); err != nil {
    30  		return "", err
    31  	}
    32  	outTree := make(map[string]any)
    33  	if err := yaml.Unmarshal([]byte(outTreeStr), &outTree); err != nil {
    34  		return "", err
    35  	}
    36  
    37  	for inPath, translation := range translations {
    38  		path := util.PathFromString(inPath)
    39  		node, found, err := tpath.Find(inTree, path)
    40  		if err != nil {
    41  			return "", err
    42  		}
    43  		if !found {
    44  			continue
    45  		}
    46  
    47  		if err := tpath.MergeNode(outTree, util.PathFromString(translation), node); err != nil {
    48  			return "", err
    49  		}
    50  	}
    51  
    52  	outYAML, err := yaml.Marshal(outTree)
    53  	if err != nil {
    54  		return "", err
    55  	}
    56  	return string(outYAML), nil
    57  }