1// Copyright 2020 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/* 16util.go contains utility function for dealing with trees. 17*/ 18 19package tpath 20 21import ( 22 yaml2 "github.com/ghodss/yaml" 23 "gopkg.in/yaml.v2" 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. 29func AddSpecRoot(tree string) (string, error) { 30 t, nt := make(map[string]interface{}), make(map[string]interface{}) 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". 43func GetSpecSubtree(yml string) (string, error) { 44 return GetConfigSubtree(yml, "spec") 45} 46 47// GetConfigSubtree returns the subtree at the given path. 48func GetConfigSubtree(manifest, path string) (string, error) { 49 root := make(map[string]interface{}) 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} 64