Skip to content

Commit

Permalink
feat: add new rules no-missing-message-ids and no-unused-message-ids
Browse files Browse the repository at this point in the history
  • Loading branch information
bmish committed Jun 29, 2022
1 parent 34bcb74 commit d91d1a0
Show file tree
Hide file tree
Showing 10 changed files with 1,065 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,10 @@ Name | ✔️ | 🛠 | 💡 | Description
[no-deprecated-context-methods](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/no-deprecated-context-methods.md) | ✔️ | 🛠 | | disallow usage of deprecated methods on rule context objects
[no-deprecated-report-api](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/no-deprecated-report-api.md) | ✔️ | 🛠 | | disallow the version of `context.report()` with multiple arguments
[no-identical-tests](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/no-identical-tests.md) | ✔️ | 🛠 | | disallow identical tests
[no-missing-message-ids](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/no-missing-message-ids.md) | | | | disallow `messageId`s that are missing from `meta.messages`
[no-missing-placeholders](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/no-missing-placeholders.md) | ✔️ | | | disallow missing placeholders in rule report messages
[no-only-tests](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/no-only-tests.md) | ✔️ | | 💡 | disallow the test case property `only`
[no-unused-message-ids](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/no-unused-message-ids.md) | | | | disallow unused `messageId`s in `meta.messages`
[no-unused-placeholders](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/no-unused-placeholders.md) | ✔️ | | | disallow unused placeholders in rule report messages
[no-useless-token-range](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/no-useless-token-range.md) | ✔️ | 🛠 | | disallow unnecessary calls to `sourceCode.getFirstToken()` and `sourceCode.getLastToken()`
[prefer-message-ids](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/prefer-message-ids.md) | | | | require using `messageId` instead of `message` to report rule violations
Expand Down
59 changes: 59 additions & 0 deletions docs/rules/no-missing-message-ids.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Disallow `messageId`s that are missing from `meta.messages` (no-missing-message-ids)

When using `meta.messages` and `messageId` to report rule violations, it's possible to mistakenly use a `messageId` that doesn't exist in `meta.messages`.

## Rule Details

Examples of **incorrect** code for this rule:

```js
/* eslint eslint-plugin/no-missing-message-ids: error */

module.exports = {
meta: {
messages: {
foo: 'hello world',
},
},
create(context) {
return {
CallExpression(node) {
context.report({
node,
messageId: 'abc',
});
},
};
},
};
```

Examples of **correct** code for this rule:

```js
/* eslint eslint-plugin/no-missing-message-ids: error */

module.exports = {
meta: {
messages: {
foo: 'hello world',
},
},
create(context) {
return {
CallExpression(node) {
context.report({
node,
messageId: 'foo',
});
},
};
},
};
```

## Further Reading

* [messageIds API](https://eslint.org/docs/developer-guide/working-with-rules#messageids)
* [no-unused-message-ids](./no-unused-message-ids.md) rule
* [prefer-message-ids](./prefer-message-ids.md) rule
60 changes: 60 additions & 0 deletions docs/rules/no-unused-message-ids.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Disallow unused `messageId`s in `meta.messages` (no-unused-message-ids)

When using `meta.messages` and `messageId` to report rule violations, it's possible to mistakenly leave a message in `meta.messages` that is never used.

## Rule Details

Examples of **incorrect** code for this rule:

```js
/* eslint eslint-plugin/no-unused-message-ids: error */

module.exports = {
meta: {
messages: {
foo: 'hello world',
bar: 'lorem ipsum', // this message is never used
},
},
create(context) {
return {
CallExpression(node) {
context.report({
node,
messageId: 'foo',
});
},
};
},
};
```

Examples of **correct** code for this rule:

```js
/* eslint eslint-plugin/no-unused-message-ids: error */

module.exports = {
meta: {
messages: {
foo: 'hello world',
},
},
create(context) {
return {
CallExpression(node) {
context.report({
node,
messageId: 'foo',
});
},
};
},
};
```

## Further Reading

* [messageIds API](https://eslint.org/docs/developer-guide/working-with-rules#messageids)
* [no-missing-message-ids](./no-missing-message-ids.md) rule
* [prefer-message-ids](./prefer-message-ids.md) rule
2 changes: 2 additions & 0 deletions docs/rules/prefer-message-ids.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,5 @@ module.exports = {
## Further Reading

* [messageIds API](https://eslint.org/docs/developer-guide/working-with-rules#messageids)
* [no-invalid-message-ids](./no-invalid-message-ids.md) rule
* [no-missing-message-ids](./no-missing-message-ids.md) rule
89 changes: 89 additions & 0 deletions lib/rules/no-missing-message-ids.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
'use strict';

const utils = require('../utils');

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'problem',
docs: {
description:
'disallow `messageId`s that are missing from `meta.messages`',
category: 'Rules',
recommended: false,
url: 'https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/tree/HEAD/docs/rules/no-missing-message-ids.md',
},
fixable: null,
schema: [],
messages: {
missingMessage: '`meta.messages` is missing this `messageId`.',
},
},

create(context) {
const sourceCode = context.getSourceCode();
const { scopeManager } = sourceCode;
const ruleInfo = utils.getRuleInfo(sourceCode);

const messagesNode = utils.getMessagesNode(ruleInfo, scopeManager);

let contextIdentifiers;

// ----------------------------------------------------------------------
// Public
// ----------------------------------------------------------------------

if (!messagesNode || messagesNode.type !== 'ObjectExpression') {
return {};
}

return {
Program(ast) {
contextIdentifiers = utils.getContextIdentifiers(scopeManager, ast);
},

CallExpression(node) {
if (
node.callee.type === 'MemberExpression' &&
contextIdentifiers.has(node.callee.object) &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'report'
) {
const reportInfo = utils.getReportInfo(node.arguments, context);
if (!reportInfo) {
return;
}

const reportMessagesAndDataArray =
utils.collectReportViolationAndSuggestionData(reportInfo);

for (const { messageId } of reportMessagesAndDataArray.filter(
(obj) => obj.messageId
)) {
const values =
messageId.type === 'Literal'
? [messageId]
: utils.findPossibleVariableValues(messageId, scopeManager);

values.forEach((val) => {
if (
val.type === 'Literal' &&
val.value !== null &&
val.value !== '' &&
!utils.getMessageIdNodeById(val.value, ruleInfo, scopeManager)
)
context.report({
node: val,
messageId: 'missingMessage',
});
});
}
}
},
};
},
};
98 changes: 98 additions & 0 deletions lib/rules/no-unused-message-ids.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
'use strict';

const utils = require('../utils');

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'disallow unused `messageId`s in `meta.messages`',
category: 'Rules',
recommended: false,
url: 'https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/tree/HEAD/docs/rules/no-unused-message-ids.md',
},
fixable: null,
schema: [],
messages: {
unusedMessage: 'This message is never used.',
},
},

