istio.io/istio@v0.0.0-20240520182934-d79c90f27776/operator/pkg/tpath/util.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  /*
    16  util.go contains utility function for dealing with trees.
    17  */
    18  
    19  package tpath
    20  
    21  import (
    22  	"gopkg.in/yaml.v2"
    23  	yaml2 "sigs.k8s.io/yaml"
    24  
    25  	"istio.io/istio/operator/pkg/util"
    26  )
    27  
    28  // AddSpecRoot adds a root node called "spec" to the given tree and returns the resulting tree.
    29  func AddSpecRoot(tree string) (string, error) {
    30  	t, nt := make(map[string]any), make(map[string]any)
    31  	if err := yaml.Unmarshal([]byte(tree), &t); err != nil {
    32  		return "", err
    33  	}
    34  	nt["spec"] = t
    35  	out, err := yaml.Marshal(nt)
    36  	if err != nil {
    37  		return "", err
    38  	}
    39  	return string(out), nil
    40  }
    41  
    42  // GetSpecSubtree returns the subtree under "spec".
    43  func GetSpecSubtree(yml string) (string, error) {
    44  	return GetConfigSubtree(yml, "spec")
    45  }
    46  
    47  // GetConfigSubtree returns the subtree at the given path.
    48  func GetConfigSubtree(manifest, path string) (string, error) {
    49  	root := make(map[string]any)
    50  	if err := yaml2.Unmarshal([]byte(manifest), &root); err != nil {
    51  		return "", err
    52  	}
    53  
    54  	nc, _, err := GetPathContext(root, util.PathFromString(path), false)
    55  	if err != nil {
    56  		return "", err
    57  	}
    58  	out, err := yaml2.Marshal(nc.Node)
    59  	if err != nil {
    60  		return "", err
    61  	}
    62  	return string(out), nil
    63  }