/
validate.go
71 lines (61 loc) · 1.73 KB
/
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
66
67
68
69
70
71
// Package validatejson impliments validate-json command
package validatejson
import (
"errors"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/taskcluster/taskcluster/v46/clients/client-shell/cmds/root"
js "github.com/xeipuuv/gojsonschema"
)
var (
Command = &cobra.Command{
Use: "validate-json <json-schema> <json-file>",
Short: "Validate json file by provided json-schema",
Args: cobra.ExactArgs(2),
RunE: validate,
}
log = root.Logger
)
func init() {
root.Command.AddCommand(Command)
}
// Takes json-schema & json as input which should be in the following 2 formats
// 1. https://community-tc.services.mozilla.com/references/schemas/<some-schema>.json
// 2. file:///home/user/<some-schema>.json
func validate(cmd *cobra.Command, args []string) error {
schema := schemaLoader(args[0])
document := schemaLoader(args[1])
result, err := js.Validate(schema, document)
if err != nil {
return err
}
if result.Valid() {
log.Info("The document is valid\n")
} else {
for _, desc := range result.Errors() {
log.Infof("- %s\n", desc)
}
return errors.New("the document is not valid")
}
return nil
}
// In case user don't provide absolute path, it should be generate & return a JSONLoader
// Input: path to json schema
// Return: JSON loader interface
func schemaLoader(path string) js.JSONLoader {
if strings.HasPrefix(path, "http") || strings.HasPrefix(path, "file://") {
return js.NewReferenceLoader(path)
} else if filepath.IsAbs(path) {
path = "file://" + path
} else if !filepath.IsAbs(path) {
fullPath, err := filepath.Abs(path)
if err != nil {
log.Fatal(err)
}
path = "file://" + fullPath
} else {
log.Panic("Input isn't supported in the format")
}
return js.NewReferenceLoader(path)
}