/
addAssertions.js
91 lines (65 loc) · 2.38 KB
/
addAssertions.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
#!/usr/bin/env node
/**
* @file This script is used to inline assertions into the README.md documents.
*/
import path from 'path';
import fs from 'fs';
import glob from 'glob';
import _ from 'lodash';
const formatCodeSnippet = (setup) => {
const paragraphs = [];
if (setup.options) {
paragraphs.push('// Options: ' + JSON.stringify(setup.options));
}
if (setup.settings) {
paragraphs.push('// Settings: ' + JSON.stringify(setup.settings));
}
paragraphs.push(setup.code);
if (setup.errors) {
setup.errors.forEach((message) => {
paragraphs.push('// Message: ' + message.message);
});
}
if (setup.rules) {
paragraphs.push('// Additional rules: ' + JSON.stringify(setup.rules));
}
return paragraphs.join('\n');
};
const getAssertions = () => {
const assertionFiles = glob.sync(path.resolve(__dirname, '../../tests/rules/assertions/*.js'));
const assertionNames = _.map(assertionFiles, (filePath) => {
return path.basename(filePath, '.js');
});
const assertionCodes = _.map(assertionFiles, (filePath) => {
// eslint-disable-next-line global-require, import/no-dynamic-require
const codes = require(filePath);
return {
invalid: _.map(codes.invalid, formatCodeSnippet),
valid: _.map(codes.valid, formatCodeSnippet),
};
});
return _.zipObject(assertionNames, assertionCodes);
};
const updateDocuments = (assertions) => {
const readmeDocumentPath = path.join(__dirname, '../../README.md');
let documentBody;
documentBody = fs.readFileSync(readmeDocumentPath, 'utf8');
documentBody = documentBody.replace(/<!-- assertions ([a-z]+?) -->/gi, (assertionsBlock) => {
let exampleBody;
const ruleName = assertionsBlock.match(/assertions ([a-z]+)/i)[1];
const ruleAssertions = assertions[ruleName];
if (!ruleAssertions) {
throw new Error('No assertions available for rule "' + ruleName + '".');
}
exampleBody = '';
if (ruleAssertions.invalid.length) {
exampleBody += 'The following patterns are considered problems:\n\n```js\n' + ruleAssertions.invalid.join('\n\n') + '\n```\n\n';
}
if (ruleAssertions.valid.length) {
exampleBody += 'The following patterns are not considered problems:\n\n```js\n' + ruleAssertions.valid.join('\n\n') + '\n```\n\n';
}
return exampleBody;
});
fs.writeFileSync(readmeDocumentPath, documentBody);
};
updateDocuments(getAssertions());