/
lint.go
58 lines (48 loc) · 1.41 KB
/
lint.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// SPDX-FileCopyrightText: 2019 Elasticsearch B.V.
// SPDX-FileCopyrightText: 2019-2023 Thibault NORMAND <me@zenithar.org>
//
// SPDX-License-Identifier: Apache-2.0 AND MIT
package ruleset
import (
"errors"
"fmt"
"io"
"github.com/xeipuuv/gojsonschema"
"zntr.io/harp/v2/api/jsonschema"
"zntr.io/harp/v2/pkg/sdk/convert"
"zntr.io/harp/v2/pkg/sdk/types"
)
// JSONSchema returns the used json schema for validation.
func JSONSchema() []byte {
return jsonschema.BundleV1RuleSetSchema()
}
// Lint to input reader content with Bundle jsonschema.
func Lint(r io.Reader) ([]gojsonschema.ResultError, error) {
// Check arguments
if types.IsNil(r) {
return nil, fmt.Errorf("reader is nil")
}
// Drain the reader
jsonReader, err := convert.YAMLtoJSON(r)
if err != nil {
return nil, fmt.Errorf("unable to parse input as YAML: %w", err)
}
// Drain reader
jsonData, err := io.ReadAll(jsonReader)
if err != nil {
return nil, fmt.Errorf("unable to drain all json reader content: %w", err)
}
// Prepare loaders
schemaLoader := gojsonschema.NewBytesLoader(jsonschema.BundleV1RuleSetSchema())
documentLoader := gojsonschema.NewBytesLoader(jsonData)
// Validate
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return nil, fmt.Errorf("ruleset validation failed %w", err)
}
if !result.Valid() {
return result.Errors(), errors.New("ruleset not valid")
}
// No error
return nil, nil
}