ESLint: Add custom rule 'correct-logger-context'

This rule ensures, that the correct context is given in any logger statements.

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-05-02 19:45:47 +02:00 committed by David Mehren
parent 375cb4eae9
commit 8cc9e12bc3
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
4 changed files with 66 additions and 1 deletions

View file

@ -33,7 +33,7 @@ module.exports = {
},
},
],
plugins: ['@typescript-eslint', 'jest'],
plugins: ['@typescript-eslint', 'jest', 'eslint-plugin-local-rules'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
@ -46,6 +46,7 @@ module.exports = {
jest: true,
},
rules: {
'local-rules/correct-logger-context': 'error',
'func-style': ['error', 'declaration'],
'@typescript-eslint/no-unused-vars': [
'warn',

58
eslint-local-rules.js Normal file
View file

@ -0,0 +1,58 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
'use strict';
const loggerFunctions = ['error', 'log', 'warn', 'debug', 'verbose'];
module.exports = {
'correct-logger-context': {
meta: {
fixable: 'code',
type: 'problem',
docs: {
recommended: true
},
schema: [],
},
create: function (context) {
return {
CallExpression: function (node) {
if (
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'MemberExpression' &&
node.callee.object.property.name === 'logger' &&
loggerFunctions.includes(node.callee.property.name) &&
!!node.arguments &&
node.arguments.length === 2
) {
const usedContext = node.arguments[1].value;
let correctContext = 'undefined';
const ancestors = context.getAncestors();
for (let index = ancestors.length - 1; index >= 0; index--) {
if (ancestors[index].type === 'MethodDefinition') {
correctContext = ancestors[index].key.name;
break;
}
}
if (usedContext !== correctContext) {
context.report({
node: node,
message: `Used wrong context in log statement`,
fix: function (fixer) {
return fixer.replaceText(
node.arguments[1],
`'${correctContext}'`,
);
},
});
}
}
},
};
},
},
};

View file

@ -45,6 +45,7 @@
"cli-color": "2.0.0",
"connect-typeorm": "1.1.4",
"eslint-plugin-jest": "24.3.6",
"eslint-plugin-local-rules": "1.1.0",
"file-type": "16.4.0",
"joi": "17.4.0",
"minio": "7.0.18",

View file

@ -2963,6 +2963,11 @@ eslint-plugin-jest@24.3.6:
dependencies:
"@typescript-eslint/experimental-utils" "^4.0.1"
eslint-plugin-local-rules@1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/eslint-plugin-local-rules/-/eslint-plugin-local-rules-1.1.0.tgz#5f934f685b08c96eed40b92aee7b02f03cf55f7b"
integrity sha512-FdPyzxakUKgZkeNM3x/vvRcB6nCjTNbui5gWALhvcaH1R6aCiD37fWtdesagcyBpEe9S9XRHAJ8CJ4rUJ3K9tQ==
eslint-scope@^5.0.0, eslint-scope@^5.1.1:
version "5.1.1"
resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c"