Bug 701967 - Misc code cleanup in Sync's util.js; r=gps
☠☠ backed out by e8b6b6b810ee ☠ ☠
authorPallani Kumaran <pallanikumaran@gmail.com>
Tue, 13 Mar 2012 02:12:47 +0800
changeset 94014 eb4233025be0571347082eb091f825f9e0753fbd
parent 94013 383da99956e6d5a8ae31f9b1e1beedae4d1d6509
child 94015 e8b6b6b810ee2914fcdb694798ad1c81955dad72
push id886
push userlsblakk@mozilla.com
push dateMon, 04 Jun 2012 19:57:52 +0000
treeherdermozilla-beta@bbd8d5efd6d1 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersgps
bugs701967
milestone14.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 701967 - Misc code cleanup in Sync's util.js; r=gps
services/sync/modules/record.js
services/sync/modules/util.js
services/sync/tests/unit/head_helpers.js
services/sync/tests/unit/test_bookmark_livemarks.js
services/sync/tests/unit/test_resource.js
services/sync/tests/unit/test_resource_async.js
services/sync/tests/unit/test_tab_store.js
services/sync/tests/unit/test_utils_deepCopy.js
services/sync/tests/unit/test_utils_json.js
services/sync/tests/unit/test_utils_makeURI.js
--- a/services/sync/modules/record.js
+++ b/services/sync/modules/record.js
@@ -83,18 +83,21 @@ WBORecord.prototype = {
 
   upload: function upload(uri) {
     return new Resource(uri).put(this);
   },
 
   // Take a base URI string, with trailing slash, and return the URI of this
   // WBO based on collection and ID.
   uri: function(base) {
-    if (this.collection && this.id)
-      return Utils.makeURL(base + this.collection + "/" + this.id);
+    if (this.collection && this.id) {
+      let url = Utils.makeURI(base + this.collection + "/" + this.id);
+      url.QueryInterface(Ci.nsIURL);
+      return url;
+    }
     return null;
   },
 
   deserialize: function deserialize(json) {
     this.data = json.constructor.toString() == String ? JSON.parse(json) : json;
 
     try {
       // The payload is likely to be JSON, but if not, keep it as a string
--- a/services/sync/modules/util.js
+++ b/services/sync/modules/util.js
@@ -202,38 +202,16 @@ let Utils = {
     return Utils.encodeBase64url(Utils.generateRandomBytes(9));
   },
 
   _base64url_regex: /^[-abcdefghijklmnopqrstuvwxyz0123456789_]{12}$/i,
   checkGUID: function checkGUID(guid) {
     return !!guid && this._base64url_regex.test(guid);
   },
 
-  ensureOneOpen: let (windows = {}) function ensureOneOpen(window) {
-    // Close the other window if it exists
-    let url = window.location.href;
-    let other = windows[url];
-    if (other != null)
-      other.close();
-
-    // Save the new window for future closure
-    windows[url] = window;
-
-    // Actively clean up when the window is closed
-    window.addEventListener("unload", function() windows[url] = null, false);
-  },
-
-  // Returns a nsILocalFile representing a file relative to the current
-  // user's profile directory.  The argument should be a string with
-  // unix-style slashes for directory names (these slashes are automatically
-  // converted to platform-specific path separators).
-  getProfileFile: function getProfileFile(path) {
-    return FileUtils.getFile("ProfD", path.split("/"), true);
-  },
-
   /**
    * Add a simple getter/setter to an object that defers access of a property
    * to an inner property.
    *
    * @param obj
    *        Object to add properties to defer in its prototype
    * @param defer
    *        Property of obj to defer to
@@ -287,80 +265,56 @@ let Utils = {
     // Do the same for b's keys but skip those that we already checked
     for (let k in b)
       if (!(k in a) && !eq(a[k], b[k]))
         return false;
 
     return true;
   },
 
-  deepCopy: function Weave_deepCopy(thing, noSort) {
-    if (typeof(thing) != "object" || thing == null)
-      return thing;
-    let ret;
-
-    if (Array.isArray(thing)) {
-      ret = [];
-      for (let i = 0; i < thing.length; i++)
-        ret.push(Utils.deepCopy(thing[i], noSort));
-
-    } else {
-      ret = {};
-      let props = [p for (p in thing)];
-      if (!noSort)
-        props = props.sort();
-      props.forEach(function(k) ret[k] = Utils.deepCopy(thing[k], noSort));
-    }
-
-    return ret;
-  },
-
-  // Works on frames or exceptions, munges file:// URIs to shorten the paths
-  // FIXME: filename munging is sort of hackish, might be confusing if
-  // there are multiple extensions with similar filenames
-  formatFrame: function Utils_formatFrame(frame) {
-    let tmp = "<file:unknown>";
-
-    let file = frame.filename || frame.fileName;
-    if (file)
-      tmp = file.replace(/^(?:chrome|file):.*?([^\/\.]+\.\w+)$/, "$1");
-
-    if (frame.lineNumber)
-      tmp += ":" + frame.lineNumber;
-    if (frame.name)
-      tmp = frame.name + "()@" + tmp;
-
-    return tmp;
-  },
-
   exceptionStr: function Weave_exceptionStr(e) {
     let message = e.message ? e.message : e;
     return message + " " + Utils.stackTrace(e);
   },
-
-  stackTraceFromFrame: function Weave_stackTraceFromFrame(frame) {
-    let output = [];
-    while (frame) {
-      let str = Utils.formatFrame(frame);
-      if (str)
-        output.push(str);
-      frame = frame.caller;
-    }
-    return output.join(" < ");
-  },
-
+  
   stackTrace: function Weave_stackTrace(e) {
     // Wrapped nsIException
-    if (e.location)
-      return "Stack trace: " + Utils.stackTraceFromFrame(e.location);
+    if (e.location){
+      let frame = e.location; 
+      let output = [];
+      while (frame) {
+      	// Works on frames or exceptions, munges file:// URIs to shorten the paths
+        // FIXME: filename munging is sort of hackish, might be confusing if
+        // there are multiple extensions with similar filenames
+        let str = "<file:unknown>";
+
+        let file = frame.filename || frame.fileName;
+        if (file){
+          str = file.replace(/^(?:chrome|file):.*?([^\/\.]+\.\w+)$/, "$1");
+        }
 
+        if (frame.lineNumber){
+          str += ":" + frame.lineNumber;
+        }
+        if (frame.name){
+          str = frame.name + "()@" + str;
+        }
+
+        if (str){
+          output.push(str);
+        }
+        frame = frame.caller;
+      }
+      return "Stack trace: " + output.join(" < ");
+    }
     // Standard JS exception
-    if (e.stack)
+    if (e.stack){
       return "JS Stack trace: " + e.stack.trim().replace(/\n/g, " < ").
         replace(/@[^@]*?([^\/\.]+\.\w+:)/g, "@$1");
+    }
 
     return "No traceback available";
   },
   
   // Generator and discriminator for HMAC exceptions.
   // Split these out in case we want to make them richer in future, and to 
   // avoid inevitable confusion if the message changes.
   throwHMACMismatch: function throwHMACMismatch(shouldBe, is) {
@@ -886,38 +840,32 @@ let Utils = {
       return Services.io.newURI(URIString, null, null);
     } catch (e) {
       let log = Log4Moz.repository.getLogger("Sync.Utils");
       log.debug("Could not create URI: " + Utils.exceptionStr(e));
       return null;
     }
   },
 
-  makeURL: function Weave_makeURL(URIString) {
-    let url = Utils.makeURI(URIString);
-    url.QueryInterface(Ci.nsIURL);
-    return url;
-  },
-
   /**
    * Load a json object from disk
    *
    * @param filePath
    *        Json file path load from weave/[filePath].json
    * @param that
    *        Object to use for logging and "this" for callback
    * @param callback
    *        Function to process json object as its first parameter
    */
   jsonLoad: function Utils_jsonLoad(filePath, that, callback) {
     filePath = "weave/" + filePath + ".json";
     if (that._log)
       that._log.trace("Loading json from disk: " + filePath);
 
-    let file = Utils.getProfileFile(filePath);
+    let file = FileUtils.getFile("ProfD", filePath.split("/"), true);
     if (!file.exists()) {
       callback.call(that);
       return;
     }
 
     let channel = NetUtil.newChannel(file);
     channel.contentType = "application/json";
 
@@ -952,17 +900,17 @@ let Utils = {
    * @param callback
    *        Function called when the write has been performed. Optional.
    */
   jsonSave: function Utils_jsonSave(filePath, that, obj, callback) {
     filePath = "weave/" + filePath + ".json";
     if (that._log)
       that._log.trace("Saving json to disk: " + filePath);
 
-    let file = Utils.getProfileFile(filePath);
+    let file = FileUtils.getFile("ProfD", filePath.split("/"), true);
     let json = typeof obj == "function" ? obj.call(that) : obj;
     let out = JSON.stringify(json);
 
     let fos = FileUtils.openSafeFileOutputStream(file);
     let is = this._utf8Converter.convertToInputStream(out);
     NetUtil.asyncCopy(is, fos, function (result) {
       if (typeof callback == "function") {
         callback.call(that);        
--- a/services/sync/tests/unit/head_helpers.js
+++ b/services/sync/tests/unit/head_helpers.js
@@ -451,8 +451,31 @@ RotaryEngine.prototype = {
 
     for (let [id, value] in Iterator(this._store.items)) {
       if (item.denomination == value) {
         return id;
       }
     }
   }
 };
+
+deepCopy: function deepCopy(thing, noSort) {
+  if (typeof(thing) != "object" || thing == null){
+    return thing;
+  }
+  let ret;
+
+  if (Array.isArray(thing)) {
+    ret = [];
+    for (let i = 0; i < thing.length; i++){
+      ret.push(deepCopy(thing[i], noSort));
+	}
+  } else {
+    ret = {};
+    let props = [p for (p in thing)];
+    if (!noSort){
+      props = props.sort();
+    }
+    props.forEach(function(k) ret[k] = deepCopy(thing[k], noSort));
+  }
+
+  return ret;
+};
\ No newline at end of file
--- a/services/sync/tests/unit/test_bookmark_livemarks.js
+++ b/services/sync/tests/unit/test_bookmark_livemarks.js
@@ -51,17 +51,17 @@ let record631361 = {
 };
 
 // Clean up after other tests. Only necessary in XULRunner.
 store.wipe();
 
 function makeLivemark(p, mintGUID) {
   let b = new Livemark("bookmarks", p.id);
   // Copy here, because tests mutate the contents.
-  b.cleartext = Utils.deepCopy(p);
+  b.cleartext = deepCopy(p);
   
   if (mintGUID)
     b.id = Utils.makeGUID();
 
   return b;
 }
 
 
--- a/services/sync/tests/unit/test_resource.js
+++ b/services/sync/tests/unit/test_resource.js
@@ -490,14 +490,16 @@ function run_test() {
   _("Testing URI construction.");
   let args = [];
   args.push("newer=" + 1234);
   args.push("limit=" + 1234);
   args.push("sort=" + 1234);
 
   let query = "?" + args.join("&");
 
-  let uri1 = Utils.makeURL("http://foo/" + query);
-  let uri2 = Utils.makeURL("http://foo/");
+  let uri1 = Utils.makeURI("http://foo/" + query)
+                  .QueryInterface(Ci.nsIURL);
+  let uri2 = Utils.makeURI("http://foo/")
+                  .QueryInterface(Ci.nsIURL);
   uri2.query = query;
   do_check_eq(uri1.query, uri2.query);
   server.stop(do_test_finished);
 }
--- a/services/sync/tests/unit/test_resource_async.js
+++ b/services/sync/tests/unit/test_resource_async.js
@@ -656,18 +656,20 @@ add_test(function test_uri_construction(
   _("Testing URI construction.");
   let args = [];
   args.push("newer=" + 1234);
   args.push("limit=" + 1234);
   args.push("sort=" + 1234);
 
   let query = "?" + args.join("&");
 
-  let uri1 = Utils.makeURL("http://foo/" + query);
-  let uri2 = Utils.makeURL("http://foo/");
+  let uri1 = Utils.makeURI("http://foo/" + query)
+                  .QueryInterface(Ci.nsIURL);
+  let uri2 = Utils.makeURI("http://foo/")
+                  .QueryInterface(Ci.nsIURL);
   uri2.query = query;
   do_check_eq(uri1.query, uri2.query);
 
   run_next_test();
 });
 
 add_test(function test_new_channel() {
   _("Ensure a redirect to a new channel is handled properly.");
--- a/services/sync/tests/unit/test_tab_store.js
+++ b/services/sync/tests/unit/test_tab_store.js
@@ -75,17 +75,17 @@ function fakeSessionSvc(url, numtabs) {
               weaveLastUsed: 1
             }
           }]
         }]
       };
       if (numtabs) {
         let tabs = obj.windows[0].tabs;
         for (let i = 0; i < numtabs-1; i++)
-          tabs.push(Utils.deepCopy(tabs[0]));
+          tabs.push(deepCopy(tabs[0]));
       }
       return JSON.stringify(obj);
     }
   };
 };
 
 function test_getAllTabs() {
   let store = new TabEngine()._store, tabs;
--- a/services/sync/tests/unit/test_utils_deepCopy.js
+++ b/services/sync/tests/unit/test_utils_deepCopy.js
@@ -1,13 +1,13 @@
 Cu.import("resource://services-sync/util.js");
 
 function run_test() {
   let thing = {o: {foo: "foo", bar: ["bar"]}, a: ["foo", {bar: "bar"}]};
-  let ret = Utils.deepCopy(thing);
+  let ret = deepCopy(thing);
   do_check_neq(ret, thing)
   do_check_neq(ret.o, thing.o);
   do_check_neq(ret.o.bar, thing.o.bar);
   do_check_neq(ret.a, thing.a);
   do_check_neq(ret.a[1], thing.a[1]);
   do_check_eq(ret.o.foo, thing.o.foo);
   do_check_eq(ret.o.bar[0], thing.o.bar[0]);
   do_check_eq(ret.a[0], thing.a[0]);
--- a/services/sync/tests/unit/test_utils_json.js
+++ b/services/sync/tests/unit/test_utils_json.js
@@ -64,17 +64,18 @@ add_test(function test_save_logging() {
     run_next_test();
   }));
 });
 
 add_test(function test_load_logging() {
   _("Verify that reads and read errors are logged.");
 
   // Write a file with some invalid JSON
-  let file = Utils.getProfileFile("weave/log.json");
+  let filePath = "weave/log.json";
+  let file = FileUtils.getFile("ProfD", filePath.split("/"), true);
   let fos = Cc["@mozilla.org/network/file-output-stream;1"]
               .createInstance(Ci.nsIFileOutputStream);
   let flags = FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE
               | FileUtils.MODE_TRUNCATE;
   fos.init(file, flags, FileUtils.PERMS_FILE, fos.DEFER_OPEN);
   let stream = Cc["@mozilla.org/intl/converter-output-stream;1"]
                  .createInstance(Ci.nsIConverterOutputStream);
   stream.init(fos, "UTF-8", 4096, 0x0000);
--- a/services/sync/tests/unit/test_utils_makeURI.js
+++ b/services/sync/tests/unit/test_utils_makeURI.js
@@ -60,40 +60,8 @@ function _test_makeURI() {
   let uria6 = "about:weave/#hash";
   do_check_eq(Utils.makeURI(uria6).spec, uria6);
 
   _("Invalid uris are undefined");
   do_check_eq(Utils.makeURI("mozillalabs.com"), undefined);
   do_check_eq(Utils.makeURI("chrome://badstuff"), undefined);
   do_check_eq(Utils.makeURI("this is a test"), undefined);
 }
-
-function _test_makeURL() {
-  _("Check http uri");
-  let uri = "http://mozillalabs.com/";
-  do_check_true(Utils.makeURL(uri) instanceof Ci.nsIURL);
-
-  _("Check https uri");
-  let uris = "https://mozillalabs.com/";
-  do_check_true(Utils.makeURL(uris) instanceof Ci.nsIURL);
-
-  let uric = "chrome://browser/content/browser.xul";
-  do_check_true(Utils.makeURL(uric) instanceof Ci.nsIURL);
-
-  _("Check about uri");
-  let uria = "about:weave";
-  let except1;
-  try {
-    Utils.makeURL(uria);
-  } catch(e) {
-    except1 = e;
-  }
-  do_check_true(!!except1);
-
-  _("Check invalid uri");
-  let except2;
-  try {
-    Utils.makeURL("mozillalabs.com");
-  } catch(e) {
-    except2 = e;
-  }
-  do_check_true(!!except2);
-}