-
Notifications
You must be signed in to change notification settings - Fork 1
/
ajv.js
85 lines (71 loc) · 1.95 KB
/
ajv.js
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
import fs from "node:fs/promises";
import Ajv from "ajv/dist/2020.js";
import addFormats from "ajv-formats";
import chalk from "chalk";
import YAML from "yaml";
/**
* @typedef {"colors"|"flag"|"patterns"} SchemaID
*/
const ajv = new Ajv({ allErrors: true, strict: true });
addFormats(ajv);
await addSchema("schemas/colors.yaml");
await addSchema("schemas/flag.yaml");
await addSchema("schemas/patterns.yaml");
await validateData("data/colors.yaml", "colors");
await validateData("data/flags/*.yaml", "flag");
await validateData("data/patterns.yaml", "patterns");
/**
* @param {string} file
*/
async function addSchema(file) {
const schema = await loadFile(file);
ajv.addSchema(schema);
}
/**
* @param {string} filePattern
* @param {SchemaID} schemaID
*/
async function validateData(filePattern, schemaID) {
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const files = await fs.glob(filePattern);
for await (const file of files) {
const data = await loadFile(file);
ajv.validate(schemaID, data);
logErrors({ file, schemaID, errors: ajv.errors });
}
}
/**
* @param {string} schema
* @returns {Promise<any>}
*/
async function loadFile(schema) {
const file = await fs.readFile(schema, { encoding: "utf8" });
return YAML.parse(file);
}
/**
*
* @param {object} options
* @param {string} options.file
* @param {SchemaID} options.schemaID
* @param {Ajv["errors"]} options.errors
*/
function logErrors({ file, schemaID, errors }) {
if (!errors) {
return;
}
process.exitCode = 1;
let index = 1;
console.log(chalk.underline(file));
console.log();
for (const error of errors) {
const errorIndex = chalk.red(index++);
const errorDataPath = chalk.cyan(error.instancePath);
const errorMessage = error.message;
const errorSchemaPath = chalk.italic(
`schemas/${schemaID}.yaml${error.schemaPath}`,
);
console.log(` ${errorIndex} ${errorDataPath} ${errorMessage}`);
console.log(` ${errorSchemaPath}`);
console.log();
}
}