UNPKG

2.41 kBJavaScriptView Raw
1/**
2 * This script is used to inline assertions into the README.md documents.
3 */
4import _ from 'lodash';
5import glob from 'glob';
6import path from 'path';
7import fs from 'fs';
8
9const formatCodeSnippet = (setup) => {
10 const paragraphs = [];
11
12 if (setup.options) {
13 paragraphs.push('// Options: ' + JSON.stringify(setup.options));
14 }
15
16 paragraphs.push(setup.code);
17
18 if (setup.errors) {
19 setup.errors.forEach((message) => {
20 paragraphs.push('// Message: ' + message.message);
21 });
22 }
23
24 if (setup.rules) {
25 paragraphs.push('// Additional rules: ' + JSON.stringify(setup.rules));
26 }
27
28 return paragraphs.join('\n');
29};
30
31const getAssertions = () => {
32 const assertionFiles = glob.sync(path.resolve(__dirname, './../tests/rules/assertions/*.js'));
33
34 const assertionNames = _.map(assertionFiles, (filePath) => {
35 return path.basename(filePath, '.js');
36 });
37
38 const assertionCodes = _.map(assertionFiles, (filePath) => {
39 const codes = require(filePath);
40
41 return {
42 valid: _.map(codes.valid, formatCodeSnippet),
43 invalid: _.map(codes.invalid, formatCodeSnippet)
44 };
45 });
46
47 return _.zipObject(assertionNames, assertionCodes);
48};
49
50const updateDocuments = (assertions) => {
51 const readmeDocumentPath = path.join(__dirname, './../README.md');
52
53 let documentBody = fs.readFileSync(readmeDocumentPath, 'utf8');
54
55 documentBody = documentBody.replace(/<!-- assertions ([a-z]+?) -->/ig, (assertionsBlock) => {
56 let exampleBody;
57
58 const ruleName = assertionsBlock.match(/assertions ([a-z]+)/i)[1];
59
60 const ruleAssertions = assertions[ruleName];
61
62 if (!ruleAssertions) {
63 throw new Error('No assertions available for rule "' + ruleName + '".');
64
65 return assertionsBlock;
66 }
67
68 exampleBody = '';
69
70 if (ruleAssertions.invalid.length) {
71 exampleBody += 'The following patterns are considered problems:\n\n```js\n' + ruleAssertions.invalid.join('\n\n') + '\n```\n\n';
72 }
73
74 if (ruleAssertions.valid.length) {
75 exampleBody += 'The following patterns are not considered problems:\n\n```js\n' + ruleAssertions.valid.join('\n\n') + '\n```\n\n';
76 }
77
78 return exampleBody;
79 });
80
81 fs.writeFileSync(readmeDocumentPath, documentBody);
82};
83
84updateDocuments(getAssertions());