-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate_config.go
79 lines (62 loc) · 1.61 KB
/
validate_config.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
72
73
74
75
76
77
78
79
package main
import (
"fmt"
"io/ioutil"
"os"
"github.com/xeipuuv/gojsonschema"
"gopkg.in/yaml.v2"
)
// ValidateSchema is
func ValidateSchema(config Config) {
configFileData, err := getFileData(config)
check(err)
schemaURL := "https://github.com/finnplay/validator/raw/master/schema/" + config.Schema
fmt.Printf("Using schema URL: %s\n", schemaURL)
result, isValid := runSchemaValidation(configFileData, schemaURL)
check(err)
if isValid {
fmt.Printf("Config %s is valid\n", config.Path)
os.Exit(0)
} else {
fmt.Printf("Config %s is invalid:\n", config.Path)
for _, error := range result.Errors() {
fmt.Printf("%s\n", error)
}
os.Exit(1)
}
}
func getFileData(config Config) (interface{}, error) {
result, err := ioutil.ReadFile(config.Path)
check(err)
var document interface{}
if err := yaml.Unmarshal([]byte(result), &document); err != nil {
panic(err)
}
var fileData interface{} = convertConfig(document)
return fileData, nil
}
func convertConfig(i interface{}) interface{} {
switch x := i.(type) {
case map[interface{}]interface{}:
m2 := map[string]interface{}{}
for k, v := range x {
m2[k.(string)] = convertConfig(v)
}
return m2
case []interface{}:
for i, v := range x {
x[i] = convertConfig(v)
}
}
return i
}
func runSchemaValidation(fileData interface{}, schemaURL string) (*gojsonschema.Result, bool) {
schemaLoader := gojsonschema.NewReferenceLoader(schemaURL)
configLoader := gojsonschema.NewGoLoader(fileData)
result, err := gojsonschema.Validate(schemaLoader, configLoader)
check(err)
if result.Valid() {
return result, true
}
return result, false
}