create(context) {
const sourceCode = context.getSourceCode();
const { scopeManager } = sourceCode;
const info = utils.getRuleInfo(sourceCode);

const messageIdsUsed = new Set();
let contextIdentifiers;
let shouldPerformUnusedCheck = true;

const messageIdNodes = utils.getMessageIdNodes(info, scopeManager);
if (!messageIdNodes) {
return {};
}

// ----------------------------------------------------------------------
// Public
// ----------------------------------------------------------------------

return {
Program(ast) {
contextIdentifiers = utils.getContextIdentifiers(scopeManager, ast);
},

'Program:exit'() {
if (shouldPerformUnusedCheck) {
for (const messageIdNode of messageIdNodes.filter(
(node) => !messageIdsUsed.has(node.key.name)
)) {
context.report({
node: messageIdNode,
messageId: 'unusedMessage',
});
}
}
},

CallExpression(node) {
if (
node.callee.type === 'MemberExpression' &&
contextIdentifiers.has(node.callee.object) &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'report'
) {
const reportInfo = utils.getReportInfo(node.arguments, context);
if (!reportInfo) {
return;
}

const reportMessagesAndDataArray =
utils.collectReportViolationAndSuggestionData(reportInfo);

for (const { messageId } of reportMessagesAndDataArray.filter(
(obj) => obj.messageId
)) {
const values =
messageId.type === 'Literal'
? [messageId]
: utils.findPossibleVariableValues(messageId, scopeManager);
if (
values.length === 0 ||
values.some((val) => val.type !== 'Literal')
) {
shouldPerformUnusedCheck = false;
}
values.forEach((val) => {
messageIdsUsed.add(val.value);
});
}
}
},
};
},
};
65 changes: 65 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -762,4 +762,69 @@ module.exports = {
return [property];
});
},

getMessagesNode(ruleInfo, scopeManager) {
if (!ruleInfo) {
return;
}

const metaNode = ruleInfo.meta;
const messagesNode = module.exports
.evaluateObjectProperties(metaNode, scopeManager)
.find(
(p) =>
p.type === 'Property' && module.exports.getKeyName(p) === 'messages'
);

if (messagesNode) {
if (messagesNode.value.type === 'ObjectExpression') {
return messagesNode.value;
}
const value = findVariableValue(messagesNode.value, scopeManager);
if (value && value.type === 'ObjectExpression') {
return value;
}
}
},

getMessageIdNodes(ruleInfo, scopeManager) {
const messagesNode = module.exports.getMessagesNode(ruleInfo, scopeManager);

return messagesNode && messagesNode.type === 'ObjectExpression'
? module.exports.evaluateObjectProperties(messagesNode, scopeManager)
: undefined;
},

getMessageIdNodeById(messageId, ruleInfo, scopeManager) {
return module.exports
.getMessageIdNodes(ruleInfo, scopeManager)
.find(
(p) =>
p.type === 'Property' && module.exports.getKeyName(p) === messageId
);
},

/**
* Get the values (or functions) that a variable is initialized to.
* @param {Node} node - the Identifier node for the variable.
* @param {ScopeManager} scopeManager
* @returns the values (or functions) that the given variable is initialized to.
*/
findPossibleVariableValues(node, scopeManager) {
const variable = findVariable(
scopeManager.acquire(node) || scopeManager.globalScope,
node
);
return ((variable && variable.references) || []).flatMap((ref) => {
if (
ref.writeExpr &&
(ref.writeExpr.parent.type !== 'AssignmentExpression' ||
ref.writeExpr.parent.operator === '=')
) {
// Given node `x`, get `123` from `x = 123;`.
return [ref.writeExpr];
}
return [];
});
},
};

0 comments on commit d91d1a0

Please sign in to comment.