istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/test/util/yml/parse.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 yml 16 17 import ( 18 "encoding/json" 19 "fmt" 20 "strings" 21 22 "sigs.k8s.io/yaml" 23 ) 24 25 // Metadata metadata for a kubernetes resource. 26 type Metadata struct { 27 Name string `json:"name"` 28 Namespace string `json:"namespace"` 29 } 30 31 // Descriptor a descriptor for a kubernetes resource. 32 type Descriptor struct { 33 Kind string `json:"kind"` 34 Group string `json:"group"` 35 APIVersion string `json:"apiVersion"` 36 Metadata Metadata `json:"metadata"` 37 } 38 39 // Part is a single-part yaml source, along with its descriptor. 40 type Part struct { 41 Contents string 42 Descriptor Descriptor 43 } 44 45 // Parse parses the given multi-part yaml text, and returns as Parts. 46 func Parse(yamlText string) ([]Part, error) { 47 splitContent := SplitString(yamlText) 48 parts := make([]Part, 0, len(splitContent)) 49 for _, part := range splitContent { 50 if len(part) > 0 { 51 descriptor, err := ParseDescriptor(part) 52 if err != nil { 53 return nil, err 54 } 55 56 parts = append(parts, Part{ 57 Contents: part, 58 Descriptor: descriptor, 59 }) 60 } 61 } 62 return parts, nil 63 } 64 65 // ParseDescriptor parses the given single-part yaml and generates the descriptor. 66 func ParseDescriptor(yamlText string) (Descriptor, error) { 67 d := Descriptor{} 68 jsonText, err := yaml.YAMLToJSON([]byte(yamlText)) 69 if err != nil { 70 return Descriptor{}, fmt.Errorf("failed converting YAML to JSON: %v", err) 71 } 72 73 if err := json.Unmarshal(jsonText, &d); err != nil { 74 return Descriptor{}, fmt.Errorf("failed parsing descriptor: %v", err) 75 } 76 77 parts := strings.Split(d.APIVersion, "/") 78 switch len(parts) { 79 case 1: 80 d.APIVersion = parts[0] 81 case 2: 82 d.Group = parts[0] 83 d.APIVersion = parts[1] 84 default: 85 return Descriptor{}, fmt.Errorf("unexpected apiGroup: %q", d.APIVersion) 86 } 87 88 return d, nil 89 }