github-pages-deploy-action/node_modules/eslint/lib/rules/no-undef-init.js

76 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2020-03-07 11:45:40 +08:00
/**
* @fileoverview Rule to flag when initializing to undefined
* @author Ilya Volodin
*/
"use strict";
2020-03-31 20:40:00 +08:00
const astUtils = require("./utils/ast-utils");
2020-03-07 11:45:40 +08:00
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "disallow initializing variables to `undefined`",
category: "Variables",
recommended: false,
url: "https://eslint.org/docs/rules/no-undef-init"
},
schema: [],
2020-05-15 05:33:08 +08:00
fixable: "code",
messages: {
unnecessaryUndefinedInit: "It's not necessary to initialize '{{name}}' to undefined."
}
2020-03-07 11:45:40 +08:00
},
create(context) {
const sourceCode = context.getSourceCode();
return {
VariableDeclarator(node) {
const name = sourceCode.getText(node.id),
init = node.init && node.init.name,
scope = context.getScope(),
undefinedVar = astUtils.getVariableByName(scope, "undefined"),
2020-03-31 20:40:00 +08:00
shadowed = undefinedVar && undefinedVar.defs.length > 0,
lastToken = sourceCode.getLastToken(node);
2020-03-07 11:45:40 +08:00
if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
context.report({
node,
2020-05-15 05:33:08 +08:00
messageId: "unnecessaryUndefinedInit",
2020-03-07 11:45:40 +08:00
data: { name },
fix(fixer) {
if (node.parent.kind === "var") {
return null;
}
if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {
// Don't fix destructuring assignment to `undefined`.
return null;
}
2020-03-31 20:40:00 +08:00
if (sourceCode.commentsExistBetween(node.id, lastToken)) {
return null;
}
2020-03-07 11:45:40 +08:00
return fixer.removeRange([node.id.range[1], node.range[1]]);
}
});
}
}
};
}
};