Bug 1358648 part 2 - Remove util.js Svc.{DefaultPrefs,Session,Idle, FormHistory} and Str. r?markh draft
authorEdouard Oger <eoger@fastmail.com>
Tue, 02 May 2017 18:30:23 -0400
changeset 571620 12e90c0e480e87428a54cd2c9b7b8ba48ee29191
parent 571619 c7e4fbfdae788cd8489c1ebff756d78a86654ff8
child 571621 e447799a6557d840e6132e65e6e305d30943c6f4
push id56865
push userbmo:eoger@fastmail.com
push dateWed, 03 May 2017 01:41:16 +0000
reviewersmarkh
bugs1358648
milestone55.0a1
Bug 1358648 part 2 - Remove util.js Svc.{DefaultPrefs,Session,Idle, FormHistory} and Str. r?markh MozReview-Commit-ID: Jc1th8Snvhv
services/sync/modules/engines/forms.js
services/sync/modules/engines/tabs.js
services/sync/modules/policies.js
services/sync/modules/util.js
services/sync/tests/unit/test_corrupt_keys.js
services/sync/tests/unit/test_interval_triggers.js
services/sync/tests/unit/test_service_detect_upgrade.js
services/sync/tests/unit/test_service_wipeServer.js
services/sync/tests/unit/test_utils_getErrorString.js
services/sync/tests/unit/xpcshell.ini
tools/lint/eslint/modules.json
--- a/services/sync/modules/engines/forms.js
+++ b/services/sync/modules/engines/forms.js
@@ -11,16 +11,18 @@ var Cu = Components.utils;
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://services-sync/engines.js");
 Cu.import("resource://services-sync/record.js");
 Cu.import("resource://services-common/async.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/collection_validator.js");
 Cu.import("resource://gre/modules/Log.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "FormHistory",
+                                  "resource://gre/modules/FormHistory.jsm");
 
 const FORMS_TTL = 3 * 365 * 24 * 60 * 60;   // Three years in seconds.
 
 this.FormRec = function FormRec(collection, id) {
   CryptoWrapper.call(this, collection, id);
 }
 FormRec.prototype = {
   __proto__: CryptoWrapper.prototype,
@@ -43,36 +45,36 @@ var FormWrapper = {
       let callbacks = {
         handleResult(result) {
           results.push(result);
         },
         handleCompletion(reason) {
           resolve(results);
         }
       };
-      Svc.FormHistory.search(terms, searchData, callbacks);
+      FormHistory.search(terms, searchData, callbacks);
     })
   },
 
   // Do a "sync" search by spinning the event loop until it completes.
   _searchSpinningly(terms, searchData) {
     return Async.promiseSpinningly(this._promiseSearch(terms, searchData));
   },
 
   _updateSpinningly(changes) {
-    if (!Svc.FormHistory.enabled) {
+    if (!FormHistory.enabled) {
       return; // update isn't going to do anything.
     }
     let cb = Async.makeSpinningCallback();
     let callbacks = {
       handleCompletion(reason) {
         cb();
       }
     };
-    Svc.FormHistory.update(changes, callbacks);
+    FormHistory.update(changes, callbacks);
     cb.wait();
   },
 
   getEntry(guid) {
     let results = this._searchSpinningly(this._getEntryCols, {guid});
     if (!results.length) {
       return null;
     }
--- a/services/sync/modules/engines/tabs.js
+++ b/services/sync/modules/engines/tabs.js
@@ -12,16 +12,18 @@ const TAB_ENTRIES_LIMIT = 5;      // How
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://services-sync/engines.js");
 Cu.import("resource://services-sync/record.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://services-sync/constants.js");
 
 XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
   "resource://gre/modules/PrivateBrowsingUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "SessionStore",
+  "resource:///modules/sessionstore/SessionStore.jsm");
 
 this.TabSetRecord = function TabSetRecord(collection, id) {
   CryptoWrapper.call(this, collection, id);
 }
 TabSetRecord.prototype = {
   __proto__: CryptoWrapper.prototype,
   _logName: "Sync.Record.Tabs",
   ttl: TABS_TTL,
@@ -122,17 +124,17 @@ TabStore.prototype = {
   },
 
   shouldSkipWindow(win) {
     return win.closed ||
            PrivateBrowsingUtils.isWindowPrivate(win);
   },
 
   getTabState(tab) {
-    return JSON.parse(Svc.Session.getTabState(tab));
+    return JSON.parse(SessionStore.getTabState(tab));
   },
 
   getAllTabs(filter) {
     let filteredUrls = new RegExp(Svc.Prefs.get("engine.tabs.filteredUrls"), "i");
 
     let allTabs = [];
 
     let winEnum = this.getWindowEnumerator();
--- a/services/sync/modules/policies.js
+++ b/services/sync/modules/policies.js
@@ -14,16 +14,19 @@ Cu.import("resource://services-sync/cons
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://services-common/logmanager.js");
 Cu.import("resource://services-common/async.js");
 
 XPCOMUtils.defineLazyModuleGetter(this, "Status",
                                   "resource://services-sync/status.js");
 XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
                                   "resource://gre/modules/AddonManager.jsm");
+XPCOMUtils.defineLazyServiceGetter(this, "IdleService",
+                                   "@mozilla.org/widget/idleservice;1",
+                                   "nsIIdleService");
 
 // Get the value for an interval that's stored in preferences. To save users
 // from themselves (and us from them!) the minimum time they can specify
 // is 60s.
 function getThrottledIntervalPreference(prefName) {
   return Math.max(Svc.Prefs.get(prefName), 60) * 1000;
 }
 
@@ -121,17 +124,17 @@ SyncScheduler.prototype = {
     Svc.Obs.add("weave:service:ready", this);
     Svc.Obs.add("weave:engine:sync:applied", this);
     Svc.Obs.add("weave:service:setup-complete", this);
     Svc.Obs.add("weave:service:start-over", this);
     Svc.Obs.add("FxA:hawk:backoff:interval", this);
 
     if (Status.checkSetup() == STATUS_OK) {
       Svc.Obs.add("wake_notification", this);
-      Svc.Idle.addIdleObserver(this, Svc.Prefs.get("scheduler.idleTime"));
+      IdleService.addIdleObserver(this, Svc.Prefs.get("scheduler.idleTime"));
     }
   },
 
   observe: function observe(subject, topic, data) {
     this._log.trace("Handling " + topic);
     switch (topic) {
       case "weave:engine:score:updated":
         if (Status.login == LOGIN_SUCCEEDED) {
@@ -239,23 +242,23 @@ SyncScheduler.prototype = {
           this.hasIncomingItems = true;
         }
         if (subject.newFailed) {
           this._log.error(`Engine ${data} found ${subject.newFailed} new records that failed to apply`);
         }
         break;
       case "weave:service:setup-complete":
          Services.prefs.savePrefFile(null);
-         Svc.Idle.addIdleObserver(this, Svc.Prefs.get("scheduler.idleTime"));
+         IdleService.addIdleObserver(this, Svc.Prefs.get("scheduler.idleTime"));
          Svc.Obs.add("wake_notification", this);
          break;
       case "weave:service:start-over":
          this.setDefaults();
          try {
-           Svc.Idle.removeIdleObserver(this, Svc.Prefs.get("scheduler.idleTime"));
+           IdleService.removeIdleObserver(this, Svc.Prefs.get("scheduler.idleTime"));
          } catch (ex) {
            if (ex.result != Cr.NS_ERROR_FAILURE) {
              throw ex;
            }
            // In all likelihood we didn't have an idle observer registered yet.
            // It's all good.
          }
          break;
--- a/services/sync/modules/util.js
+++ b/services/sync/modules/util.js
@@ -1,13 +1,13 @@
 /* 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/. */
 
-this.EXPORTED_SYMBOLS = ["XPCOMUtils", "Services", "Utils", "Async", "Svc", "Str"];
+this.EXPORTED_SYMBOLS = ["XPCOMUtils", "Services", "Utils", "Async", "Svc"];
 
 var {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
 
 Cu.import("resource://services-common/observers.js");
 Cu.import("resource://services-common/utils.js");
 Cu.import("resource://services-common/async.js", this);
 Cu.import("resource://services-crypto/utils.js");
 Cu.import("resource://services-sync/constants.js");
@@ -210,21 +210,16 @@ this.Utils = {
     // Create a setter if it doesn't exist yet
     if (!prot.__lookupSetter__(prop)) {
       prot.__defineSetter__(prop, function(val) {
         this[defer][prop] = val;
       });
     }
   },
 
-  lazyStrings: function Weave_lazyStrings(name) {
-    return () => Services.strings.createBundle(
-      `chrome://weave/locale/${name}.properties`);
-  },
-
   deepEquals: function eq(a, b) {
     // If they're triple equals, then it must be equals!
     if (a === b)
       return true;
 
     // If they weren't equal, they must be objects to be different
     if (typeof a != "object" || typeof b != "object")
       return false;
@@ -452,29 +447,16 @@ this.Utils = {
     let path = OS.Path.join(OS.Constants.Path.profileDir, "weave",
                             ...(filePath + ".json").split("/"));
     if (that._log) {
       that._log.trace("Deleting " + path);
     }
     return OS.File.remove(path, { ignoreAbsent: true });
   },
 
-  getErrorString: function Utils_getErrorString(error, args) {
-    try {
-      if (args) {
-        return Str.errors.formatStringFromName(error, args, args.length);
-      }
-      return Str.errors.GetStringFromName(error);
-
-    } catch (e) {}
-
-    // basically returns "Unknown Error"
-    return Str.errors.GetStringFromName("error.reason.unknown");
-  },
-
   /**
    * Generate 26 characters.
    */
   generatePassphrase: function generatePassphrase() {
     // Note that this is a different base32 alphabet to the one we use for
     // other tasks. It's lowercase, uses different letters, and needs to be
     // decoded with decodeKeyBase32, not just decodeBase32.
     return Utils.encodeKeyBase32(CryptoUtils.generateRandomBytes(16));
@@ -684,32 +666,26 @@ this.Utils = {
     if (user == "%USERNAME%" && env.get("USERNAME")) {
       user = env.get("USERNAME");
     }
 
     let brand = Services.strings.createBundle(
       "chrome://branding/locale/brand.properties");
     let brandName = brand.GetStringFromName("brandShortName");
 
-    let appName;
-    try {
-      let syncStrings = Services.strings.createBundle("chrome://browser/locale/sync.properties");
-      appName = syncStrings.formatStringFromName("sync.defaultAccountApplication", [brandName], 1);
-    } catch (ex) {}
-    appName = appName || brandName;
-
     let system =
       // 'device' is defined on unix systems
       Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2).get("device") ||
       // hostname of the system, usually assigned by the user or admin
       Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2).get("host") ||
       // fall back on ua info string
       Cc["@mozilla.org/network/protocol;1?name=http"].getService(Ci.nsIHttpProtocolHandler).oscpu;
 
-    return Str.sync.formatStringFromName("client.name2", [user, appName, system], 3);
+    let syncStrings = Services.strings.createBundle("chrome://weave/locale/sync.properties");
+    return syncStrings.formatStringFromName("client.name2", [user, brandName, system], 3);
   },
 
   getDeviceName() {
     const deviceName = Svc.Prefs.get("client.name", "");
 
     if (deviceName === "") {
       return this.getDefaultDeviceName();
     }
@@ -741,42 +717,23 @@ XPCOMUtils.defineLazyGetter(Utils, "_utf
   return converter;
 });
 
 /*
  * Commonly-used services
  */
 this.Svc = {};
 Svc.Prefs = new Preferences(PREFS_BRANCH);
-Svc.DefaultPrefs = new Preferences({branch: PREFS_BRANCH, defaultBranch: true});
 Svc.Obs = Observers;
 
-var _sessionCID = Services.appinfo.ID == SEAMONKEY_ID ?
-  "@mozilla.org/suite/sessionstore;1" :
-  "@mozilla.org/browser/sessionstore;1";
-
-[
- ["Idle", "@mozilla.org/widget/idleservice;1", "nsIIdleService"],
- ["Session", _sessionCID, "nsISessionStore"]
-].forEach(function([name, contract, iface]) {
-  XPCOMUtils.defineLazyServiceGetter(Svc, name, contract, iface);
-});
-
-XPCOMUtils.defineLazyModuleGetter(Svc, "FormHistory", "resource://gre/modules/FormHistory.jsm");
-
 Svc.__defineGetter__("Crypto", function() {
   let cryptoSvc;
   let ns = {};
   Cu.import("resource://services-crypto/WeaveCrypto.js", ns);
   cryptoSvc = new ns.WeaveCrypto();
   delete Svc.Crypto;
   return Svc.Crypto = cryptoSvc;
 });
 
-this.Str = {};
-["errors", "sync"].forEach(function(lazy) {
-  XPCOMUtils.defineLazyGetter(Str, lazy, Utils.lazyStrings(lazy));
-});
-
 Svc.Obs.add("xpcom-shutdown", function() {
   for (let name in Svc)
     delete Svc[name];
 });
--- a/services/sync/tests/unit/test_corrupt_keys.js
+++ b/services/sync/tests/unit/test_corrupt_keys.js
@@ -32,31 +32,16 @@ add_task(async function test_locally_cha
     meta: {},
     crypto: {},
     clients: {}
   });
   server.start();
 
   try {
     Svc.Prefs.set("registerEngines", "Tab");
-    _("Set up some tabs.");
-    let myTabs =
-      {windows: [{tabs: [{index: 1,
-                          entries: [{
-                            url: "http://foo.com/",
-                            title: "Title"
-                          }],
-                          attributes: {
-                            image: "image"
-                          }
-                          }]}]};
-    delete Svc.Session;
-    Svc.Session = {
-      getBrowserState: () => JSON.stringify(myTabs)
-    };
 
     await configureIdentity({ username: "johndoe" }, server);
     // We aren't doing a .login yet, so fudge the cluster URL.
     Service.clusterURL = Service.identity._token.endpoint;
 
     Service.engineManager.register(HistoryEngine);
     Service.engineManager.unregister("addons");
 
--- a/services/sync/tests/unit/test_interval_triggers.js
+++ b/services/sync/tests/unit/test_interval_triggers.js
@@ -2,17 +2,17 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/engines.js");
 Cu.import("resource://services-sync/engines/clients.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://testing-common/services/sync/utils.js");
 
-Svc.DefaultPrefs.set("registerEngines", "");
+Svc.Prefs.set("registerEngines", "");
 Cu.import("resource://services-sync/service.js");
 
 var scheduler = Service.scheduler;
 var clientsEngine = Service.clientsEngine;
 
 // Don't remove stale clients when syncing. This is a test-only workaround
 // that lets us add clients directly to the store, without losing them on
 // the next sync.
--- a/services/sync/tests/unit/test_service_detect_upgrade.js
+++ b/services/sync/tests/unit/test_service_detect_upgrade.js
@@ -40,32 +40,16 @@ add_task(async function v4_upgrade() {
     "/1.1/johndoe/storage/forms": new ServerCollection().handler(),
     "/1.1/johndoe/storage/history": new ServerCollection().handler(),
     "/1.1/johndoe/storage/passwords": new ServerCollection().handler(),
     "/1.1/johndoe/storage/prefs": new ServerCollection().handler()
   });
 
   try {
 
-    _("Set up some tabs.");
-    let myTabs =
-      {windows: [{tabs: [{index: 1,
-                          entries: [{
-                            url: "http://foo.com/",
-                            title: "Title"
-                          }],
-                          attributes: {
-                            image: "image"
-                          }
-                          }]}]};
-    delete Svc.Session;
-    Svc.Session = {
-      getBrowserState: () => JSON.stringify(myTabs)
-    };
-
     Service.status.resetSync();
 
     _("Logging in.");
 
     await configureIdentity({ "username": "johndoe" }, server);
 
     Service.login();
     do_check_true(Service.isLoggedIn);
@@ -206,33 +190,16 @@ add_task(async function v5_upgrade() {
     "/1.1/johndoe/storage/crypto/bulk": upd("crypto", bulkWBO.handler()),
 
     // Track modified times.
     "/1.1/johndoe/storage/clients": upd("clients", clients.handler()),
     "/1.1/johndoe/storage/tabs": upd("tabs", new ServerCollection().handler()),
   });
 
   try {
-
-    _("Set up some tabs.");
-    let myTabs =
-      {windows: [{tabs: [{index: 1,
-                          entries: [{
-                            url: "http://foo.com/",
-                            title: "Title"
-                          }],
-                          attributes: {
-                            image: "image"
-                          }
-                          }]}]};
-    delete Svc.Session;
-    Svc.Session = {
-      getBrowserState: () => JSON.stringify(myTabs)
-    };
-
     Service.status.resetSync();
 
     Service.clusterURL = server.baseURI + "/";
 
     await configureIdentity({ "username": "johndoe" }, server);
 
     // Test an upgrade where the contents of the server would cause us to error
     // -- keys decrypted with a different sync key, for example.
--- a/services/sync/tests/unit/test_service_wipeServer.js
+++ b/services/sync/tests/unit/test_service_wipeServer.js
@@ -1,15 +1,15 @@
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://services-sync/record.js");
 Cu.import("resource://services-sync/resource.js");
 Cu.import("resource://testing-common/services/sync/fakeservices.js");
 Cu.import("resource://testing-common/services/sync/utils.js");
 
-Svc.DefaultPrefs.set("registerEngines", "");
+Svc.Prefs.set("registerEngines", "");
 Cu.import("resource://services-sync/service.js");
 
 // configure the identity we use for this test.
 const identityConfig = makeIdentityConfig({username: "johndoe"});
 
 function FakeCollection() {
   this.deleted = false;
 }
deleted file mode 100644
--- a/services/sync/tests/unit/test_utils_getErrorString.js
+++ /dev/null
@@ -1,14 +0,0 @@
-Cu.import("resource://services-sync/util.js");
-
-function run_test() {
-  let str;
-
-  // we just test whether the returned string includes the
-  // string "unknown", should be good enough
-
-  str = Utils.getErrorString("error.login.reason.account");
-  do_check_true(str.match(/unknown/i) == null);
-
-  str = Utils.getErrorString("foobar");
-  do_check_true(str.match(/unknown/i) != null);
-}
--- a/services/sync/tests/unit/xpcshell.ini
+++ b/services/sync/tests/unit/xpcshell.ini
@@ -23,17 +23,16 @@ support-files =
 [test_load_modules.js]
 
 # util contains a bunch of functionality used throughout.
 [test_utils_catch.js]
 [test_utils_deepEquals.js]
 [test_utils_deferGetSet.js]
 [test_utils_deriveKey.js]
 [test_utils_keyEncoding.js]
-[test_utils_getErrorString.js]
 [test_utils_json.js]
 [test_utils_lock.js]
 [test_utils_makeGUID.js]
 [test_utils_notify.js]
 [test_utils_passphrase.js]
 
 # We have a number of other libraries that are pretty much standalone.
 [test_addon_utils.js]
--- a/tools/lint/eslint/modules.json
+++ b/tools/lint/eslint/modules.json
@@ -219,17 +219,17 @@
   "test_bug883784.jsm": ["Test"],
   "Timer.jsm": ["setTimeout", "clearTimeout", "setInterval", "clearInterval"],
   "tokenserverclient.js": ["TokenServerClient", "TokenServerClientError", "TokenServerClientNetworkError", "TokenServerClientServerError"],
   "ToolboxProcess.jsm": ["BrowserToolboxProcess"],
   "tps.jsm": ["ACTIONS", "TPS"],
   "Translation.jsm": ["Translation", "TranslationTelemetry"],
   "Traversal.jsm": ["TraversalRules", "TraversalHelper"],
   "UpdateTelemetry.jsm": ["AUSTLMY"],
-  "util.js": ["getChromeWindow", "XPCOMUtils", "Services", "Utils", "Async", "Svc", "Str"],
+  "util.js": ["getChromeWindow", "XPCOMUtils", "Services", "Utils", "Async", "Svc"],
   "utils.js": ["applicationName", "assert", "Copy", "getBrowserObject", "getChromeWindow", "getWindows", "getWindowByTitle", "getWindowByType", "getWindowId", "getMethodInWindows", "getPreference", "saveDataURL", "setPreference", "sleep", "startTimer", "stopTimer", "takeScreenshot", "unwrapNode", "waitFor", "btoa", "encryptPayload", "makeIdentityConfig", "makeFxAccountsInternalMock", "configureFxAccountIdentity", "configureIdentity", "SyncTestingInfrastructure", "waitForZeroTimer", "Promise", "MockFxaStorageManager", "AccountState", "sumHistogram", "CommonUtils", "CryptoUtils", "TestingUtils", "promiseZeroTimer", "promiseNamedTimer"],
   "Utils.jsm": ["Utils", "Logger", "PivotContext", "PrefCache"],
   "VariablesView.jsm": ["VariablesView", "escapeHTML"],
   "VariablesViewController.jsm": ["VariablesViewController", "StackFrameUtils"],
   "version.jsm": ["VERSION"],
   "vtt.jsm": ["WebVTT"],
   "WebChannel.jsm": ["WebChannel", "WebChannelBroker"],
   "WindowDraggingUtils.jsm": ["WindowDraggingElement"],