github.com/zntrio/harp/v2@v2.0.9/pkg/bundle/ruleset/lint.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 "errors" 22 "fmt" 23 "io" 24 25 "github.com/xeipuuv/gojsonschema" 26 27 "github.com/zntrio/harp/v2/api/jsonschema" 28 "github.com/zntrio/harp/v2/pkg/sdk/convert" 29 "github.com/zntrio/harp/v2/pkg/sdk/types" 30 ) 31 32 // JSONSchema returns the used json schema for validation. 33 func JSONSchema() []byte { 34 return jsonschema.BundleV1RuleSetSchema() 35 } 36 37 // Lint to input reader content with Bundle jsonschema. 38 func Lint(r io.Reader) ([]gojsonschema.ResultError, error) { 39 // Check arguments 40 if types.IsNil(r) { 41 return nil, fmt.Errorf("reader is nil") 42 } 43 44 // Drain the reader 45 jsonReader, err := convert.YAMLtoJSON(r) 46 if err != nil { 47 return nil, fmt.Errorf("unable to parse input as YAML: %w", err) 48 } 49 50 // Drain reader 51 jsonData, err := io.ReadAll(jsonReader) 52 if err != nil { 53 return nil, fmt.Errorf("unable to drain all json reader content: %w", err) 54 } 55 56 // Prepare loaders 57 schemaLoader := gojsonschema.NewBytesLoader(jsonschema.BundleV1RuleSetSchema()) 58 documentLoader := gojsonschema.NewBytesLoader(jsonData) 59 60 // Validate 61 result, err := gojsonschema.Validate(schemaLoader, documentLoader) 62 if err != nil { 63 return nil, fmt.Errorf("ruleset validation failed %w", err) 64 } 65 if !result.Valid() { 66 return result.Errors(), errors.New("ruleset not valid") 67 } 68 69 // No error 70 return nil, nil 71 }