consistent-if-bracing.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * @fileoverview checks if/else if/else bracing is consistent
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7. */
  8. "use strict";
  9. module.exports = {
  10. meta: {
  11. docs: {
  12. url:
  13. "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/consistent-if-bracing.html",
  14. },
  15. messages: {
  16. consistentIfBracing: "Bracing of if..else bodies should be consistent.",
  17. },
  18. type: "layout",
  19. },
  20. create(context) {
  21. return {
  22. IfStatement(node) {
  23. if (node.parent.type !== "IfStatement") {
  24. let types = new Set();
  25. for (
  26. let currentNode = node;
  27. currentNode;
  28. currentNode = currentNode.alternate
  29. ) {
  30. let type = currentNode.consequent.type;
  31. types.add(type == "BlockStatement" ? "Block" : "NotBlock");
  32. if (
  33. currentNode.alternate &&
  34. currentNode.alternate.type !== "IfStatement"
  35. ) {
  36. type = currentNode.alternate.type;
  37. types.add(type == "BlockStatement" ? "Block" : "NotBlock");
  38. break;
  39. }
  40. }
  41. if (types.size > 1) {
  42. context.report({
  43. node,
  44. messageId: "consistentIfBracing",
  45. });
  46. }
  47. }
  48. },
  49. };
  50. },
  51. };