istio
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
15package translate16
17import (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.
27func YAMLTree(inTreeStr, outTreeStr string, translations map[string]string) (string, error) {28inTree := make(map[string]any)29if err := yaml.Unmarshal([]byte(inTreeStr), &inTree); err != nil {30return "", err31}32outTree := make(map[string]any)33if err := yaml.Unmarshal([]byte(outTreeStr), &outTree); err != nil {34return "", err35}36
37for inPath, translation := range translations {38path := util.PathFromString(inPath)39node, found, err := tpath.Find(inTree, path)40if err != nil {41return "", err42}43if !found {44continue45}46
47if err := tpath.MergeNode(outTree, util.PathFromString(translation), node); err != nil {48return "", err49}50}51
52outYAML, err := yaml.Marshal(outTree)53if err != nil {54return "", err55}56return string(outYAML), nil57}
58