use-default-preference-values.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * @fileoverview Require providing a second parameter to get*Pref
  3. * methods instead of using a try/catch block.
  4. *
  5. * This Source Code Form is subject to the terms of the Mozilla Public
  6. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. */
  9. "use strict";
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. url:
  14. "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/use-default-preference-values.html",
  15. },
  16. type: "suggestion",
  17. },
  18. create(context) {
  19. return {
  20. TryStatement(node) {
  21. let types = ["Bool", "Char", "Float", "Int"];
  22. let methods = types.map(type => "get" + type + "Pref");
  23. if (
  24. node.block.type != "BlockStatement" ||
  25. node.block.body.length != 1
  26. ) {
  27. return;
  28. }
  29. let firstStm = node.block.body[0];
  30. if (
  31. firstStm.type != "ExpressionStatement" ||
  32. firstStm.expression.type != "AssignmentExpression" ||
  33. firstStm.expression.right.type != "CallExpression" ||
  34. firstStm.expression.right.callee.type != "MemberExpression" ||
  35. firstStm.expression.right.callee.property.type != "Identifier" ||
  36. !methods.includes(firstStm.expression.right.callee.property.name)
  37. ) {
  38. return;
  39. }
  40. let msg = "provide a default value instead of using a try/catch block";
  41. context.report(node, msg);
  42. },
  43. };
  44. },
  45. };