Skip to content

Commit

Permalink
tools: add eslint rule for documented errors
Browse files Browse the repository at this point in the history
PR-URL: #16450
Reviewed-By: Anatoli Papirovski <[email protected]>
Reviewed-By: Refael Ackermann <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: Teddy Katz <[email protected]>
  • Loading branch information
jasnell committed Oct 26, 2017
1 parent fb477f3 commit 76b8803
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint documented-errors: "error" */
/* eslint alphabetize-errors: "error" */

'use strict';
Expand Down
34 changes: 34 additions & 0 deletions test/parallel/test-eslint-documented-errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';

require('../common');

const RuleTester = require('../../tools/eslint').RuleTester;
const rule = require('../../tools/eslint-rules/documented-errors');

const invalidCode = 'UNDOCUMENTED ERROR CODE';

new RuleTester().run('documented-errors', rule, {
valid: [
`
E('ERR_ASSERTION', 'foo');
`
],
invalid: [
{
code: `
E('${invalidCode}', 'bar');
`,
errors: [
{
message: `"${invalidCode}" is not documented in doc/api/errors.md`,
line: 2
},
{
message:
`doc/api/errors.md does not have an anchor for "${invalidCode}"`,
line: 2
}
]
}
]
});
46 changes: 46 additions & 0 deletions tools/eslint-rules/documented-errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
'use strict';

const fs = require('fs');
const path = require('path');

const doc = fs.readFileSync(path.resolve(__dirname, '../../doc/api/errors.md'),
'utf8');

function isInDoc(code) {
return doc.match(`### ${code}`) != null;
}

function includesAnchor(code) {
return doc.match(`<a id="${code}"></a>`) != null;
}

function errorForNode(node) {
return node.expression.arguments[0].value;
}

function isDefiningError(node) {
return node.expression &&
node.expression.type === 'CallExpression' &&
node.expression.callee &&
node.expression.callee.name === 'E';
}

module.exports = {
create: function(context) {
return {
ExpressionStatement: function(node) {
if (!isDefiningError(node)) return;
const code = errorForNode(node);
if (!isInDoc(code)) {
const message = `"${code}" is not documented in doc/api/errors.md`;
context.report({ node, message });
}
if (!includesAnchor(code)) {
const message =
`doc/api/errors.md does not have an anchor for "${code}"`;
context.report({ node, message });
}
}
};
}
};

0 comments on commit 76b8803

Please sign in to comment.