/
policy_validate.go
65 lines (50 loc) · 1.14 KB
/
policy_validate.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
59
60
61
62
63
64
65
package cmd
import (
"bytes"
_ "embed"
"fmt"
"log"
"github.com/santhosh-tekuri/jsonschema/v5"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
//go:embed policy.schema.json
var policySchemaFile []byte
var (
policyValidateCmd = &cobra.Command{
Use: "validate",
Short: "Validates a policy file to match the schema",
RunE: func(cmd *cobra.Command, args []string) error {
_, policyFile, err := loadPolicyFile(policyFileFl)
if err != nil {
log.Fatal(err)
}
schemaReader := bytes.NewReader(policySchemaFile)
if err != nil {
log.Fatal(err)
}
var m interface{}
err = yaml.Unmarshal(policyFile, &m)
if err != nil {
log.Fatal(err)
}
compiler := jsonschema.NewCompiler()
if err := compiler.AddResource("policy.schema.json", schemaReader); err != nil {
log.Fatal(err)
}
schema, err := compiler.Compile("policy.schema.json")
if err != nil {
log.Fatal(err)
}
if err := schema.Validate(m); err != nil {
log.Fatal(err)
}
fmt.Println("Validation successful.")
return nil
},
}
)
func init() {
AddPolicyFileFlag(policyValidateCmd)
policyCmd.AddCommand(policyValidateCmd)
}