github.com/zntrio/harp/v2@v2.0.9/pkg/bundle/ruleset/reader.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package ruleset 19 20 import ( 21 "fmt" 22 "io" 23 24 "google.golang.org/protobuf/encoding/protojson" 25 26 bundlev1 "github.com/zntrio/harp/v2/api/gen/go/harp/bundle/v1" 27 "github.com/zntrio/harp/v2/pkg/sdk/convert" 28 "github.com/zntrio/harp/v2/pkg/sdk/types" 29 ) 30 31 // YAML a given reader in order to extract a BundlePatch sepcification. 32 func YAML(r io.Reader) (*bundlev1.RuleSet, error) { 33 // Check arguments 34 if types.IsNil(r) { 35 return nil, fmt.Errorf("reader is nil") 36 } 37 38 // Drain the reader 39 jsonReader, err := convert.YAMLtoJSON(r) 40 if err != nil { 41 return nil, fmt.Errorf("unable to parse input as BundlePatch: %w", err) 42 } 43 44 // Drain reader 45 jsonData, err := io.ReadAll(jsonReader) 46 if err != nil { 47 return nil, fmt.Errorf("unable to drain all json reader content: %w", err) 48 } 49 50 // Initialize empty definition object 51 def := bundlev1.RuleSet{} 52 def.Reset() 53 54 // Deserialize JSON with JSONPB wrapper 55 if err := protojson.Unmarshal(jsonData, &def); err != nil { 56 return nil, fmt.Errorf("unable to decode spec as json: %w", err) 57 } 58 59 // Validate spec 60 if err := Validate(&def); err != nil { 61 return nil, fmt.Errorf("unable to validate descriptor: %w", err) 62 } 63 64 // No error 65 return &def, nil 66 }