-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathvalidate.ts
67 lines (62 loc) · 1.83 KB
/
validate.ts
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
import type {Command} from "./types"
import type {ParsedArgs} from "minimist"
import {compile, getFiles, openFile, logJSON} from "./util"
import getAjv from "./ajv"
import * as jsonPatch from "fast-json-patch"
import * as fs from "fs"
const cmd: Command = {
execute,
schema: {
type: "object",
required: ["s", "d"],
properties: {
s: {
type: "string",
format: "notGlob",
},
d: {$ref: "#/$defs/stringOrArray"},
r: {$ref: "#/$defs/stringOrArray"},
m: {$ref: "#/$defs/stringOrArray"},
c: {$ref: "#/$defs/stringOrArray"},
o: {type: "string", format: "notGlob"},
errors: {enum: ["json", "line", "text", "js", "no"]},
changes: {enum: [true, "json", "line", "js"]},
spec: {enum: ["draft7", "draft2019", "draft2020", "jtd"]},
},
ajvOptions: true,
},
}
export default cmd
function execute(argv: ParsedArgs): boolean {
const ajv = getAjv(argv)
const validate = compile(ajv, argv.s)
return getFiles(argv.d)
.map(validateDataFile)
.every((x) => x)
function validateDataFile(file: string): boolean {
const data = openFile(file, `data file ${file}`)
let original
if (argv.changes) original = JSON.parse(JSON.stringify(data))
const validData = validate(data) as boolean
if (validData) {
console.log(file, "valid")
if (argv.changes) {
const patch = jsonPatch.compare(original, data)
if (patch.length === 0) {
console.log("no changes")
} else {
console.log("changes:")
console.log(logJSON(argv.changes, patch))
}
}
} else {
console.error(file, "invalid")
if (argv.o) {
fs.writeFileSync(argv.o, JSON.stringify(validate.errors))
} else {
console.error(logJSON(argv.errors, validate.errors, ajv))
}
}
return validData
}
}