Bug 1431533: Part 4 - Add ESLint support for ChromeUtils import methods. r=florian
☠☠ backed out by c6e0fe339cb1 ☠ ☠
authorKris Maglione <maglione.k@gmail.com>
Thu, 18 Jan 2018 12:53:01 -0800
changeset 748706 e2674287e57fbf6835729f42b8491359c2c4bfd5
parent 748705 b0ac714075000b1a9d7c56977246a095b8734c08
child 748707 34c999fa006bffe8705cf50c54708aa21a962e62
push id97228
push usersfraser@mozilla.com
push dateTue, 30 Jan 2018 10:21:04 +0000
reviewersflorian
bugs1431533
milestone60.0a1
Bug 1431533: Part 4 - Add ESLint support for ChromeUtils import methods. r=florian This adds support for detecting globals created by these helpers, as well as a rule to enforce their use over the older XPConnect variants. The latter rule also supports fixing code to use the newer variants, and will be used in the next part to rewrite in-tree ESLint-enabled code that fails it. MozReview-Commit-ID: 6Bgo6ohQA5j
devtools/.eslintrc.js
tools/lint/docs/linters/eslint-plugin-mozilla.rst
tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js
tools/lint/eslint/eslint-plugin-mozilla/lib/helpers.js
tools/lint/eslint/eslint-plugin-mozilla/lib/index.js
tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-chromeutils-import.js
tools/lint/eslint/eslint-plugin-mozilla/tests/use-chromeutils-import.js
--- a/devtools/.eslintrc.js
+++ b/devtools/.eslintrc.js
@@ -22,16 +22,17 @@ module.exports = {
     "mozilla/no-single-arg-cu-import": "error",
     // See bug 1224289.
     "mozilla/reject-importGlobalProperties": "error",
     // devtools/shared/platform is special; see the README.md in that
     // directory for details.  We reject requires using explicit
     // subdirectories of this directory.
     "mozilla/reject-some-requires": ["error", "^devtools/shared/platform/(chome|content)/"],
     "mozilla/var-only-at-top-level": "error",
+    "mozilla/use-chromeutils-import": ["error", {allowCu: true}],
 
     // Rules from the React plugin
     "react/display-name": "error",
     "react/no-danger": "error",
     "react/no-did-mount-set-state": "error",
     "react/no-did-update-set-state": "error",
     "react/no-direct-mutation-state": "error",
     "react/no-unknown-property": "error",
--- a/tools/lint/docs/linters/eslint-plugin-mozilla.rst
+++ b/tools/lint/docs/linters/eslint-plugin-mozilla.rst
@@ -251,16 +251,23 @@ Treats top-level assignments like ``this
 Note: These are string matches so we will miss situations where the parent
 object is assigned to another variable e.g.:
 
 .. code-block:: js
 
    var b = gBrowser;
    b.content // Would not be detected as a CPOW.
 
+use-chromeutils-import
+----------------------
+
+Require use of ``ChromeUtils.import`` and ``ChromeUtils.defineModuleGetter``
+rather than ``Components.utils.import`` and
+``XPCOMUtils.defineLazyModuleGetter``.
+
 use-default-preference-values
 ---------------
 
 Require providing a second parameter to get*Pref methods instead of
 using a try/catch block.
 
 use-ownerGlobal
 ---------------
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js
+++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js
@@ -164,16 +164,17 @@ module.exports = {
     "max-nested-callbacks": ["error", 10],
 
     "mozilla/avoid-removeChild": "error",
     "mozilla/import-browser-window-globals": "error",
     "mozilla/import-globals": "error",
     "mozilla/no-import-into-var-and-global": "error",
     "mozilla/no-useless-parameters": "error",
     "mozilla/no-useless-removeEventListener": "error",
+    "mozilla/use-chromeutils-import": "error",
     "mozilla/use-default-preference-values": "error",
     "mozilla/use-ownerGlobal": "error",
     "mozilla/use-services": "error",
 
     // Always require parenthesis for new calls
     // "new-parens": "error",
 
     // Use [] instead of Array()
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/helpers.js
+++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/helpers.js
@@ -18,16 +18,17 @@ var directoryManifests = new Map();
 
 const callExpressionDefinitions = [
   /^loader\.lazyGetter\(this, "(\w+)"/,
   /^loader\.lazyImporter\(this, "(\w+)"/,
   /^loader\.lazyServiceGetter\(this, "(\w+)"/,
   /^loader\.lazyRequireGetter\(this, "(\w+)"/,
   /^XPCOMUtils\.defineLazyGetter\(this, "(\w+)"/,
   /^XPCOMUtils\.defineLazyModuleGetter\(this, "(\w+)"/,
+  /^ChromeUtils\.defineModuleGetter\(this, "(\w+)"/,
   /^XPCOMUtils\.defineLazyPreferenceGetter\(this, "(\w+)"/,
   /^XPCOMUtils\.defineLazyScriptGetter\(this, "(\w+)"/,
   /^XPCOMUtils\.defineLazyServiceGetter\(this, "(\w+)"/,
   /^XPCOMUtils\.defineConstant\(this, "(\w+)"/,
   /^DevToolsUtils\.defineLazyModuleGetter\(this, "(\w+)"/,
   /^DevToolsUtils\.defineLazyGetter\(this, "(\w+)"/,
   /^Object\.defineProperty\(this, "(\w+)"/,
   /^Reflect\.defineProperty\(this, "(\w+)"/,
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/index.js
+++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/index.js
@@ -52,16 +52,17 @@ module.exports = {
     "no-useless-parameters": require("../lib/rules/no-useless-parameters"),
     "no-useless-removeEventListener":
       require("../lib/rules/no-useless-removeEventListener"),
     "no-useless-run-test":
       require("../lib/rules/no-useless-run-test"),
     "reject-importGlobalProperties":
       require("../lib/rules/reject-importGlobalProperties"),
     "reject-some-requires": require("../lib/rules/reject-some-requires"),
+    "use-chromeutils-import": require("../lib/rules/use-chromeutils-import"),
     "use-default-preference-values":
       require("../lib/rules/use-default-preference-values"),
     "use-ownerGlobal": require("../lib/rules/use-ownerGlobal"),
     "use-services": require("../lib/rules/use-services"),
     "var-only-at-top-level": require("../lib/rules/var-only-at-top-level")
   },
   rulesConfig: {
     "avoid-Date-timing": "off",
@@ -78,14 +79,15 @@ module.exports = {
     "no-single-arg-cu-import": "off",
     "no-import-into-var-and-global": "off",
     "no-task": "off",
     "no-useless-parameters": "off",
     "no-useless-run-test": "off",
     "no-useless-removeEventListener": "off",
     "reject-importGlobalProperties": "off",
     "reject-some-requires": "off",
+    "use-chromeutils-import": "off",
     "use-default-preference-values": "off",
     "use-ownerGlobal": "off",
     "use-services": "off",
     "var-only-at-top-level": "off"
   }
 };
new file mode 100644
--- /dev/null
+++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-chromeutils-import.js
@@ -0,0 +1,79 @@
+/**
+ * @fileoverview Reject use of Cu.import and XPCOMUtils.defineLazyModuleGetter
+ *               in favor of ChromeUtils.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+"use strict";
+
+// -----------------------------------------------------------------------------
+// Rule Definition
+// -----------------------------------------------------------------------------
+
+function isIdentifier(node, id) {
+  return node && node.type === "Identifier" && node.name === id;
+}
+
+function isMemberExpression(node, object, member) {
+  return (node.type === "MemberExpression" &&
+          isIdentifier(node.object, object) &&
+          isIdentifier(node.property, member));
+}
+
+module.exports = {
+  meta: {
+    schema: [
+      {
+        "type": "object",
+        "properties": {
+          "allowCu": {
+            "type": "boolean"
+          }
+        },
+        "additionalProperties": false
+      }
+    ],
+    fixable: "code"
+  },
+
+  create(context) {
+    return {
+      "CallExpression": function(node) {
+        if (node.callee.type !== "MemberExpression") {
+          return;
+        }
+
+        let {allowCu} = context.options[0] || {};
+        let {callee} = node;
+
+        // Is the expression starting with `Cu` or `Components.utils`?
+        if (((!allowCu && isIdentifier(callee.object, "Cu")) ||
+             isMemberExpression(callee.object, "Components", "utils")) &&
+            isIdentifier(callee.property, "import")) {
+          context.report({
+            node,
+            message: "Please use ChromeUtils.import instead of Cu.import",
+            fix(fixer) {
+              return fixer.replaceText(callee, "ChromeUtils.import");
+            }
+          });
+        }
+
+        if (isMemberExpression(callee, "XPCOMUtils", "defineLazyModuleGetter") &&
+            node.arguments.length < 4) {
+          context.report({
+            node,
+            message: ("Please use ChromeUtils.defineModuleGetter instead of " +
+                      "XPCOMUtils.defineLazyModuleGetter"),
+            fix(fixer) {
+              return fixer.replaceText(callee, "ChromeUtils.defineModuleGetter");
+            }
+          });
+        }
+      }
+    };
+  }
+};
new file mode 100644
--- /dev/null
+++ b/tools/lint/eslint/eslint-plugin-mozilla/tests/use-chromeutils-import.js
@@ -0,0 +1,80 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// ------------------------------------------------------------------------------
+// Requirements
+// ------------------------------------------------------------------------------
+
+var rule = require("../lib/rules/use-chromeutils-import");
+var RuleTester = require("eslint/lib/testers/rule-tester");
+
+const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 6 } });
+
+// ------------------------------------------------------------------------------
+// Tests
+// ------------------------------------------------------------------------------
+
+function callError(message) {
+  return [{message, type: "CallExpression"}];
+}
+
+const MESSAGE_IMPORT = "Please use ChromeUtils.import instead of Cu.import";
+const MESSAGE_DEFINE = ("Please use ChromeUtils.defineModuleGetter instead of " +
+                        "XPCOMUtils.defineLazyModuleGetter");
+
+ruleTester.run("use-chromeutils-import", rule, {
+  valid: [
+    `ChromeUtils.import("resource://gre/modules/Service.jsm");`,
+    `ChromeUtils.import("resource://gre/modules/Service.jsm", this);`,
+    `ChromeUtils.defineModuleGetter(this, "Services",
+                                    "resource://gre/modules/Service.jsm");`,
+    `XPCOMUtils.defineLazyModuleGetter(this, "Services",
+                                       "resource://gre/modules/Service.jsm",
+                                       "Foo");`,
+    `XPCOMUtils.defineLazyModuleGetter(this, "Services",
+                                       "resource://gre/modules/Service.jsm",
+                                       undefined, preServicesLambda);`,
+    {
+      options: [{allowCu: true}],
+      code: `Cu.import("resource://gre/modules/Service.jsm");`
+    }
+  ],
+  invalid: [
+    {
+      code: `Cu.import("resource://gre/modules/Services.jsm");`,
+      output: `ChromeUtils.import("resource://gre/modules/Services.jsm");`,
+      errors: callError(MESSAGE_IMPORT)
+    },
+    {
+      code: `Cu.import("resource://gre/modules/Services.jsm", this);`,
+      output: `ChromeUtils.import("resource://gre/modules/Services.jsm", this);`,
+      errors: callError(MESSAGE_IMPORT)
+    },
+    {
+      code: `Components.utils.import("resource://gre/modules/Services.jsm");`,
+      output: `ChromeUtils.import("resource://gre/modules/Services.jsm");`,
+      errors: callError(MESSAGE_IMPORT)
+    },
+    {
+      code: `Components.utils.import("resource://gre/modules/Services.jsm");`,
+      output: `ChromeUtils.import("resource://gre/modules/Services.jsm");`,
+      errors: callError(MESSAGE_IMPORT)
+    },
+    {
+      options: [{allowCu: true}],
+      code: `Components.utils.import("resource://gre/modules/Services.jsm", this);`,
+      output: `ChromeUtils.import("resource://gre/modules/Services.jsm", this);`,
+      errors: callError(MESSAGE_IMPORT)
+    },
+    {
+      code: `XPCOMUtils.defineLazyModuleGetter(this, "Services",
+                                               "resource://gre/modules/Services.jsm");`,
+      output: `ChromeUtils.defineModuleGetter(this, "Services",
+                                               "resource://gre/modules/Services.jsm");`,
+      errors: callError(MESSAGE_DEFINE)
+    }
+  ]
+});
+