use-chromeutils-import.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * @fileoverview Reject use of Cu.import and XPCOMUtils.defineLazyModuleGetter
  3. * in favor of ChromeUtils.
  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. function isIdentifier(node, id) {
  11. return node && node.type === "Identifier" && node.name === id;
  12. }
  13. function isMemberExpression(node, object, member) {
  14. return (
  15. node.type === "MemberExpression" &&
  16. isIdentifier(node.object, object) &&
  17. isIdentifier(node.property, member)
  18. );
  19. }
  20. module.exports = {
  21. meta: {
  22. docs: {
  23. url:
  24. "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/use-chromeutils-import.html",
  25. },
  26. fixable: "code",
  27. type: "suggestion",
  28. },
  29. create(context) {
  30. return {
  31. CallExpression(node) {
  32. if (node.callee.type !== "MemberExpression") {
  33. return;
  34. }
  35. let { callee } = node;
  36. // Is the expression starting with `Cu` or `Components.utils`?
  37. if (
  38. (isIdentifier(callee.object, "Cu") ||
  39. isMemberExpression(callee.object, "Components", "utils")) &&
  40. isIdentifier(callee.property, "import")
  41. ) {
  42. context.report({
  43. node,
  44. message: "Please use ChromeUtils.import instead of Cu.import",
  45. fix(fixer) {
  46. return fixer.replaceText(callee, "ChromeUtils.import");
  47. },
  48. });
  49. }
  50. if (
  51. isMemberExpression(callee, "XPCOMUtils", "defineLazyModuleGetter") &&
  52. node.arguments.length < 4
  53. ) {
  54. context.report({
  55. node,
  56. message:
  57. "Please use ChromeUtils.defineModuleGetter instead of " +
  58. "XPCOMUtils.defineLazyModuleGetter",
  59. fix(fixer) {
  60. return fixer.replaceText(
  61. callee,
  62. "ChromeUtils.defineModuleGetter"
  63. );
  64. },
  65. });
  66. }
  67. },
  68. };
  69. },
  70. };