JS: Add hasComment and getComments (#9742)

This commit is contained in:
fisker Cheung authored and GitHub committed 2020-11-25 22:14:27 +08:00
1 parent 125492818c
commit d8e40cd978
25 files changed
+335 -212

No files matched your search

@@ -4,6 +4,7 @@ module.exports = {
rules: {
"better-parent-property-check-in-needs-parens": require("./better-parent-property-check-in-needs-parens"),
"directly-loc-start-end": require("./directly-loc-start-end"),
"no-node-comments": require("./no-node-comments"),
"prefer-fast-path-each": require("./prefer-fast-path-each"),
"require-json-extensions": require("./require-json-extensions"),
},
@@ -0,0 +1,85 @@
"use strict";
const path = require("path");
// `node.comments`
const memberExpressionSelector = [
"MemberExpression[computed=false]",
"",
">",
"Identifier.property",
'[name="comments"]',
].join("");
// `const {comments} = node`
// `const {comments: nodeComments} = node`
const objectPatternSelector = [
"ObjectPattern",
">",
"Property.properties",
">",
"Identifier.key",
'[name="comments"]',
].join("");
const selector = `:matches(${memberExpressionSelector}, ${objectPatternSelector})`;
const messageId = "no-node-comments";
module.exports = {
meta: {
type: "suggestion",
docs: {
url:
"https://github.com/prettier/prettier/blob/master/scripts/eslint-plugin-prettier-internal-rules/no-node-comments.js",
},
messages: {
[messageId]: "Do not access node.comments.",
},
},
create(context) {
const fileName = context.getFilename();
const ignored = new Map(
context.options.map((option) => {
if (typeof option === "string") {
option = { file: option };
}
const { file, functions } = option;
return [
path.join(__dirname, "../../..", file),
functions ? new Set(functions) : true,
];
})
);
return {
[selector](node) {
if (ignored.has(fileName)) {
const functionNames = ignored.get(fileName);
if (functionNames === true) {
return;
}
let isIgnored;
let currentNode = node.parent;
while (currentNode) {
if (
currentNode.type === "FunctionDeclaration" &&
currentNode.id &&
currentNode.id.type === "Identifier" &&
functionNames.has(currentNode.id.name)
) {
isIgnored = true;
break;
}
currentNode = currentNode.parent;
}
if (isIgnored) {
return;
}
}
context.report({
node,
messageId,
});
},
};
},
};