-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.js
240 lines (202 loc) · 6.23 KB
/
index.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
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/**
* yaml-validator
* https://github.com/paazmaya/yaml-validator
*
* Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (https://paazmaya.fi)
* Licensed under the MIT license.
*/
import fs from 'node:fs';
import yaml from 'js-yaml';
import checkType from 'check-type';
const check = checkType.init();
const FIND_LINENUMBER = /(\d+):\d+/u;
class YamlValidatore {
constructor (options) {
this.options = Object.assign({
log: false,
structure: false,
onWarning: null,
writeJson: false
}, options);
this.logs = [];
this.nonValidPaths = []; // list of property paths
this.inValidFilesCount = 0;
}
/**
* Store log messages
* possible later use by writing a log file.
* @param {string} msg Error message
* @returns {void}
*/
errored(msg) {
this.logs.push(msg);
}
/**
* Check that the given structure is available.
* @param {Object} doc Object loaded from Yaml file
* @param {Object} structure Structure requirements
* @param {string} parent Address in a dot notation
* @returns {Array} List of not found structure paths
*/
validateStructure(doc, structure, parent) {
let notFound = [],
current = '',
notValid; // false or path
parent = parent || '';
Object.keys(structure).forEach((originKey) => {
const optional = originKey.endsWith('?');
const key = originKey.replace(/\?$/u, '');
current = parent;
if (!check(structure).is('Array')) {
current += (parent.length > 0 ?
'.' :
'') + key;
}
const item = structure[originKey];
if (item instanceof Array) {
if (check(doc).has(key) && check(doc[key]).is('Array')) {
doc[key].forEach((child, index) => {
if (item.length > 1) {
notValid = this.validateStructure([child], [item[index]], current + '[' + index + ']');
}
else {
notValid = this.validateStructure([child], item, current + '[' + index + ']');
}
notFound = notFound.concat(notValid);
});
}
else if (!optional) {
notFound.push(current);
}
}
else if (typeof item === 'string') {
if (!check(doc).has(key) && optional){
notValid = false;
}
else {
notValid = !((check(structure).is('Array') || check(doc).has(key)) && check(doc[key]).is(item));
}
// Key can be a index number when the structure is an array, but passed as a string
notFound.push(notValid ?
current :
false);
}
else if (typeof item === 'object' && item !== null) {
if (!optional) {
notValid = this.validateStructure(doc[key], item, current);
notFound = notFound.concat(notValid);
}
}
});
return notFound.filter(function filterFalse(item) {
return item !== false;
});
}
/**
* Parse the given Yaml data.
* @param {string} filepath Yaml file path
* @param {string} data Yaml data
* @returns {string|null} Parsed Yaml or null on failure
*/
loadData(filepath, data) {
const onWarning = (error) => {
this.errored(filepath + ' > ' + error);
if (typeof this.options.onWarning === 'function') {
this.options.onWarning.call(this, error, filepath);
}
};
let doc;
try {
doc = yaml.load(data, {
onWarning: onWarning
});
// i.e empty yml file
if (!doc) {
onWarning('File is empty');
return null;
}
}
catch (error) {
const findNumber = error.message.match(FIND_LINENUMBER);
const lineNumber = findNumber && findNumber.length > 0 ?
findNumber[1] :
'unknown';
console.error(`${filepath}:${lineNumber}\n${error.message}`);
onWarning(`Failed to load the Yaml file "${filepath}:${lineNumber}"\n${error.message}`);
return null;
}
return doc;
}
/**
* Read and parse the given Yaml file.
* @param {string} filepath Yaml file path
* @returns {string|null} Parsed Yaml or null on failure
*/
loadFile(filepath) {
// Verbose output will tell which file is being read
let data;
const _self = this;
try {
data = fs.readFileSync(filepath, 'utf8');
}
catch (err) {
_self.errored(filepath + ' > No such file or directory');
return null;
}
return this.loadData(filepath, data);
}
/**
* Read the given Yaml file, load and check its structure.
* @param {string} filepath Yaml file path
* @returns {number} 0 when no errors, 1 when errors.
*/
checkFile(filepath) {
const doc = this.loadFile(filepath);
if (!doc) {
return 1;
}
if (this.options.writeJson) {
const json = JSON.stringify(doc, null, ' ');
fs.writeFileSync(filepath.replace(/\.y(a)?ml$/iu, '.json'), json, 'utf8');
}
if (this.options.structure) {
const nonValidPaths = this.validateStructure(doc, this.options.structure);
if (nonValidPaths.length > 0) {
this.errored(filepath + ' is not following the correct structure, missing:');
this.errored(nonValidPaths.join('\n'));
this.nonValidPaths = this.nonValidPaths.concat(nonValidPaths);
return 1;
}
}
return 0;
}
/**
* Create a report out of this, but in reality also run.
* @param {array} files List of files that have been checked that they exist
* @returns {void}
*/
validate(files) {
const _self = this;
this.inValidFilesCount = files.map((filepath) => {
return _self.checkFile(filepath);
}).reduce((prev, curr) => {
return prev + curr;
}, _self.inValidFilesCount);
}
/**
* Create a report out of this, but in reality also run.
* @returns {number} 0 when no errors, the count of invalid files otherwise.
*/
report() {
if (this.inValidFilesCount > 0) {
this.errored('Yaml format related errors in ' + this.inValidFilesCount + ' files');
}
const len = this.nonValidPaths.length;
this.errored('Total of ' + len + ' structure validation error(s)');
if (typeof this.options.log === 'string') {
fs.writeFileSync(this.options.log, this.logs.join('\n'), 'utf8');
}
return this.inValidFilesCount;
}
}
export default YamlValidatore;