no-inline-comments.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * @fileoverview Enforces or disallows inline comments.
  3. * @author Greg Cochard
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "disallow inline comments after code",
  15. category: "Stylistic Issues",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/no-inline-comments"
  18. },
  19. schema: []
  20. },
  21. create(context) {
  22. const sourceCode = context.getSourceCode();
  23. /**
  24. * Will check that comments are not on lines starting with or ending with code
  25. * @param {ASTNode} node The comment node to check
  26. * @private
  27. * @returns {void}
  28. */
  29. function testCodeAroundComment(node) {
  30. const startLine = String(sourceCode.lines[node.loc.start.line - 1]),
  31. endLine = String(sourceCode.lines[node.loc.end.line - 1]),
  32. preamble = startLine.slice(0, node.loc.start.column).trim(),
  33. postamble = endLine.slice(node.loc.end.column).trim(),
  34. isPreambleEmpty = !preamble,
  35. isPostambleEmpty = !postamble;
  36. // Nothing on both sides
  37. if (isPreambleEmpty && isPostambleEmpty) {
  38. return;
  39. }
  40. // JSX Exception
  41. if (
  42. (isPreambleEmpty || preamble === "{") &&
  43. (isPostambleEmpty || postamble === "}")
  44. ) {
  45. const enclosingNode = sourceCode.getNodeByRangeIndex(node.range[0]);
  46. if (enclosingNode && enclosingNode.type === "JSXEmptyExpression") {
  47. return;
  48. }
  49. }
  50. // Don't report ESLint directive comments
  51. if (astUtils.isDirectiveComment(node)) {
  52. return;
  53. }
  54. context.report({ node, message: "Unexpected comment inline with code." });
  55. }
  56. //--------------------------------------------------------------------------
  57. // Public
  58. //--------------------------------------------------------------------------
  59. return {
  60. Program() {
  61. const comments = sourceCode.getAllComments();
  62. comments.filter(token => token.type !== "Shebang").forEach(testCodeAroundComment);
  63. }
  64. };
  65. }
  66. };