/
main.go
142 lines (129 loc) · 2.44 KB
/
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package main
import (
"fmt"
"github.com/xeipuuv/gojsonschema"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"strings"
)
type Context struct {
schema *gojsonschema.Schema
result chan<- string
running chan<- bool
}
func validateFile(ctx Context, path string) {
ctx.running <- true
defer func() {
ctx.running <- false
}()
//fmt.Println(path)
bytes, err := ioutil.ReadFile(path)
if err != nil {
ctx.result <- fmt.Sprint(err)
return
}
result, err := ctx.schema.Validate(gojsonschema.NewStringLoader(string(bytes)))
if err != nil {
ctx.result <- fmt.Sprint(path, err)
return
}
if !result.Valid() {
errors := result.Errors()
res := make([]string, 1+len(errors))
res[0] = fmt.Sprintf("%s:", path)
//ctx.result <- fmt.Sprintf("%s:\n", path)
for i, desc := range errors {
res[1+i] = fmt.Sprint(desc)
}
ctx.result <- strings.Join(res, "\n- ") + "\n"
} else {
//ctx.result <- = fmt.Sprintf("%s: ok\n", path)
}
}
func validateDir(ctx Context, dir string) {
ctx.running <- true
defer func() {
ctx.running <- false
}()
file, err := os.Open(dir)
if err != nil {
ctx.result <- fmt.Sprintln(err)
return
}
defer file.Close()
for {
fi, errDir := file.Readdir(50)
if errDir == nil {
for _, any := range fi {
path := dir + "/" + any.Name()
if any.IsDir() {
// Recurse
go validateDir(ctx, path)
} else {
go validateFile(ctx, path)
}
}
} else {
if errDir != io.EOF {
ctx.result <- fmt.Sprintln(err)
}
break
}
}
}
func validateAny(ctx Context, path string) {
if fileinfo, err := os.Stat(path); err == nil {
if fileinfo.IsDir() {
go validateDir(ctx, path)
} else {
go validateFile(ctx, path)
}
} else {
panic(err)
}
}
func main() {
result := make(chan string)
running := make(chan bool)
ctx := Context{
result: result,
running: running,
}
schemaFile, err := filepath.Abs(os.Args[1])
u := url.URL{
Scheme: "file",
Path: schemaFile,
}
ctx.schema, err = gojsonschema.NewSchema(gojsonschema.NewReferenceLoader(u.String()))
if err != nil {
panic(err)
}
if len(os.Args) == 2 {
fmt.Println("missing files/dir to process")
return
}
for _, arg := range os.Args[2:] {
validateAny(ctx, arg)
}
count := 0
for {
select {
case r := <-running:
if r {
count++
} else {
count--
if count == 0 {
//fmt.Println("Done.")
return
}
}
//fmt.Println("Running: ", count)
case r := <-result:
fmt.Print(r)
}
}
}