You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by br...@apache.org on 2013/10/16 19:13:24 UTC

[1/4] android commit: Updating to latest shelljs, old version doesn't preserve +x bits

Updated Branches:
  refs/heads/master 638fbfabd -> b57317bdc


Updating to latest shelljs, old version doesn't preserve +x bits


Project: http://git-wip-us.apache.org/repos/asf/cordova-android/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-android/commit/1f49f291
Tree: http://git-wip-us.apache.org/repos/asf/cordova-android/tree/1f49f291
Diff: http://git-wip-us.apache.org/repos/asf/cordova-android/diff/1f49f291

Branch: refs/heads/master
Commit: 1f49f291832c8f627108818fc7307934aa831fe2
Parents: 638fbfa
Author: Braden Shepherdson <br...@gmail.com>
Authored: Wed Oct 16 11:08:28 2013 -0400
Committer: Braden Shepherdson <br...@gmail.com>
Committed: Wed Oct 16 13:10:39 2013 -0400

----------------------------------------------------------------------
 bin/node_modules/shelljs/package.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cordova-android/blob/1f49f291/bin/node_modules/shelljs/package.json
----------------------------------------------------------------------
diff --git a/bin/node_modules/shelljs/package.json b/bin/node_modules/shelljs/package.json
index 6f545b9..fb6b9be 100644
--- a/bin/node_modules/shelljs/package.json
+++ b/bin/node_modules/shelljs/package.json
@@ -41,7 +41,7 @@
   },
   "_id": "shelljs@0.1.4",
   "dist": {
-    "shasum": "7a8aeaa3dc3c0be2e59d83168e83b4c4bc4dac95"
+    "shasum": "e3e290bd698047b9ef12f7f2c538ddb9f1a1c20e"
   },
   "_from": "shelljs@0.1.4",
   "_resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.1.4.tgz"


[2/4] Refactoring Android project-level and platform scripts to use Q.js

Posted by br...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/emulator.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/emulator.js b/bin/templates/cordova/lib/emulator.js
index 6f8a7dd..367cd94 100644
--- a/bin/templates/cordova/lib/emulator.js
+++ b/bin/templates/cordova/lib/emulator.js
@@ -20,14 +20,17 @@
 */
 
 var shell = require('shelljs'),
+    exec  = require('./exec'),
+    Q     = require('q'),
     path  = require('path'),
     appinfo = require('./appinfo'),
     build = require('./build'),
     ROOT  = path.join(__dirname, '..', '..'),
+    child_process = require('child_process'),
     new_emulator = 'cordova_emulator';
 
 /**
- * Returns a list of emulator images in the form of objects
+ * Returns a Promise for a list of emulator images in the form of objects
  * {
        name   : <emulator_name>,
        path   : <path_to_emulator_image>,
@@ -37,13 +40,9 @@ var shell = require('shelljs'),
    }
  */
 module.exports.list_images = function() {
-    var cmd = 'android list avds';
-    var result = shell.exec(cmd, {silent:true, async:false});
-    if (result.code > 0) {
-        console.error('Failed to execute android command \'' + cmd + '\'.');
-        process.exit(2);
-    } else {
-        var response = result.output.split('\n');
+    return exec('android list avds')
+    .then(function(output) {
+        var response = output.split('\n');
         var emulator_list = [];
         for (var i = 1; i < response.length; i++) {
             // To return more detailed information use img_obj
@@ -76,41 +75,41 @@ module.exports.list_images = function() {
 
         }
         return emulator_list;
-    }
+    });
 }
 
 /**
  * Will return the closest avd to the projects target
  * or undefined if no avds exist.
+ * Returns a promise.
  */
 module.exports.best_image = function() {
     var project_target = this.get_target().replace('android-', '');
-    var images = this.list_images();
-    var closest = 9999;
-    var best = images[0];
-    for (i in images) {
-        var target = images[i].target;
-        if(target) {
-            var num = target.split('(API level ')[1].replace(')', '');
-            if (num == project_target) {
-                return images[i];
-            } else if (project_target - num < closest && project_target > num) {
-                var closest = project_target - num;
-                best = images[i];
+    return this.list_images()
+    .then(function(images) {
+        var closest = 9999;
+        var best = images[0];
+        for (i in images) {
+            var target = images[i].target;
+            if(target) {
+                var num = target.split('(API level ')[1].replace(')', '');
+                if (num == project_target) {
+                    return images[i];
+                } else if (project_target - num < closest && project_target > num) {
+                    var closest = project_target - num;
+                    best = images[i];
+                }
             }
         }
-    }
-    return best;
+        return best;
+    });
 }
 
+// Returns a promise.
 module.exports.list_started = function() {
-    var cmd = 'adb devices';
-    var result = shell.exec(cmd, {silent:true, async:false});
-    if (result.code > 0) {
-        console.error('Failed to execute android command \'' + cmd + '\'.');
-        process.exit(2);
-    } else {
-        var response = result.output.split('\n');
+    return exec('adb devices')
+    .then(function(output) {
+        var response = output.split('\n');
         var started_emulator_list = [];
         for (var i = 1; i < response.length; i++) {
             if (response[i].match(/device/) && response[i].match(/emulator/)) {
@@ -118,7 +117,7 @@ module.exports.list_started = function() {
             }
         }
         return started_emulator_list;
-    }
+    });
 }
 
 module.exports.get_target = function() {
@@ -126,15 +125,19 @@ module.exports.get_target = function() {
     return target.split('=')[1].replace('\n', '').replace('\r', '').replace(' ', '');
 }
 
+// Returns a promise.
 module.exports.list_targets = function() {
-    var target_out = shell.exec('android list targets', {silent:true, async:false}).output.split('\n');
-    var targets = [];
-    for (var i = target_out.length; i >= 0; i--) {
-        if(target_out[i].match(/id:/)) {
-            targets.push(targets[i].split(' ')[1]);
+    return exec('android list targets')
+    .then(function(output) {
+        var target_out = output.split('\n');
+        var targets = [];
+        for (var i = target_out.length; i >= 0; i--) {
+            if(target_out[i].match(/id:/)) {
+                targets.push(targets[i].split(' ')[1]);
+            }
         }
-    }
-    return targets;
+        return targets;
+    });
 }
 
 /*
@@ -142,147 +145,141 @@ module.exports.list_targets = function() {
  * and returns the started ID of that emulator.
  * If no ID is given it will used the first image availible,
  * if no image is availible it will error out (maybe create one?).
+ *
+ * Returns a promise.
  */
 module.exports.start = function(emulator_ID) {
-    var started_emulators = this.list_started();
-    var num_started = started_emulators.length;
-    if (typeof emulator_ID === 'undefined') {
-        var emulator_list = this.list_images();
-        if (emulator_list.length > 0) {
-            emulator_ID = this.best_image().name;
-            console.log('WARNING : no emulator specified, defaulting to ' + emulator_ID);
+    var self = this;
+    var emulator_id, num_started, started_emulators;
+
+    return self.list_started()
+    .then(function(list) {
+        started_emulators = list;
+        num_started = started_emulators.length;
+        if (typeof emulator_ID === 'undefined') {
+            return self.list_images()
+            .then(function(emulator_list) {
+                if (emulator_list.length > 0) {
+                    return self.best_image()
+                    .then(function(best) {
+                        emulator_ID = best.name;
+                        console.log('WARNING : no emulator specified, defaulting to ' + emulator_ID);
+                        return emulator_ID;
+                    });
+                } else {
+                    return Q.reject('ERROR : No emulator images (avds) found, if you would like to create an\n' +
+                        ' avd follow the instructions provided here:\n' +
+                        ' http://developer.android.com/tools/devices/index.html\n' +
+                        ' Or run \'android create avd --name <name> --target <targetID>\'\n' +
+                        ' in on the command line.');
+                }
+            });
         } else {
-            console.error('ERROR : No emulator images (avds) found, if you would like to create an');
-            console.error(' avd follow the instructions provided here : ');
-            console.error(' http://developer.android.com/tools/devices/index.html')
-            console.error(' Or run \'android create avd --name <name> --target <targetID>\' ');
-            console.error(' in on the command line.');
-            process.exit(2);
-            /*console.log('WARNING : no emulators availible, creating \'' + new_emulator + '\'.');
-            this.create_image(new_emulator, this.get_target());
-            emulator_ID = new_emulator;*/
+            return Q(emulator_ID);
         }
-    }
-
-    var pipe_null = (process.platform == 'win32' || process.platform == 'win64'? '> NUL' : '> /dev/null');
-    var cmd = 'emulator -avd ' + emulator_ID + ' ' + pipe_null + ' &';
-    if(process.platform == 'win32' || process.platform == 'win64') {
-        cmd = '%comspec% /c start cmd /c ' + cmd;
-    }
-    var result = shell.exec(cmd, {silent:true, async:false}, function(code, output) {
-        if (code > 0) {
-            console.error('Failed to execute android command \'' + cmd + '\'.');
-            console.error(output);
-            process.exit(2);
+    }).then(function() {
+        var cmd, args;
+        if(process.platform == 'win32' || process.platform == 'win64') {
+            cmd = '%comspec%';
+            args = ['/c', 'start', 'cmd', '/c', 'emulator', '-avd', emulator_ID];
+        } else {
+            cmd = 'emulator';
+            args = ['-avd', emulator_ID];
         }
-    });
-
-    // wait for emulator to start
-    console.log('Waiting for emulator...');
-    var new_started = this.wait_for_emulator(num_started);
-    var emulator_id;
-    if (new_started.length > 1) {
-        for (i in new_started) {
-            console.log(new_started[i]);
-            console.log(started_emulators.indexOf(new_started[i]));
-            if (started_emulators.indexOf(new_started[i]) < 0) {
-                emulator_id = new_started[i];
+        var proc = child_process.spawn(cmd, args, { stdio: 'inherit', detached: true });
+        proc.unref(); // Don't wait for it to finish, since the emulator will probably keep running for a long time.
+    }).then(function() {
+        // wait for emulator to start
+        console.log('Waiting for emulator...');
+        return self.wait_for_emulator(num_started);
+    }).then(function(new_started) {
+        if (new_started.length > 1) {
+            for (i in new_started) {
+                if (started_emulators.indexOf(new_started[i]) < 0) {
+                    emulator_id = new_started[i];
+                }
             }
+        } else {
+            emulator_id = new_started[0];
         }
-    } else {
-        emulator_id = new_started[0];
-    }
-    if (!emulator_id) {
-        console.error('ERROR :  Failed to start emulator, could not find new emulator');
-        process.exit(2);
-    }
-
-    //wait for emulator to boot up
-    process.stdout.write('Booting up emulator (this may take a while)...');
-    this.wait_for_boot(emulator_id);
-    console.log('BOOT COMPLETE');
+        if (!emulator_id) return Q.reject('ERROR :  Failed to start emulator, could not find new emulator');
 
-    //unlock screen
-    cmd = 'adb -s ' + emulator_id + ' shell input keyevent 82';
-    shell.exec(cmd, {silent:false, async:false});
+        //wait for emulator to boot up
+        process.stdout.write('Booting up emulator (this may take a while)...');
+        return self.wait_for_boot(emulator_id);
+    }).then(function() {
+        console.log('BOOT COMPLETE');
 
-    //return the new emulator id for the started emulators
-    return emulator_id;
+        //unlock screen
+        return exec('adb -s ' + emulator_id + ' shell input keyevent 82');
+    }).then(function() {
+        //return the new emulator id for the started emulators
+        return emulator_id;
+    });
 }
 
 /*
  * Waits for the new emulator to apear on the started-emulator list.
+ * Returns a promise with a list of newly started emulators' IDs.
  */
 module.exports.wait_for_emulator = function(num_running) {
-    var new_started = this.list_started();
-    if (new_started.length > num_running) {
-        return new_started;
-    } else {
-        this.sleep(1);
-        return this.wait_for_emulator(num_running);
-    }
+    var self = this;
+    return self.list_started()
+    .then(function(new_started) {
+        if (new_started.length > num_running) {
+            return new_started;
+        } else {
+            return Q.delay(1000).then(function() {
+                return self.wait_for_emulator(num_running);
+            });
+        }
+    });
 }
 
 /*
  * Waits for the boot animation property of the emulator to switch to 'stopped'
  */
 module.exports.wait_for_boot = function(emulator_id) {
-    var cmd;
-    // ShellJS opens a lot of file handles, and the default on OS X is too small.
-    // TODO : This is not working, need to find a better way to increese the ulimit.
-    if(process.platform == 'win32' || process.platform == 'win64') {
-        cmd = 'adb -s ' + emulator_id + ' shell getprop init.svc.bootanim';
-    } else {
-        cmd = 'ulimit -S -n 4096; adb -s ' + emulator_id + ' shell getprop init.svc.bootanim';
-    }
-    var boot_anim = shell.exec(cmd, {silent:true, async:false});
-    if (boot_anim.output.match(/stopped/)) {
-        return;
-    } else {
-        process.stdout.write('.');
-        this.sleep(3);
-        return this.wait_for_boot(emulator_id);
-    }
-}
-
-/*
- * TODO : find a better way to wait for the emulator (maybe using async methods?)
- */
-module.exports.sleep = function(time_sec) {
-    if (process.platform == 'win32' || process.platform == 'win64') {
-        shell.exec('ping 127.0.0.1 -n ' + time_sec, {silent:true, async:false});
-    } else {
-        shell.exec('sleep ' + time_sec, {silent:true, async:false});
-    }
+    var self = this;
+    return exec('adb -s ' + emulator_id + ' shell getprop init.svc.bootanim')
+    .then(function(output) {
+        if (output.match(/stopped/)) {
+            return;
+        } else {
+            process.stdout.write('.');
+            return Q.delay(3000).then(function() {
+                return self.wait_for_boot(emulator_id);
+            });
+        }
+    });
 }
 
 /*
  * Create avd
  * TODO : Enter the stdin input required to complete the creation of an avd.
+ * Returns a promise.
  */
 module.exports.create_image = function(name, target) {
     console.log('Creating avd named ' + name);
     if (target) {
-        var cmd = 'android create avd --name ' + name + ' --target ' + target;
-        var create = shell.exec(cmd, {sient:false, async:false});
-        if (create.error) {
+        return exec('android create avd --name ' + name + ' --target ' + target)
+        .then(null, function(error) {
             console.error('ERROR : Failed to create emulator image : ');
             console.error(' Do you have the latest android targets including ' + target + '?');
             console.error(create.output);
-            process.exit(2);
-        }
+        });
     } else {
         console.log('WARNING : Project target not found, creating avd with a different target but the project may fail to install.');
-        var cmd = 'android create avd --name ' + name + ' --target ' + this.list_targets()[0];
-        var create = shell.exec(cmd, {sient:false, async:false});
-        if (create.error) {
+        return exec('android create avd --name ' + name + ' --target ' + this.list_targets()[0])
+        .then(function() {
+            // TODO: This seems like another error case, even though it always happens.
+            console.error('ERROR : Unable to create an avd emulator, no targets found.');
+            console.error('Please insure you have targets availible by runing the "android" command');
+            return Q.reject();
+        }, function(error) {
             console.error('ERROR : Failed to create emulator image : ');
-            console.error(create.output);
-            process.exit(2);
-        }
-        console.error('ERROR : Unable to create an avd emulator, no targets found.');
-        console.error('Please insure you have targets availible by runing the "android" command').
-        process.exit(2);
+            console.error(error);
+        });
     }
 }
 
@@ -290,48 +287,44 @@ module.exports.create_image = function(name, target) {
  * Installs a previously built application on the emulator and launches it.
  * If no target is specified, then it picks one.
  * If no started emulators are found, error out.
+ * Returns a promise.
  */
 module.exports.install = function(target) {
-    var emulator_list = this.list_started();
-    if (emulator_list.length < 1) {
-        console.error('ERROR : No started emulators found, please start an emultor before deploying your project.');
-        process.exit(2);
-        /*console.log('WARNING : No started emulators found, attemting to start an avd...');
-        this.start(this.best_image().name);*/
-    }
-    // default emulator
-    target = typeof target !== 'undefined' ? target : emulator_list[0];
-    if (emulator_list.indexOf(target) > -1) {
+    var self = this;
+    return this.list_started()
+    .then(function(emulator_list) {
+        if (emulator_list.length < 1) {
+            return Q.reject('No started emulators found, please start an emultor before deploying your project.');
+        }
+
+        // default emulator
+        target = typeof target !== 'undefined' ? target : emulator_list[0];
+        if (emulator_list.indexOf(target) < 0) {
+            return Q.reject('Unable to find target \'' + target + '\'. Failed to deploy to emulator.');
+        }
+
         console.log('Installing app on emulator...');
         var apk_path = build.get_apk();
-        var cmd = 'adb -s ' + target + ' install -r ' + apk_path;
-        var install = shell.exec(cmd, {sient:false, async:false});
-        if (install.error || install.output.match(/Failure/)) {
-            console.error('ERROR : Failed to install apk to emulator : ');
-            console.error(install.output);
-            process.exit(2);
+        return exec('adb -s ' + target + ' install -r ' + apk_path);
+    }).then(function(output) {
+        if (output.match(/Failure/)) {
+            return Q.reject('Failed to install apk to emulator: ' + output);
         }
-
+        return Q();
+    }, function(err) {
+        return Q.reject('Failed to install apk to emulator: ' + err);
+    }).then(function() {
         //unlock screen
-        cmd = 'adb -s ' + target + ' shell input keyevent 82';
-        shell.exec(cmd, {silent:true, async:false});
-
+        return exec('adb -s ' + target + ' shell input keyevent 82');
+    }).then(function() {
         // launch the application
         console.log('Launching application...');
         var launchName = appinfo.getActivityName();
         cmd = 'adb -s ' + target + ' shell am start -W -a android.intent.action.MAIN -n ' + launchName;
-        console.log(cmd);
-        var launch = shell.exec(cmd, {silent:false, async:false});
-        if(launch.code > 0) {
-            console.error('ERROR : Failed to launch application on emulator : ' + launch.error);
-            console.error(launch.output);
-            process.exit(2);
-        } else {
-            console.log('LANCH SUCCESS');
-        }
-    } else {
-        console.error('ERROR : Unable to find target \'' + target + '\'.');
-        console.error('Failed to deploy to emulator.');
-        process.exit(2);
-    }
+        return exec(cmd);
+    }).then(function(output) {
+        console.log('LAUNCH SUCCESS');
+    }, function(err) {
+        return Q.reject('Failed to launch app on emulator: ' + err);
+    });
 }

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/exec.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/exec.js b/bin/templates/cordova/lib/exec.js
new file mode 100644
index 0000000..6afa9c0
--- /dev/null
+++ b/bin/templates/cordova/lib/exec.js
@@ -0,0 +1,43 @@
+#!/usr/bin/env node
+
+/*
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+*/
+
+var child_process = require('child_process'),
+    Q       = require('q');
+
+// Takes a command and optional current working directory.
+// Returns a promise that either resolves with the stdout, or
+// rejects with an error message and the stderr.
+module.exports = function(cmd, opt_cwd) {
+    var d = Q.defer();
+    console.log('exec: ' + cmd);
+    try {
+        child_process.exec(cmd, {cwd: opt_cwd}, function(err, stdout, stderr) {
+            console.log([cmd, err, stdout, stderr]);
+            if (err) d.reject('Error executing "' + cmd + '": ' + stderr);
+            else d.resolve(stdout);
+        });
+    } catch(e) {
+        console.error('error caught: ' + e);
+        d.reject(e);
+    }
+    return d.promise;
+}
+

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/install-device
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/install-device b/bin/templates/cordova/lib/install-device
index cf53918..fc4b784 100755
--- a/bin/templates/cordova/lib/install-device
+++ b/bin/templates/cordova/lib/install-device
@@ -26,13 +26,17 @@ if(args.length > 2) {
     var install_target;
     if (args[2].substring(0, 9) == '--target=') {
         install_target = args[2].substring(9, args[2].length);
-        device.install(install_target);
-        process.exit(0);
+        device.install(install_target).done(null, function(err) {
+            console.error('ERROR: ' + err);
+            process.exit(2);
+        });
      } else {
         console.error('ERROR : argument \'' + args[2] + '\' not recognized.');
         process.exit(2);
      }
 } else {
-    device.install();
-    process.exit(0);
-}
\ No newline at end of file
+    device.install().done(null, function(err) {
+        console.error('ERROR: ' + err);
+        process.exit(2);
+    });
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/install-emulator
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/install-emulator b/bin/templates/cordova/lib/install-emulator
index 70421be..aa2a34f 100755
--- a/bin/templates/cordova/lib/install-emulator
+++ b/bin/templates/cordova/lib/install-emulator
@@ -22,17 +22,17 @@
 var emulator = require('./emulator'),
     args     = process.argv;
 
+var install_target;
 if(args.length > 2) {
-    var install_target;
     if (args[2].substring(0, 9) == '--target=') {
         install_target = args[2].substring(9, args[2].length);
-        emulator.install(install_target);
-        process.exit(0);
      } else {
         console.error('ERROR : argument \'' + args[2] + '\' not recognized.');
         process.exit(2);
      }
-} else {
-    emulator.install();
-    process.exit(0);
-}
\ No newline at end of file
+}
+
+emulator.install(install_target).done(null, function(err) {
+    console.error('ERROR: ' + err);
+    process.exit(2);
+});

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/list-devices
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/list-devices b/bin/templates/cordova/lib/list-devices
index bdd0abd..e390bff 100755
--- a/bin/templates/cordova/lib/list-devices
+++ b/bin/templates/cordova/lib/list-devices
@@ -22,7 +22,12 @@
 var devices = require('./device');
 
 // Usage support for when args are given
-var device_list = devices.list();
-for(device in device_list) {
-    console.log(device_list[device]);
-}
\ No newline at end of file
+devices.list().done(function(device_list) {
+    device_list && device_list.forEach(function(dev) {
+        console.log(dev);
+    });
+}, function(err) {
+    console.error('ERROR: ' + err);
+    process.exit(2);
+});
+

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/list-emulator-images
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/list-emulator-images b/bin/templates/cordova/lib/list-emulator-images
index 69f4789..996cf55 100755
--- a/bin/templates/cordova/lib/list-emulator-images
+++ b/bin/templates/cordova/lib/list-emulator-images
@@ -22,8 +22,11 @@
 var emulators = require('./emulator');
 
 // Usage support for when args are given
-var emulator_list = emulators.list_images();
-for(emulator in emulator_list) {
-    console.log(emulator_list[emulator].name);
-    process.exit(0);
-}
\ No newline at end of file
+emulators.list_images().done(function(emulator_list) {
+    emulator_list && emulator_list.forEach(function(emu) {
+        console.log(emu.name);
+    });
+}, function(err) {
+    console.error('ERROR: ' + err);
+    process.exit(2);
+});

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/list-started-emulators
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/list-started-emulators b/bin/templates/cordova/lib/list-started-emulators
index 3e69b2f..2ae8c5a 100755
--- a/bin/templates/cordova/lib/list-started-emulators
+++ b/bin/templates/cordova/lib/list-started-emulators
@@ -22,8 +22,11 @@
 var emulators = require('./emulator');
 
 // Usage support for when args are given
-var emulator_list = emulators.list_started();
-for(emulator in emulator_list) {
-    console.log(emulator_list[emulator]);
-    process.exit(0);
-}
\ No newline at end of file
+emulators.list_started().done(function(emulator_list) {
+    emulator_list && emulator_list.forEach(function(emu) {
+        console.log(emu);
+    });
+}, function(err) {
+    console.error('ERROR: ' + err);
+    process.exit(2);
+});

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/log.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/log.js b/bin/templates/cordova/lib/log.js
index ff14e46..7339b1c 100644
--- a/bin/templates/cordova/lib/log.js
+++ b/bin/templates/cordova/lib/log.js
@@ -21,23 +21,37 @@
 
 var shell = require('shelljs'),
     path  = require('path'),
-    ROOT = path.join(__dirname, '..', '..');
+    Q     = require('q'),
+    child_process = require('child_process'),
+    ROOT  = path.join(__dirname, '..', '..');
 
 /*
  * Starts running logcat in the shell.
+ * Returns a promise.
  */
 module.exports.run = function() {
     var cmd = 'adb logcat | grep -v nativeGetEnabledTags';
-    var result = shell.exec(cmd, {silent:false, async:false});
-    if (result.code > 0) {
-        console.error('ERROR: Failed to run logcat command.');
-        console.error(result.output);
-        process.exit(2);
-    }
+    var d = Q.defer();
+    var adb = child_process.spawn('adb', ['logcat']);
+
+    adb.stdout.on('data', function(data) {
+        var lines = data ? data.toString().split('\n') : [];
+        var out = lines.filter(function(x) { return x.indexOf('nativeGetEnabledTags') < 0; });
+        console.log(out.join('\n'));
+    });
+
+    adb.stderr.on('data', console.error);
+    adb.on('close', function(code) {
+        if (code > 0) {
+            d.reject('Failed to run logcat command.');
+        } else d.resolve();
+    });
+
+    return d.promise;
 }
 
 module.exports.help = function() {
     console.log('Usage: ' + path.relative(process.cwd(), path.join(ROOT, 'corodva', 'log')));
     console.log('Gives the logcat output on the command line.');
     process.exit(0);
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/run.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/run.js b/bin/templates/cordova/lib/run.js
index b1c8b2b..6806014 100644
--- a/bin/templates/cordova/lib/run.js
+++ b/bin/templates/cordova/lib/run.js
@@ -22,13 +22,15 @@
 var path  = require('path'),
     build = require('./build'),
     emulator = require('./emulator'),
-    device   = require('./device');
+    device   = require('./device'),
+    Q = require('q');
 
 /*
  * Runs the application on a device if availible.
  * If not device is found, it will use a started emulator.
  * If no started emulators are found it will attempt to start an avd.
  * If no avds are found it will error out.
+ * Returns a promise.
  */
  module.exports.run = function(args) {
     var build_type;
@@ -52,61 +54,75 @@ var path  = require('path'),
             process.exit(2);
         }
     }
-    build.run(build_type);
-    if (install_target == '--device') {
-        device.install();
-    } else if (install_target == '--emulator') {
-        if (emulator.list_started() == 0) {
-            emulator.start();
-        }
-        emulator.install();
-    } else if (install_target) {
-        var devices = device.list();
-        var started_emulators = emulator.list_started();
-        var avds = emulator.list_images();
-        if (devices.indexOf(install_target) > -1) {
-            device.install(install_target);
-        } else if (started_emulators.indexOf(install_target) > -1) {
-            emulator.install(install_target);
-        } else {
-            // if target emulator isn't started, then start it.
-            var emulator_ID;
-            for(avd in avds) {
-                if(avds[avd].name == install_target) {
-                    emulator_ID = emulator.start(install_target);
-                    emulator.install(emulator_ID);
-                    break;
+
+    return build.run(build_type).then(function() {
+        if (install_target == '--device') {
+            return device.install();
+        } else if (install_target == '--emulator') {
+            return emulator.list_started().then(function(started) {
+                var p = started && started.length > 0 ? Q() : emulator.start();
+                return p.then(function() { emulator.install(); });
+            });
+        } else if (install_target) {
+            var devices, started_emulators, avds;
+            return device.list()
+            .then(function(res) {
+                devices = res;
+                return emulator.list_started();
+            }).then(function(res) {
+                started_emulators = res;
+                return emulator.list_images();
+            }).then(function(res) {
+                avds = res;
+                if (devices.indexOf(install_target) > -1) {
+                    return device.install(install_target);
+                } else if (started_emulators.indexOf(install_target) > -1) {
+                    return emulator.install(install_target);
+                } else {
+                    // if target emulator isn't started, then start it.
+                    var emulator_ID;
+                    for(avd in avds) {
+                        if(avds[avd].name == install_target) {
+                            return emulator.start(install_target)
+                            .then(function() { emulator.install(emulator_ID); });
+                        }
+                    }
+                    return Q.reject('Target \'' + install_target + '\' not found, unable to run project');
                 }
-            }
-            if(!emulator_ID) {
-                console.error('ERROR : Target \'' + install_target + '\' not found, unalbe to run project');
-                process.exit(2);
-            }
-        }
-    } else {
-        // no target given, deploy to device if availible, otherwise use the emulator.
-        var device_list = device.list();
-        if (device_list.length > 0) {
-            console.log('WARNING : No target specified, deploying to device \'' + device_list[0] + '\'.');
-            device.install(device_list[0])
+            });
         } else {
-            var emulator_list = emulator.list_started();
-            if (emulator_list.length > 0) {
-                console.log('WARNING : No target specified, deploying to emulator \'' + emulator_list[0] + '\'.');
-                emulator.install(emulator_list[0]);
-            } else {
-                console.log('WARNING : No started emulators found, starting an emulator.');
-                var best_avd = emulator.best_image();
-                if(best_avd) {
-                    var emulator_ID = emulator.start(best_avd.name);
-                    console.log('WARNING : No target specified, deploying to emulator \'' + emulator_ID + '\'.');
-                    emulator.install(emulator_ID);
+            // no target given, deploy to device if availible, otherwise use the emulator.
+            return device.list()
+            .then(function(device_list) {
+                if (device_list.length > 0) {
+                    console.log('WARNING : No target specified, deploying to device \'' + device_list[0] + '\'.');
+                    return device.install(device_list[0]);
                 } else {
-                    emulator.start();
+                    return emulator.list_started()
+                    .then(function(emulator_list) {
+                        if (emulator_list.length > 0) {
+                            console.log('WARNING : No target specified, deploying to emulator \'' + emulator_list[0] + '\'.');
+                            return emulator.install(emulator_list[0]);
+                        } else {
+                            console.log('WARNING : No started emulators found, starting an emulator.');
+                            return emulator.best_image()
+                            .then(function(best_avd) {
+                                if(best_avd) {
+                                    return emulator.start(best_avd.name)
+                                    .then(function(emulator_ID) {
+                                        console.log('WARNING : No target specified, deploying to emulator \'' + emulator_ID + '\'.');
+                                        return emulator.install(emulator_ID);
+                                    });
+                                } else {
+                                    return emulator.start();
+                                }
+                            });
+                        }
+                    });
                 }
-            }
+            });
         }
-    }
+    });
 }
 
 module.exports.help = function() {
@@ -120,4 +136,4 @@ module.exports.help = function() {
     console.log('    --emulator : Will deploy the built project to an emulator if one exists');
     console.log('    --target=<target_id> : Installs to the target with the specified id.');
     process.exit(0);
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/start-emulator
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/start-emulator b/bin/templates/cordova/lib/start-emulator
index 8ea6d3f..f96bdc3 100755
--- a/bin/templates/cordova/lib/start-emulator
+++ b/bin/templates/cordova/lib/start-emulator
@@ -22,17 +22,18 @@
 var emulator = require('./emulator'),
       args   = process.argv;
 
+var install_target;
 if(args.length > 2) {
-    var install_target;
     if (args[2].substring(0, 9) == '--target=') {
         install_target = args[2].substring(9, args[2].length);
-        emulator.start(install_target);
-        process.exit(0);
      } else {
         console.error('ERROR : argument \'' + args[2] + '\' not recognized.');
         process.exit(2);
      }
-} else {
-    emulator.start();
-    process.exit(0);
-}
\ No newline at end of file
+}
+
+emulator.start(install_target).done(null, function(err) {
+    console.error('ERROR: ' + err);
+    process.exit(2);
+});
+

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/log
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/log b/bin/templates/cordova/log
index 514f69c..47f0605 100755
--- a/bin/templates/cordova/log
+++ b/bin/templates/cordova/log
@@ -26,8 +26,11 @@ var log  = require('./lib/log'),
 // Usage support for when args are given
 if(args.length > 2) {
     log.help();
-} else if(reqs.run()) {
-    log.run();
 } else {
-    process.exit(2);
-}
\ No newline at end of file
+    reqs.run().done(function() {
+        return log.run();
+    }, function(err) {
+        console.error('ERROR: ' + err);
+        process.exit(2);
+    });
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/run
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/run b/bin/templates/cordova/run
index c3a5772..d4e2c6c 100755
--- a/bin/templates/cordova/run
+++ b/bin/templates/cordova/run
@@ -27,9 +27,11 @@ var run  = require('./lib/run'),
 if (args[2] == '--help' || args[2] == '/?' || args[2] == '-h' ||
                     args[2] == 'help' || args[2] == '-help' || args[2] == '/help') {
     run.help();
-} else if(reqs.run()) {
-    run.run(args);
-    process.exit(0);
 } else {
-    process.exit(2);
-}
\ No newline at end of file
+    reqs.run().done(function() {
+        return run.run(args);
+    }, function(err) {
+        console.error('ERROR: ' + err);
+        process.exit(2);
+    });
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/update
----------------------------------------------------------------------
diff --git a/bin/update b/bin/update
index aabe7db..59f2bb6 100755
--- a/bin/update
+++ b/bin/update
@@ -28,6 +28,9 @@ if(args.length < 3 || (args[2] == '--help' || args[2] == '/?' || args[2] == '-h'
     console.log('Usage: ' + path.relative(process.cwd(), path.join(__dirname, 'update')) + ' <path_to_project>');
     process.exit(1);
 } else {
-    create.updateProject(args[2]);
+    create.updateProject(args[2]).done(null, function(err) {
+        console.error(err);
+        process.exit(2);
+    });
 }
 


[4/4] android commit: Refactoring Android project-level and platform scripts to use Q.js

Posted by br...@apache.org.
Refactoring Android project-level and platform scripts to use Q.js

This eliminates the use of shelljs.exec's sync mode, which is the source
of the filehandle leaks that can cause EMFILE on OSX, and are
CPU-intensive everywhere.

Tested locally, needs poking before it gets released.


Project: http://git-wip-us.apache.org/repos/asf/cordova-android/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-android/commit/b57317bd
Tree: http://git-wip-us.apache.org/repos/asf/cordova-android/tree/b57317bd
Diff: http://git-wip-us.apache.org/repos/asf/cordova-android/diff/b57317bd

Branch: refs/heads/master
Commit: b57317bdc25e3d48bb014faa7c063bc289682a1c
Parents: 1f49f29
Author: Braden Shepherdson <br...@gmail.com>
Authored: Fri Sep 27 11:48:55 2013 -0400
Committer: Braden Shepherdson <br...@gmail.com>
Committed: Wed Oct 16 13:10:53 2013 -0400

----------------------------------------------------------------------
 bin/check_reqs                                  |    7 +-
 bin/create                                      |    5 +-
 bin/lib/check_reqs.js                           |   61 +-
 bin/lib/create.js                               |  151 +-
 bin/node_modules/q/CONTRIBUTING.md              |   40 +
 bin/node_modules/q/LICENSE                      |   19 +
 bin/node_modules/q/README.md                    |  813 ++++++++
 .../q/benchmark/compare-with-callbacks.js       |   71 +
 bin/node_modules/q/benchmark/scenarios.js       |   36 +
 bin/node_modules/q/package.json                 |   93 +
 bin/node_modules/q/q.js                         | 1937 ++++++++++++++++++
 bin/node_modules/q/queue.js                     |   35 +
 bin/package.json                                |    7 +-
 bin/templates/cordova/build                     |   12 +-
 bin/templates/cordova/clean                     |   12 +-
 bin/templates/cordova/lib/build.js              |   24 +-
 bin/templates/cordova/lib/clean.js              |   13 +-
 bin/templates/cordova/lib/device.js             |   85 +-
 bin/templates/cordova/lib/emulator.js           |  347 ++--
 bin/templates/cordova/lib/exec.js               |   43 +
 bin/templates/cordova/lib/install-device        |   14 +-
 bin/templates/cordova/lib/install-emulator      |   14 +-
 bin/templates/cordova/lib/list-devices          |   13 +-
 bin/templates/cordova/lib/list-emulator-images  |   13 +-
 .../cordova/lib/list-started-emulators          |   13 +-
 bin/templates/cordova/lib/log.js                |   30 +-
 bin/templates/cordova/lib/run.js                |  120 +-
 bin/templates/cordova/lib/start-emulator        |   15 +-
 bin/templates/cordova/log                       |   11 +-
 bin/templates/cordova/run                       |   12 +-
 bin/update                                      |    5 +-
 31 files changed, 3606 insertions(+), 465 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/check_reqs
----------------------------------------------------------------------
diff --git a/bin/check_reqs b/bin/check_reqs
index 4a8abee..2ac8752 100755
--- a/bin/check_reqs
+++ b/bin/check_reqs
@@ -21,7 +21,8 @@
 
 var check_reqs = require('./lib/check_reqs');
 
-if(!check_reqs.run()) {
-      process.exit(2);
-}
+check_reqs.run().done(null, function(err) {
+    console.log(err);
+    process.exit(2);
+});
 

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/create
----------------------------------------------------------------------
diff --git a/bin/create b/bin/create
index 020bf86..9ab6689 100755
--- a/bin/create
+++ b/bin/create
@@ -31,6 +31,9 @@ if(args.length < 3 || (args[2] == '--help' || args[2] == '/?' || args[2] == '-h'
     console.log('    <project_name>: Project name');
     process.exit(1);
 } else {
-    create.createProject(args[2], args[3], args[4], args[5]);
+    create.createProject(args[2], args[3], args[4], args[5]).done(null, function(err) {
+        console.error(err);
+        process.exit(2);
+    });
 }
 

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/lib/check_reqs.js
----------------------------------------------------------------------
diff --git a/bin/lib/check_reqs.js b/bin/lib/check_reqs.js
index c064499..80f88a8 100644
--- a/bin/lib/check_reqs.js
+++ b/bin/lib/check_reqs.js
@@ -20,6 +20,8 @@
 */
 
 var shell = require('shelljs'),
+    child_process = require('child_process'),
+    Q     = require('q'),
     path  = require('path'),
     fs    = require('fs'),
     ROOT  = path.join(__dirname, '..', '..');
@@ -36,43 +38,54 @@ module.exports.get_target = function() {
     }
 }
 
+// Returns a promise.
 module.exports.check_ant = function() {
-    var test = shell.exec('ant -version', {silent:true, async:false});
-    if(test.code > 0) {
-        console.error('ERROR : executing command \'ant\', make sure you have ant installed and added to your path.');
-        return false;
-    }
-    return true;
+    var d = Q.defer();
+    child_process.exec('ant -version', function(err, stdout, stderr) {
+        if (err) d.reject(new Error('ERROR : executing command \'ant\', make sure you have ant installed and added to your path.'));
+        else d.resolve();
+    });
+    return d.promise;
 }
 
+// Returns a promise.
 module.exports.check_java = function() {
     if(process.env.JAVA_HOME) {
-        var test = shell.exec('java', {silent:true, async:false});
-        if(test.code > 0) {
-            console.error('ERROR : executing command \'java\', make sure you java environment is set up. Including your JDK and JRE.');
-            return false;
-        }
-        return true;
+        var d = Q.defer();
+        child_process.exec('java', function(err, stdout, stderr) {
+            if(err) d.reject(new Error('ERROR : executing command \'java\', make sure you java environment is set up. Including your JDK and JRE.'));
+            else d.resolve();
+        });
+        return d.promise;
     } else {
-        console.error('ERROR : Make sure JAVA_HOME is set, as well as paths to your JDK and JRE for java.');
-        return false;
+        return Q.reject(new Error('ERROR : Make sure JAVA_HOME is set, as well as paths to your JDK and JRE for java.'));
     }
 }
 
+// Returns a promise.
 module.exports.check_android = function() {
     var valid_target = this.get_target();
-    var targets = shell.exec('android list targets', {silent:true, async:false});
+    var d = Q.defer();
+    child_process.exec('android list targets', function(err, stdout, stderr) {
+        if (err) d.reject(stderr);
+        else d.resolve(stdout);
+    });
 
-    if(targets.code > 0 && targets.output.match(/command\snot\sfound/)) {
-        console.error('The command \"android\" failed. Make sure you have the latest Android SDK installed, and the \"android\" command (inside the tools/ folder) is added to your path.');
-        return false;
-    } else if(!targets.output.match(valid_target)) {
-        console.error('Please install Android target ' + valid_target.split('-')[1] + ' (the Android newest SDK). Make sure you have the latest Android tools installed as well. Run \"android\" from your command-line to install/update any missing SDKs or tools.');
-        return false;
-    }
-    return true;
+    return d.promise.then(function(output) {
+        if (!output.match(valid_target)) {
+            return Q.reject(new Error('Please install Android target ' + valid_target.split('-')[1] + ' (the Android newest SDK). Make sure you have the latest Android tools installed as well. Run \"android\" from your command-line to install/update any missing SDKs or tools.'));
+        }
+        return Q();
+    }, function(stderr) {
+        if (stderr.match(/command\snot\sfound/)) {
+            return Q.reject(new Error('The command \"android\" failed. Make sure you have the latest Android SDK installed, and the \"android\" command (inside the tools/ folder) is added to your path.'));
+        } else {
+            return Q.reject(new Error('An error occurred while listing Android targets'));
+        }
+    });
 }
 
+// Returns a promise.
 module.exports.run = function() {
-    return this.check_ant() && this.check_java && this.check_android();
+    return Q.all([this.check_ant(), this.check_java, this.check_android()]);
 }

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/lib/create.js
----------------------------------------------------------------------
diff --git a/bin/lib/create.js b/bin/lib/create.js
index f34a244..9ba460d 100755
--- a/bin/lib/create.js
+++ b/bin/lib/create.js
@@ -19,27 +19,25 @@
        under the License.
 */
 var shell = require('shelljs'),
+    child_process = require('child_process'),
+    Q     = require('q'),
     path  = require('path'),
     fs    = require('fs'),
     check_reqs = require('./check_reqs'),
     ROOT    = path.join(__dirname, '..', '..');
 
-function exec(command) {
-    var result;
+// Returns a promise.
+function exec(command, opt_cwd) {
+    var d = Q.defer();
     try {
-        result = shell.exec(command, {silent:false, async:false});
+        child_process.exec(command, { cwd: opt_cwd }, function(err, stdout, stderr) {
+            if (err) d.reject(err);
+            else d.resolve(stdout);
+        });
     } catch(e) {
-        console.error('Command error on execuation : ' + command);
-        console.error(e);
-        process.exit(2);
-    }
-    if(result && result.code > 0) {
-        console.error('Command failed to execute : ' + command);
-        console.error(result.output);
-        process.exit(2);
-    } else {
-        return result;
+        return Q.reject('Command error on execution: ' + command + '\n' + e);
     }
+    return d.promise;
 }
 
 function setShellFatal(value, func) {
@@ -49,19 +47,20 @@ function setShellFatal(value, func) {
     shell.config.fatal = oldVal;
 }
 
+// Returns a promise.
 function ensureJarIsBuilt(version, target_api) {
     var isDevVersion = /-dev$/.test(version);
     if (isDevVersion || !fs.existsSync(path.join(ROOT, 'framework', 'cordova-' + version + '.jar')) && fs.existsSync(path.join(ROOT, 'framework'))) {
         var valid_target = check_reqs.get_target();
         console.log('Building cordova-' + version + '.jar');
         // update the cordova-android framework for the desired target
-        exec('android --silent update lib-project --target "' + target_api + '" --path "' + path.join(ROOT, 'framework') + '"');
-        // compile cordova.js and cordova.jar
-        var cwd = process.cwd();
-        process.chdir(path.join(ROOT, 'framework'));
-        exec('ant jar');
-        process.chdir(cwd);
+        return exec('android --silent update lib-project --target "' + target_api + '" --path "' + path.join(ROOT, 'framework') + '"')
+        .then(function() {
+            // compile cordova.js and cordova.jar
+            return exec('ant jar', path.join(ROOT, 'framework'));
+        });
     }
+    return Q();
 }
 
 function copyJsAndJar(projectPath, version) {
@@ -100,6 +99,8 @@ function copyScripts(projectPath) {
  *   - `package_name`{String} Package name, following reverse-domain style convention.
  *   - `project_name` 	{String} Project name.
  *   - 'project_template_dir' {String} Path to project template (override).
+ *
+ * Returns a promise.
  */
 
 exports.createProject = function(project_path, package_name, project_name, project_template_dir) {
@@ -123,72 +124,72 @@ exports.createProject = function(project_path, package_name, project_name, proje
 
     // Check if project already exists
     if(fs.existsSync(project_path)) {
-        console.error('Project already exists! Delete and recreate');
-        process.exit(2);
+        return Q.reject('Project already exists! Delete and recreate');
     }
 
     if (!/[a-zA-Z0-9_]+\.[a-zA-Z0-9_](.[a-zA-Z0-9_])*/.test(package_name)) {
-        console.error('Package name must look like: com.company.Name');
-        process.exit(2);
+        return Q.reject('Package name must look like: com.company.Name');
     }
 
     // Check that requirements are met and proper targets are installed
-    if(!check_reqs.run()) {
-        process.exit(2);
-    }
-
-    // Log the given values for the project
-    console.log('Creating Cordova project for the Android platform:');
-    console.log('\tPath: ' + project_path);
-    console.log('\tPackage: ' + package_name);
-    console.log('\tName: ' + project_name);
-    console.log('\tAndroid target: ' + target_api);
-
-    // build from source. distro should have these files
-    ensureJarIsBuilt(VERSION, target_api);
-
-    console.log('Copying template files...');
-
-    setShellFatal(true, function() {
-        // copy project template
-        shell.cp('-r', path.join(project_template_dir, 'assets'), project_path);
-        shell.cp('-r', path.join(project_template_dir, 'res'), project_path);
-        // Manually create directories that would be empty within the template (since git doesn't track directories).
-        shell.mkdir(path.join(project_path, 'libs'));
-
-        // copy cordova.js, cordova.jar and res/xml
-        shell.cp('-r', path.join(ROOT, 'framework', 'res', 'xml'), path.join(project_path, 'res'));
-        copyJsAndJar(project_path, VERSION);
-
-        // interpolate the activity name and package
-        shell.mkdir('-p', activity_dir);
-        shell.cp('-f', path.join(project_template_dir, 'Activity.java'), activity_path);
-        shell.sed('-i', /__ACTIVITY__/, safe_activity_name, activity_path);
-        shell.sed('-i', /__NAME__/, project_name, path.join(project_path, 'res', 'values', 'strings.xml'));
-        shell.sed('-i', /__ID__/, package_name, activity_path);
-
-        shell.cp('-f', path.join(project_template_dir, 'AndroidManifest.xml'), manifest_path);
-        shell.sed('-i', /__ACTIVITY__/, safe_activity_name, manifest_path);
-        shell.sed('-i', /__PACKAGE__/, package_name, manifest_path);
-        shell.sed('-i', /__APILEVEL__/, target_api.split('-')[1], manifest_path);
-        copyScripts(project_path);
+    return check_reqs.run()
+    .then(function() {
+        // Log the given values for the project
+        console.log('Creating Cordova project for the Android platform:');
+        console.log('\tPath: ' + project_path);
+        console.log('\tPackage: ' + package_name);
+        console.log('\tName: ' + project_name);
+        console.log('\tAndroid target: ' + target_api);
+
+        // build from source. distro should have these files
+        return ensureJarIsBuilt(VERSION, target_api);
+    }).then(function() {
+        console.log('Copying template files...');
+
+        setShellFatal(true, function() {
+            // copy project template
+            shell.cp('-r', path.join(project_template_dir, 'assets'), project_path);
+            shell.cp('-r', path.join(project_template_dir, 'res'), project_path);
+            // Manually create directories that would be empty within the template (since git doesn't track directories).
+            shell.mkdir(path.join(project_path, 'libs'));
+
+            // copy cordova.js, cordova.jar and res/xml
+            shell.cp('-r', path.join(ROOT, 'framework', 'res', 'xml'), path.join(project_path, 'res'));
+            copyJsAndJar(project_path, VERSION);
+
+            // interpolate the activity name and package
+            shell.mkdir('-p', activity_dir);
+            shell.cp('-f', path.join(project_template_dir, 'Activity.java'), activity_path);
+            shell.sed('-i', /__ACTIVITY__/, safe_activity_name, activity_path);
+            shell.sed('-i', /__NAME__/, project_name, path.join(project_path, 'res', 'values', 'strings.xml'));
+            shell.sed('-i', /__ID__/, package_name, activity_path);
+
+            shell.cp('-f', path.join(project_template_dir, 'AndroidManifest.xml'), manifest_path);
+            shell.sed('-i', /__ACTIVITY__/, safe_activity_name, manifest_path);
+            shell.sed('-i', /__PACKAGE__/, package_name, manifest_path);
+            shell.sed('-i', /__APILEVEL__/, target_api.split('-')[1], manifest_path);
+            copyScripts(project_path);
+        });
+        // Link it to local android install.
+        console.log('Running "android update project"');
+        return exec('android --silent update project --target "'+target_api+'" --path "'+ project_path+'"');
+    }).then(function() {
+        console.log('Project successfully created.');
     });
-    // Link it to local android install.
-    console.log('Running "android update project"');
-    exec('android --silent update project --target "'+target_api+'" --path "'+ project_path+'"');
-    console.log('Project successfully created.');
 }
 
+// Returns a promise.
 exports.updateProject = function(projectPath) {
     // Check that requirements are met and proper targets are installed
-    if (!check_reqs.run()) {
-        process.exit(2);
-    }
-    var version = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf-8').trim();
-    var target_api = check_reqs.get_target();
-    ensureJarIsBuilt(version, target_api);
-    copyJsAndJar(projectPath, version);
-    copyScripts(projectPath);
-    console.log('Android project is now at version ' + version);
+    return check_reqs.run()
+    .then(function() {
+        var version = fs.readFileSync(path.join(ROOT, 'VERSION'), 'utf-8').trim();
+        var target_api = check_reqs.get_target();
+        return ensureJarIsBuilt(version, target_api);
+    }).then(function() {
+        copyJsAndJar(projectPath, version);
+        copyScripts(projectPath);
+        console.log('Android project is now at version ' + version);
+    });
 };
 

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/node_modules/q/CONTRIBUTING.md
----------------------------------------------------------------------
diff --git a/bin/node_modules/q/CONTRIBUTING.md b/bin/node_modules/q/CONTRIBUTING.md
new file mode 100644
index 0000000..500ab17
--- /dev/null
+++ b/bin/node_modules/q/CONTRIBUTING.md
@@ -0,0 +1,40 @@
+
+For pull requests:
+
+-   Be consistent with prevalent style and design decisions.
+-   Add a Jasmine spec to `specs/q-spec.js`.
+-   Use `npm test` to avoid regressions.
+-   Run tests in `q-spec/run.html` in as many supported browsers as you
+    can find the will to deal with.
+-   Do not build minified versions; we do this each release.
+-   If you would be so kind, add a note to `CHANGES.md` in an
+    appropriate section:
+
+    -   `Next Major Version` if it introduces backward incompatibilities
+        to code in the wild using documented features.
+    -   `Next Minor Version` if it adds a new feature.
+    -   `Next Patch Version` if it fixes a bug.
+
+For releases:
+
+-   Run `npm test`.
+-   Run tests in `q-spec/run.html` in a representative sample of every
+    browser under the sun.
+-   Run `npm run cover` and make sure you're happy with the results.
+-   Run `npm run minify` and be sure to commit the resulting `q.min.js`.
+-   Note the Gzipped size output by the previous command, and update
+    `README.md` if it has changed to 1 significant digit.
+-   Stash any local changes.
+-   Update `CHANGES.md` to reflect all changes in the differences
+    between `HEAD` and the previous tagged version.  Give credit where
+    credit is due.
+-   Update `README.md` to address all new, non-experimental features.
+-   Update the API reference on the Wiki to reflect all non-experimental
+    features.
+-   Use `npm version major|minor|patch` to update `package.json`,
+    commit, and tag the new version.
+-   Use `npm publish` to send up a new release.
+-   Send an email to the q-continuum mailing list announcing the new
+    release and the notes from the change log.  This helps folks
+    maintaining other package ecosystems.
+

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/node_modules/q/LICENSE
----------------------------------------------------------------------
diff --git a/bin/node_modules/q/LICENSE b/bin/node_modules/q/LICENSE
new file mode 100644
index 0000000..76c5fe4
--- /dev/null
+++ b/bin/node_modules/q/LICENSE
@@ -0,0 +1,19 @@
+
+Copyright 2009–2012 Kristopher Michael Kowal. All rights reserved.
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/node_modules/q/README.md
----------------------------------------------------------------------
diff --git a/bin/node_modules/q/README.md b/bin/node_modules/q/README.md
new file mode 100644
index 0000000..c0f513c
--- /dev/null
+++ b/bin/node_modules/q/README.md
@@ -0,0 +1,813 @@
+[![Build Status](https://secure.travis-ci.org/kriskowal/q.png?branch=master)](http://travis-ci.org/kriskowal/q)
+
+<a href="http://promises-aplus.github.com/promises-spec">
+    <img src="http://promises-aplus.github.com/promises-spec/assets/logo-small.png"
+         align="right" alt="Promises/A+ logo" />
+</a>
+
+If a function cannot return a value or throw an exception without
+blocking, it can return a promise instead.  A promise is an object
+that represents the return value or the thrown exception that the
+function may eventually provide.  A promise can also be used as a
+proxy for a [remote object][Q-Connection] to overcome latency.
+
+[Q-Connection]: https://github.com/kriskowal/q-connection
+
+On the first pass, promises can mitigate the “[Pyramid of
+Doom][POD]”: the situation where code marches to the right faster
+than it marches forward.
+
+[POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/
+
+```javascript
+step1(function (value1) {
+    step2(value1, function(value2) {
+        step3(value2, function(value3) {
+            step4(value3, function(value4) {
+                // Do something with value4
+            });
+        });
+    });
+});
+```
+
+With a promise library, you can flatten the pyramid.
+
+```javascript
+Q.fcall(promisedStep1)
+.then(promisedStep2)
+.then(promisedStep3)
+.then(promisedStep4)
+.then(function (value4) {
+    // Do something with value4
+})
+.catch(function (error) {
+    // Handle any error from all above steps
+})
+.done();
+```
+
+With this approach, you also get implicit error propagation, just like `try`,
+`catch`, and `finally`.  An error in `promisedStep1` will flow all the way to
+the `catch` function, where it’s caught and handled.  (Here `promisedStepN` is
+a version of `stepN` that returns a promise.)
+
+The callback approach is called an “inversion of control”.
+A function that accepts a callback instead of a return value
+is saying, “Don’t call me, I’ll call you.”.  Promises
+[un-invert][IOC] the inversion, cleanly separating the input
+arguments from control flow arguments.  This simplifies the
+use and creation of API’s, particularly variadic,
+rest and spread arguments.
+
+[IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript
+
+
+## Getting Started
+
+The Q module can be loaded as:
+
+-   A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and
+    gzipped.
+-   A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as
+    the [q](https://npmjs.org/package/q) package
+-   An AMD module
+-   A [component](https://github.com/component/component) as ``microjs/q``
+-   Using [bower](http://bower.io/) as ``q``
+-   Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q)
+
+Q can exchange promises with jQuery, Dojo, When.js, WinJS, and more.
+
+## Resources
+
+Our [wiki][] contains a number of useful resources, including:
+
+- A method-by-method [Q API reference][reference].
+- A growing [examples gallery][examples], showing how Q can be used to make
+  everything better. From XHR to database access to accessing the Flickr API,
+  Q is there for you.
+- There are many libraries that produce and consume Q promises for everything
+  from file system/database access or RPC to templating. For a list of some of
+  the more popular ones, see [Libraries][].
+- If you want materials that introduce the promise concept generally, and the
+  below tutorial isn't doing it for you, check out our collection of
+  [presentations, blog posts, and podcasts][resources].
+- A guide for those [coming from jQuery's `$.Deferred`][jquery].
+
+We'd also love to have you join the Q-Continuum [mailing list][].
+
+[wiki]: https://github.com/kriskowal/q/wiki
+[reference]: https://github.com/kriskowal/q/wiki/API-Reference
+[examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery
+[Libraries]: https://github.com/kriskowal/q/wiki/Libraries
+[resources]: https://github.com/kriskowal/q/wiki/General-Promise-Resources
+[jquery]: https://github.com/kriskowal/q/wiki/Coming-from-jQuery
+[mailing list]: https://groups.google.com/forum/#!forum/q-continuum
+
+
+## Tutorial
+
+Promises have a ``then`` method, which you can use to get the eventual
+return value (fulfillment) or thrown exception (rejection).
+
+```javascript
+promiseMeSomething()
+.then(function (value) {
+}, function (reason) {
+});
+```
+
+If ``promiseMeSomething`` returns a promise that gets fulfilled later
+with a return value, the first function (the fulfillment handler) will be
+called with the value.  However, if the ``promiseMeSomething`` function
+gets rejected later by a thrown exception, the second function (the
+rejection handler) will be called with the exception.
+
+Note that resolution of a promise is always asynchronous: that is, the
+fulfillment or rejection handler will always be called in the next turn of the
+event loop (i.e. `process.nextTick` in Node). This gives you a nice
+guarantee when mentally tracing the flow of your code, namely that
+``then`` will always return before either handler is executed.
+
+In this tutorial, we begin with how to consume and work with promises. We'll
+talk about how to create them, and thus create functions like
+`promiseMeSomething` that return promises, [below](#the-beginning).
+
+
+### Propagation
+
+The ``then`` method returns a promise, which in this example, I’m
+assigning to ``outputPromise``.
+
+```javascript
+var outputPromise = getInputPromise()
+.then(function (input) {
+}, function (reason) {
+});
+```
+
+The ``outputPromise`` variable becomes a new promise for the return
+value of either handler.  Since a function can only either return a
+value or throw an exception, only one handler will ever be called and it
+will be responsible for resolving ``outputPromise``.
+
+-   If you return a value in a handler, ``outputPromise`` will get
+    fulfilled.
+
+-   If you throw an exception in a handler, ``outputPromise`` will get
+    rejected.
+
+-   If you return a **promise** in a handler, ``outputPromise`` will
+    “become” that promise.  Being able to become a new promise is useful
+    for managing delays, combining results, or recovering from errors.
+
+If the ``getInputPromise()`` promise gets rejected and you omit the
+rejection handler, the **error** will go to ``outputPromise``:
+
+```javascript
+var outputPromise = getInputPromise()
+.then(function (value) {
+});
+```
+
+If the input promise gets fulfilled and you omit the fulfillment handler, the
+**value** will go to ``outputPromise``:
+
+```javascript
+var outputPromise = getInputPromise()
+.then(null, function (error) {
+});
+```
+
+Q promises provide a ``fail`` shorthand for ``then`` when you are only
+interested in handling the error:
+
+```javascript
+var outputPromise = getInputPromise()
+.fail(function (error) {
+});
+```
+
+If you are writing JavaScript for modern engines only or using
+CoffeeScript, you may use `catch` instead of `fail`.
+
+Promises also have a ``fin`` function that is like a ``finally`` clause.
+The final handler gets called, with no arguments, when the promise
+returned by ``getInputPromise()`` either returns a value or throws an
+error.  The value returned or error thrown by ``getInputPromise()``
+passes directly to ``outputPromise`` unless the final handler fails, and
+may be delayed if the final handler returns a promise.
+
+```javascript
+var outputPromise = getInputPromise()
+.fin(function () {
+    // close files, database connections, stop servers, conclude tests
+});
+```
+
+-   If the handler returns a value, the value is ignored
+-   If the handler throws an error, the error passes to ``outputPromise``
+-   If the handler returns a promise, ``outputPromise`` gets postponed.  The
+    eventual value or error has the same effect as an immediate return
+    value or thrown error: a value would be ignored, an error would be
+    forwarded.
+
+If you are writing JavaScript for modern engines only or using
+CoffeeScript, you may use `finally` instead of `fin`.
+
+### Chaining
+
+There are two ways to chain promises.  You can chain promises either
+inside or outside handlers.  The next two examples are equivalent.
+
+```javascript
+return getUsername()
+.then(function (username) {
+    return getUser(username)
+    .then(function (user) {
+        // if we get here without an error,
+        // the value returned here
+        // or the exception thrown here
+        // resolves the promise returned
+        // by the first line
+    })
+});
+```
+
+```javascript
+return getUsername()
+.then(function (username) {
+    return getUser(username);
+})
+.then(function (user) {
+    // if we get here without an error,
+    // the value returned here
+    // or the exception thrown here
+    // resolves the promise returned
+    // by the first line
+});
+```
+
+The only difference is nesting.  It’s useful to nest handlers if you
+need to capture multiple input values in your closure.
+
+```javascript
+function authenticate() {
+    return getUsername()
+    .then(function (username) {
+        return getUser(username);
+    })
+    // chained because we will not need the user name in the next event
+    .then(function (user) {
+        return getPassword()
+        // nested because we need both user and password next
+        .then(function (password) {
+            if (user.passwordHash !== hash(password)) {
+                throw new Error("Can't authenticate");
+            }
+        });
+    });
+}
+```
+
+
+### Combination
+
+You can turn an array of promises into a promise for the whole,
+fulfilled array using ``all``.
+
+```javascript
+return Q.all([
+    eventualAdd(2, 2),
+    eventualAdd(10, 20)
+]);
+```
+
+If you have a promise for an array, you can use ``spread`` as a
+replacement for ``then``.  The ``spread`` function “spreads” the
+values over the arguments of the fulfillment handler.  The rejection handler
+will get called at the first sign of failure.  That is, whichever of
+the recived promises fails first gets handled by the rejection handler.
+
+```javascript
+function eventualAdd(a, b) {
+    return Q.spread([a, b], function (a, b) {
+        return a + b;
+    })
+}
+```
+
+But ``spread`` calls ``all`` initially, so you can skip it in chains.
+
+```javascript
+return getUsername()
+.then(function (username) {
+    return [username, getUser(username)];
+})
+.spread(function (username, user) {
+});
+```
+
+The ``all`` function returns a promise for an array of values.  When this
+promise is fulfilled, the array contains the fulfillment values of the original
+promises, in the same order as those promises.  If one of the given promises
+is rejected, the returned promise is immediately rejected, not waiting for the
+rest of the batch.  If you want to wait for all of the promises to either be
+fulfilled or rejected, you can use ``allSettled``.
+
+```javascript
+Q.allSettled(promises)
+.then(function (results) {
+    results.forEach(function (result) {
+        if (result.state === "fulfilled") {
+            var value = result.value;
+        } else {
+            var reason = result.reason;
+        }
+    });
+});
+```
+
+
+### Sequences
+
+If you have a number of promise-producing functions that need
+to be run sequentially, you can of course do so manually:
+
+```javascript
+return foo(initialVal).then(bar).then(baz).then(qux);
+```
+
+However, if you want to run a dynamically constructed sequence of
+functions, you'll want something like this:
+
+```javascript
+var funcs = [foo, bar, baz, qux];
+
+var result = Q(initialVal);
+funcs.forEach(function (f) {
+    result = result.then(f);
+});
+return result;
+```
+
+You can make this slightly more compact using `reduce`:
+
+```javascript
+return funcs.reduce(function (soFar, f) {
+    return soFar.then(f);
+}, Q(initialVal));
+```
+
+Or, you could use th ultra-compact version:
+
+```javascript
+return funcs.reduce(Q.when, Q());
+```
+
+### Handling Errors
+
+One sometimes-unintuive aspect of promises is that if you throw an
+exception in the fulfillment handler, it will not be be caught by the error
+handler.
+
+```javascript
+return foo()
+.then(function (value) {
+    throw new Error("Can't bar.");
+}, function (error) {
+    // We only get here if "foo" fails
+});
+```
+
+To see why this is, consider the parallel between promises and
+``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error
+handler represents a ``catch`` for ``foo()``, while the fulfillment handler
+represents code that happens *after* the ``try``/``catch`` block.
+That code then needs its own ``try``/``catch`` block.
+
+In terms of promises, this means chaining your rejection handler:
+
+```javascript
+return foo()
+.then(function (value) {
+    throw new Error("Can't bar.");
+})
+.fail(function (error) {
+    // We get here with either foo's error or bar's error
+});
+```
+
+### Progress Notification
+
+It's possible for promises to report their progress, e.g. for tasks that take a
+long time like a file upload. Not all promises will implement progress
+notifications, but for those that do, you can consume the progress values using
+a third parameter to ``then``:
+
+```javascript
+return uploadFile()
+.then(function () {
+    // Success uploading the file
+}, function (err) {
+    // There was an error, and we get the reason for error
+}, function (progress) {
+    // We get notified of the upload's progress as it is executed
+});
+```
+
+Like `fail`, Q also provides a shorthand for progress callbacks
+called `progress`:
+
+```javascript
+return uploadFile().progress(function (progress) {
+    // We get notified of the upload's progress
+});
+```
+
+### The End
+
+When you get to the end of a chain of promises, you should either
+return the last promise or end the chain.  Since handlers catch
+errors, it’s an unfortunate pattern that the exceptions can go
+unobserved.
+
+So, either return it,
+
+```javascript
+return foo()
+.then(function () {
+    return "bar";
+});
+```
+
+Or, end it.
+
+```javascript
+foo()
+.then(function () {
+    return "bar";
+})
+.done();
+```
+
+Ending a promise chain makes sure that, if an error doesn’t get
+handled before the end, it will get rethrown and reported.
+
+This is a stopgap. We are exploring ways to make unhandled errors
+visible without any explicit handling.
+
+
+### The Beginning
+
+Everything above assumes you get a promise from somewhere else.  This
+is the common case.  Every once in a while, you will need to create a
+promise from scratch.
+
+#### Using ``Q.fcall``
+
+You can create a promise from a value using ``Q.fcall``.  This returns a
+promise for 10.
+
+```javascript
+return Q.fcall(function () {
+    return 10;
+});
+```
+
+You can also use ``fcall`` to get a promise for an exception.
+
+```javascript
+return Q.fcall(function () {
+    throw new Error("Can't do it");
+});
+```
+
+As the name implies, ``fcall`` can call functions, or even promised
+functions.  This uses the ``eventualAdd`` function above to add two
+numbers.
+
+```javascript
+return Q.fcall(eventualAdd, 2, 2);
+```
+
+
+#### Using Deferreds
+
+If you have to interface with asynchronous functions that are callback-based
+instead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and
+friends). But much of the time, the solution will be to use *deferreds*.
+
+```javascript
+var deferred = Q.defer();
+FS.readFile("foo.txt", "utf-8", function (error, text) {
+    if (error) {
+        deferred.reject(new Error(error));
+    } else {
+        deferred.resolve(text);
+    }
+});
+return deferred.promise;
+```
+
+Note that a deferred can be resolved with a value or a promise.  The
+``reject`` function is a shorthand for resolving with a rejected
+promise.
+
+```javascript
+// this:
+deferred.reject(new Error("Can't do it"));
+
+// is shorthand for:
+var rejection = Q.fcall(function () {
+    throw new Error("Can't do it");
+});
+deferred.resolve(rejection);
+```
+
+This is a simplified implementation of ``Q.delay``.
+
+```javascript
+function delay(ms) {
+    var deferred = Q.defer();
+    setTimeout(deferred.resolve, ms);
+    return deferred.promise;
+}
+```
+
+This is a simplified implementation of ``Q.timeout``
+
+```javascript
+function timeout(promise, ms) {
+    var deferred = Q.defer();
+    Q.when(promise, deferred.resolve);
+    delay(ms).then(function () {
+        deferred.reject(new Error("Timed out"));
+    });
+    return deferred.promise;
+}
+```
+
+Finally, you can send a progress notification to the promise with
+``deferred.notify``.
+
+For illustration, this is a wrapper for XML HTTP requests in the browser. Note
+that a more [thorough][XHR] implementation would be in order in practice.
+
+[XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js#L29-L73
+
+```javascript
+function requestOkText(url) {
+    var request = new XMLHttpRequest();
+    var deferred = Q.defer();
+
+    request.open("GET", url, true);
+    request.onload = onload;
+    request.onerror = onerror;
+    request.onprogress = onprogress;
+    request.send();
+
+    function onload() {
+        if (request.status === 200) {
+            deferred.resolve(request.responseText);
+        } else {
+            deferred.reject(new Error("Status code was " + request.status));
+        }
+    }
+
+    function onerror() {
+        deferred.reject(new Error("Can't XHR " + JSON.stringify(url)));
+    }
+
+    function onprogress(event) {
+        deferred.notify(event.loaded / event.total);
+    }
+
+    return deferred.promise;
+}
+```
+
+Below is an example of how to use this ``requestOkText`` function:
+
+```javascript
+requestOkText("http://localhost:3000")
+.then(function (responseText) {
+    // If the HTTP response returns 200 OK, log the response text.
+    console.log(responseText);
+}, function (error) {
+    // If there's an error or a non-200 status code, log the error.
+    console.error(error);
+}, function (progress) {
+    // Log the progress as it comes in.
+    console.log("Request progress: " + Math.round(progress * 100) + "%");
+});
+```
+
+### The Middle
+
+If you are using a function that may return a promise, but just might
+return a value if it doesn’t need to defer, you can use the “static”
+methods of the Q library.
+
+The ``when`` function is the static equivalent for ``then``.
+
+```javascript
+return Q.when(valueOrPromise, function (value) {
+}, function (error) {
+});
+```
+
+All of the other methods on a promise have static analogs with the
+same name.
+
+The following are equivalent:
+
+```javascript
+return Q.all([a, b]);
+```
+
+```javascript
+return Q.fcall(function () {
+    return [a, b];
+})
+.all();
+```
+
+When working with promises provided by other libraries, you should
+convert it to a Q promise.  Not all promise libraries make the same
+guarantees as Q and certainly don’t provide all of the same methods.
+Most libraries only provide a partially functional ``then`` method.
+This thankfully is all we need to turn them into vibrant Q promises.
+
+```javascript
+return Q($.ajax(...))
+.then(function () {
+});
+```
+
+If there is any chance that the promise you receive is not a Q promise
+as provided by your library, you should wrap it using a Q function.
+You can even use ``Q.invoke`` as a shorthand.
+
+```javascript
+return Q.invoke($, 'ajax', ...)
+.then(function () {
+});
+```
+
+
+### Over the Wire
+
+A promise can serve as a proxy for another object, even a remote
+object.  There are methods that allow you to optimistically manipulate
+properties or call functions.  All of these interactions return
+promises, so they can be chained.
+
+```
+direct manipulation         using a promise as a proxy
+--------------------------  -------------------------------
+value.foo                   promise.get("foo")
+value.foo = value           promise.put("foo", value)
+delete value.foo            promise.del("foo")
+value.foo(...args)          promise.post("foo", [args])
+value.foo(...args)          promise.invoke("foo", ...args)
+value(...args)              promise.fapply([args])
+value(...args)              promise.fcall(...args)
+```
+
+If the promise is a proxy for a remote object, you can shave
+round-trips by using these functions instead of ``then``.  To take
+advantage of promises for remote objects, check out [Q-Connection][].
+
+[Q-Connection]: https://github.com/kriskowal/q-connection
+
+Even in the case of non-remote objects, these methods can be used as
+shorthand for particularly-simple fulfillment handlers. For example, you
+can replace
+
+```javascript
+return Q.fcall(function () {
+    return [{ foo: "bar" }, { foo: "baz" }];
+})
+.then(function (value) {
+    return value[0].foo;
+});
+```
+
+with
+
+```javascript
+return Q.fcall(function () {
+    return [{ foo: "bar" }, { foo: "baz" }];
+})
+.get(0)
+.get("foo");
+```
+
+
+### Adapting Node
+
+If you're working with functions that make use of the Node.js callback pattern,
+where callbacks are in the form of `function(err, result)`, Q provides a few
+useful utility functions for converting between them. The most straightforward
+are probably `Q.nfcall` and `Q.nfapply` ("Node function call/apply") for calling
+Node.js-style functions and getting back a promise:
+
+```javascript
+return Q.nfcall(FS.readFile, "foo.txt", "utf-8");
+return Q.nfapply(FS.readFile, ["foo.txt", "utf-8"]);
+```
+
+If you are working with methods, instead of simple functions, you can easily
+run in to the usual problems where passing a method to another function—like
+`Q.nfcall`—"un-binds" the method from its owner. To avoid this, you can either
+use `Function.prototype.bind` or some nice shortcut methods we provide:
+
+```javascript
+return Q.ninvoke(redisClient, "get", "user:1:id");
+return Q.npost(redisClient, "get", ["user:1:id"]);
+```
+
+You can also create reusable wrappers with `Q.denodeify` or `Q.nbind`:
+
+```javascript
+var readFile = Q.denodeify(FS.readFile);
+return readFile("foo.txt", "utf-8");
+
+var redisClientGet = Q.nbind(redisClient.get, redisClient);
+return redisClientGet("user:1:id");
+```
+
+Finally, if you're working with raw deferred objects, there is a
+`makeNodeResolver` method on deferreds that can be handy:
+
+```javascript
+var deferred = Q.defer();
+FS.readFile("foo.txt", "utf-8", deferred.makeNodeResolver());
+return deferred.promise;
+```
+
+### Long Stack Traces
+
+Q comes with optional support for “long stack traces,” wherein the `stack`
+property of `Error` rejection reasons is rewritten to be traced along
+asynchronous jumps instead of stopping at the most recent one. As an example:
+
+```js
+function theDepthsOfMyProgram() {
+  Q.delay(100).done(function explode() {
+    throw new Error("boo!");
+  });
+}
+
+theDepthsOfMyProgram();
+```
+
+usually would give a rather unhelpful stack trace looking something like
+
+```
+Error: boo!
+    at explode (/path/to/test.js:3:11)
+    at _fulfilled (/path/to/test.js:q:54)
+    at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30)
+    at makePromise.promise.promiseDispatch (/path/to/q.js:496:13)
+    at pending (/path/to/q.js:397:39)
+    at process.startup.processNextTick.process._tickCallback (node.js:244:9)
+```
+
+But, if you turn this feature on by setting
+
+```js
+Q.longStackSupport = true;
+```
+
+then the above code gives a nice stack trace to the tune of
+
+```
+Error: boo!
+    at explode (/path/to/test.js:3:11)
+From previous event:
+    at theDepthsOfMyProgram (/path/to/test.js:2:16)
+    at Object.<anonymous> (/path/to/test.js:7:1)
+```
+
+Note how you can see the the function that triggered the async operation in the
+stack trace! This is very helpful for debugging, as otherwise you end up getting
+only the first line, plus a bunch of Q internals, with no sign of where the
+operation started.
+
+This feature does come with somewhat-serious performance and memory overhead,
+however. If you're working with lots of promises, or trying to scale a server
+to many users, you should probably keep it off. But in development, go for it!
+
+## Tests
+
+You can view the results of the Q test suite [in your browser][tests]!
+
+[tests]: https://rawgithub.com/kriskowal/q/master/spec/q-spec.html
+
+## License
+
+Copyright 2009–2013 Kristopher Michael Kowal
+MIT License (enclosed)
+

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/node_modules/q/benchmark/compare-with-callbacks.js
----------------------------------------------------------------------
diff --git a/bin/node_modules/q/benchmark/compare-with-callbacks.js b/bin/node_modules/q/benchmark/compare-with-callbacks.js
new file mode 100644
index 0000000..97f1298
--- /dev/null
+++ b/bin/node_modules/q/benchmark/compare-with-callbacks.js
@@ -0,0 +1,71 @@
+"use strict";
+
+var Q = require("../q");
+var fs = require("fs");
+
+suite("A single simple async operation", function () {
+    bench("with an immediately-fulfilled promise", function (done) {
+        Q().then(done);
+    });
+
+    bench("with direct setImmediate usage", function (done) {
+        setImmediate(done);
+    });
+
+    bench("with direct setTimeout(…, 0)", function (done) {
+        setTimeout(done, 0);
+    });
+});
+
+suite("A fs.readFile", function () {
+    var denodeified = Q.denodeify(fs.readFile);
+
+    set("iterations", 1000);
+    set("delay", 1000);
+
+    bench("directly, with callbacks", function (done) {
+        fs.readFile(__filename, done);
+    });
+
+    bench("with Q.nfcall", function (done) {
+        Q.nfcall(fs.readFile, __filename).then(done);
+    });
+
+    bench("with a Q.denodeify'ed version", function (done) {
+        denodeified(__filename).then(done);
+    });
+
+    bench("with manual usage of deferred.makeNodeResolver", function (done) {
+        var deferred = Q.defer();
+        fs.readFile(__filename, deferred.makeNodeResolver());
+        deferred.promise.then(done);
+    });
+});
+
+suite("1000 operations in parallel", function () {
+    function makeCounter(desiredCount, ultimateCallback) {
+        var soFar = 0;
+        return function () {
+            if (++soFar === desiredCount) {
+                ultimateCallback();
+            }
+        };
+    }
+    var numberOfOps = 1000;
+
+    bench("with immediately-fulfilled promises", function (done) {
+        var counter = makeCounter(numberOfOps, done);
+
+        for (var i = 0; i < numberOfOps; ++i) {
+            Q().then(counter);
+        }
+    });
+
+    bench("with direct setImmediate usage", function (done) {
+        var counter = makeCounter(numberOfOps, done);
+
+        for (var i = 0; i < numberOfOps; ++i) {
+            setImmediate(counter);
+        }
+    });
+});

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/node_modules/q/benchmark/scenarios.js
----------------------------------------------------------------------
diff --git a/bin/node_modules/q/benchmark/scenarios.js b/bin/node_modules/q/benchmark/scenarios.js
new file mode 100644
index 0000000..7c18564
--- /dev/null
+++ b/bin/node_modules/q/benchmark/scenarios.js
@@ -0,0 +1,36 @@
+"use strict";
+
+var Q = require("../q");
+
+suite("Chaining", function () {
+    var numberToChain = 1000;
+
+    bench("Chaining many already-fulfilled promises together", function (done) {
+        var currentPromise = Q();
+        for (var i = 0; i < numberToChain; ++i) {
+            currentPromise = currentPromise.then(function () {
+                return Q();
+            });
+        }
+
+        currentPromise.then(done);
+    });
+
+    bench("Chaining and then fulfilling the end of the chain", function (done) {
+        var deferred = Q.defer();
+
+        var currentPromise = deferred.promise;
+        for (var i = 0; i < numberToChain; ++i) {
+            (function () {
+                var promiseToReturn = currentPromise;
+                currentPromise = Q().then(function () {
+                    return promiseToReturn;
+                });
+            }());
+        }
+
+        currentPromise.then(done);
+
+        deferred.resolve();
+    });
+});

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/node_modules/q/package.json
----------------------------------------------------------------------
diff --git a/bin/node_modules/q/package.json b/bin/node_modules/q/package.json
new file mode 100644
index 0000000..2ef9436
--- /dev/null
+++ b/bin/node_modules/q/package.json
@@ -0,0 +1,93 @@
+{
+  "name": "q",
+  "version": "0.9.7",
+  "description": "A library for promises (CommonJS/Promises/A,B,D)",
+  "homepage": "https://github.com/kriskowal/q",
+  "author": {
+    "name": "Kris Kowal",
+    "email": "kris@cixar.com",
+    "url": "https://github.com/kriskowal"
+  },
+  "keywords": [
+    "q",
+    "promise",
+    "promises",
+    "promises-a",
+    "promises-aplus",
+    "deferred",
+    "future",
+    "async",
+    "flow control",
+    "fluent",
+    "browser",
+    "node"
+  ],
+  "contributors": [
+    {
+      "name": "Kris Kowal",
+      "email": "kris@cixar.com",
+      "url": "https://github.com/kriskowal"
+    },
+    {
+      "name": "Irakli Gozalishvili",
+      "email": "rfobic@gmail.com",
+      "url": "http://jeditoolkit.com"
+    },
+    {
+      "name": "Domenic Denicola",
+      "email": "domenic@domenicdenicola.com",
+      "url": "http://domenicdenicola.com"
+    }
+  ],
+  "bugs": {
+    "url": "http://github.com/kriskowal/q/issues"
+  },
+  "license": {
+    "type": "MIT",
+    "url": "http://github.com/kriskowal/q/raw/master/LICENSE"
+  },
+  "main": "q.js",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/kriskowal/q.git"
+  },
+  "engines": {
+    "node": ">=0.6.0",
+    "teleport": ">=0.2.0"
+  },
+  "dependencies": {},
+  "devDependencies": {
+    "jshint": "~2.1.9",
+    "cover": "*",
+    "jasmine-node": "1.11.0",
+    "opener": "*",
+    "promises-aplus-tests": "1.x",
+    "grunt": "~0.4.1",
+    "grunt-cli": "~0.1.9",
+    "grunt-contrib-uglify": "~0.2.2",
+    "matcha": "~0.2.0"
+  },
+  "scripts": {
+    "test": "jasmine-node spec && promises-aplus-tests spec/aplus-adapter",
+    "test-browser": "opener spec/q-spec.html",
+    "benchmark": "matcha",
+    "lint": "jshint q.js",
+    "cover": "cover run node_modules/jasmine-node/bin/jasmine-node spec && cover report html && opener cover_html/index.html",
+    "minify": "grunt",
+    "prepublish": "grunt"
+  },
+  "overlay": {
+    "teleport": {
+      "dependencies": {
+        "system": ">=0.0.4"
+      }
+    }
+  },
+  "directories": {
+    "test": "./spec"
+  },
+  "readme": "[![Build Status](https://secure.travis-ci.org/kriskowal/q.png?branch=master)](http://travis-ci.org/kriskowal/q)\n\n<a href=\"http://promises-aplus.github.com/promises-spec\">\n    <img src=\"http://promises-aplus.github.com/promises-spec/assets/logo-small.png\"\n         align=\"right\" alt=\"Promises/A+ logo\" />\n</a>\n\nIf a function cannot return a value or throw an exception without\nblocking, it can return a promise instead.  A promise is an object\nthat represents the return value or the thrown exception that the\nfunction may eventually provide.  A promise can also be used as a\nproxy for a [remote object][Q-Connection] to overcome latency.\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nOn the first pass, promises can mitigate the “[Pyramid of\nDoom][POD]”: the situation where code marches to the right faster\nthan it marches forward.\n\n[POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/\n\n```javascript\nstep1(
 function (value1) {\n    step2(value1, function(value2) {\n        step3(value2, function(value3) {\n            step4(value3, function(value4) {\n                // Do something with value4\n            });\n        });\n    });\n});\n```\n\nWith a promise library, you can flatten the pyramid.\n\n```javascript\nQ.fcall(promisedStep1)\n.then(promisedStep2)\n.then(promisedStep3)\n.then(promisedStep4)\n.then(function (value4) {\n    // Do something with value4\n})\n.catch(function (error) {\n    // Handle any error from all above steps\n})\n.done();\n```\n\nWith this approach, you also get implicit error propagation, just like `try`,\n`catch`, and `finally`.  An error in `promisedStep1` will flow all the way to\nthe `catch` function, where it’s caught and handled.  (Here `promisedStepN` is\na version of `stepN` that returns a promise.)\n\nThe callback approach is called an “inversion of control”.\nA function that accepts a callback instead of a return value\nis saying, “Don’
 t call me, I’ll call you.”.  Promises\n[un-invert][IOC] the inversion, cleanly separating the input\narguments from control flow arguments.  This simplifies the\nuse and creation of API’s, particularly variadic,\nrest and spread arguments.\n\n[IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript\n\n\n## Getting Started\n\nThe Q module can be loaded as:\n\n-   A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and\n    gzipped.\n-   A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as\n    the [q](https://npmjs.org/package/q) package\n-   An AMD module\n-   A [component](https://github.com/component/component) as ``microjs/q``\n-   Using [bower](http://bower.io/) as ``q``\n-   Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q)\n\nQ can exchange promises with jQuery, Dojo, When.js, WinJS, and more.\n\n## Resources\n\nOur [wiki][] contains a
  number of useful resources, including:\n\n- A method-by-method [Q API reference][reference].\n- A growing [examples gallery][examples], showing how Q can be used to make\n  everything better. From XHR to database access to accessing the Flickr API,\n  Q is there for you.\n- There are many libraries that produce and consume Q promises for everything\n  from file system/database access or RPC to templating. For a list of some of\n  the more popular ones, see [Libraries][].\n- If you want materials that introduce the promise concept generally, and the\n  below tutorial isn't doing it for you, check out our collection of\n  [presentations, blog posts, and podcasts][resources].\n- A guide for those [coming from jQuery's `$.Deferred`][jquery].\n\nWe'd also love to have you join the Q-Continuum [mailing list][].\n\n[wiki]: https://github.com/kriskowal/q/wiki\n[reference]: https://github.com/kriskowal/q/wiki/API-Reference\n[examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery\n[
 Libraries]: https://github.com/kriskowal/q/wiki/Libraries\n[resources]: https://github.com/kriskowal/q/wiki/General-Promise-Resources\n[jquery]: https://github.com/kriskowal/q/wiki/Coming-from-jQuery\n[mailing list]: https://groups.google.com/forum/#!forum/q-continuum\n\n\n## Tutorial\n\nPromises have a ``then`` method, which you can use to get the eventual\nreturn value (fulfillment) or thrown exception (rejection).\n\n```javascript\npromiseMeSomething()\n.then(function (value) {\n}, function (reason) {\n});\n```\n\nIf ``promiseMeSomething`` returns a promise that gets fulfilled later\nwith a return value, the first function (the fulfillment handler) will be\ncalled with the value.  However, if the ``promiseMeSomething`` function\ngets rejected later by a thrown exception, the second function (the\nrejection handler) will be called with the exception.\n\nNote that resolution of a promise is always asynchronous: that is, the\nfulfillment or rejection handler will always be called in
  the next turn of the\nevent loop (i.e. `process.nextTick` in Node). This gives you a nice\nguarantee when mentally tracing the flow of your code, namely that\n``then`` will always return before either handler is executed.\n\nIn this tutorial, we begin with how to consume and work with promises. We'll\ntalk about how to create them, and thus create functions like\n`promiseMeSomething` that return promises, [below](#the-beginning).\n\n\n### Propagation\n\nThe ``then`` method returns a promise, which in this example, I’m\nassigning to ``outputPromise``.\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (input) {\n}, function (reason) {\n});\n```\n\nThe ``outputPromise`` variable becomes a new promise for the return\nvalue of either handler.  Since a function can only either return a\nvalue or throw an exception, only one handler will ever be called and it\nwill be responsible for resolving ``outputPromise``.\n\n-   If you return a value in a handler, ``outputPr
 omise`` will get\n    fulfilled.\n\n-   If you throw an exception in a handler, ``outputPromise`` will get\n    rejected.\n\n-   If you return a **promise** in a handler, ``outputPromise`` will\n    “become” that promise.  Being able to become a new promise is useful\n    for managing delays, combining results, or recovering from errors.\n\nIf the ``getInputPromise()`` promise gets rejected and you omit the\nrejection handler, the **error** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (value) {\n});\n```\n\nIf the input promise gets fulfilled and you omit the fulfillment handler, the\n**value** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(null, function (error) {\n});\n```\n\nQ promises provide a ``fail`` shorthand for ``then`` when you are only\ninterested in handling the error:\n\n```javascript\nvar outputPromise = getInputPromise()\n.fail(function (error) {\n});\n```\n\nIf
  you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `catch` instead of `fail`.\n\nPromises also have a ``fin`` function that is like a ``finally`` clause.\nThe final handler gets called, with no arguments, when the promise\nreturned by ``getInputPromise()`` either returns a value or throws an\nerror.  The value returned or error thrown by ``getInputPromise()``\npasses directly to ``outputPromise`` unless the final handler fails, and\nmay be delayed if the final handler returns a promise.\n\n```javascript\nvar outputPromise = getInputPromise()\n.fin(function () {\n    // close files, database connections, stop servers, conclude tests\n});\n```\n\n-   If the handler returns a value, the value is ignored\n-   If the handler throws an error, the error passes to ``outputPromise``\n-   If the handler returns a promise, ``outputPromise`` gets postponed.  The\n    eventual value or error has the same effect as an immediate return\n    value or thrown erro
 r: a value would be ignored, an error would be\n    forwarded.\n\nIf you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `finally` instead of `fin`.\n\n### Chaining\n\nThere are two ways to chain promises.  You can chain promises either\ninside or outside handlers.  The next two examples are equivalent.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n    return getUser(username)\n    .then(function (user) {\n        // if we get here without an error,\n        // the value returned here\n        // or the exception thrown here\n        // resolves the promise returned\n        // by the first line\n    })\n});\n```\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n    return getUser(username);\n})\n.then(function (user) {\n    // if we get here without an error,\n    // the value returned here\n    // or the exception thrown here\n    // resolves the promise returned\n    // by the first line\n});\n```\n\nThe
  only difference is nesting.  It’s useful to nest handlers if you\nneed to capture multiple input values in your closure.\n\n```javascript\nfunction authenticate() {\n    return getUsername()\n    .then(function (username) {\n        return getUser(username);\n    })\n    // chained because we will not need the user name in the next event\n    .then(function (user) {\n        return getPassword()\n        // nested because we need both user and password next\n        .then(function (password) {\n            if (user.passwordHash !== hash(password)) {\n                throw new Error(\"Can't authenticate\");\n            }\n        });\n    });\n}\n```\n\n\n### Combination\n\nYou can turn an array of promises into a promise for the whole,\nfulfilled array using ``all``.\n\n```javascript\nreturn Q.all([\n    eventualAdd(2, 2),\n    eventualAdd(10, 20)\n]);\n```\n\nIf you have a promise for an array, you can use ``spread`` as a\nreplacement for ``then``.  The ``spread`` function “s
 preads” the\nvalues over the arguments of the fulfillment handler.  The rejection handler\nwill get called at the first sign of failure.  That is, whichever of\nthe recived promises fails first gets handled by the rejection handler.\n\n```javascript\nfunction eventualAdd(a, b) {\n    return Q.spread([a, b], function (a, b) {\n        return a + b;\n    })\n}\n```\n\nBut ``spread`` calls ``all`` initially, so you can skip it in chains.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n    return [username, getUser(username)];\n})\n.spread(function (username, user) {\n});\n```\n\nThe ``all`` function returns a promise for an array of values.  When this\npromise is fulfilled, the array contains the fulfillment values of the original\npromises, in the same order as those promises.  If one of the given promises\nis rejected, the returned promise is immediately rejected, not waiting for the\nrest of the batch.  If you want to wait for all of the promises to either be\
 nfulfilled or rejected, you can use ``allSettled``.\n\n```javascript\nQ.allSettled(promises)\n.then(function (results) {\n    results.forEach(function (result) {\n        if (result.state === \"fulfilled\") {\n            var value = result.value;\n        } else {\n            var reason = result.reason;\n        }\n    });\n});\n```\n\n\n### Sequences\n\nIf you have a number of promise-producing functions that need\nto be run sequentially, you can of course do so manually:\n\n```javascript\nreturn foo(initialVal).then(bar).then(baz).then(qux);\n```\n\nHowever, if you want to run a dynamically constructed sequence of\nfunctions, you'll want something like this:\n\n```javascript\nvar funcs = [foo, bar, baz, qux];\n\nvar result = Q(initialVal);\nfuncs.forEach(function (f) {\n    result = result.then(f);\n});\nreturn result;\n```\n\nYou can make this slightly more compact using `reduce`:\n\n```javascript\nreturn funcs.reduce(function (soFar, f) {\n    return soFar.then(f);\n}, Q(initi
 alVal));\n```\n\nOr, you could use th ultra-compact version:\n\n```javascript\nreturn funcs.reduce(Q.when, Q());\n```\n\n### Handling Errors\n\nOne sometimes-unintuive aspect of promises is that if you throw an\nexception in the fulfillment handler, it will not be be caught by the error\nhandler.\n\n```javascript\nreturn foo()\n.then(function (value) {\n    throw new Error(\"Can't bar.\");\n}, function (error) {\n    // We only get here if \"foo\" fails\n});\n```\n\nTo see why this is, consider the parallel between promises and\n``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error\nhandler represents a ``catch`` for ``foo()``, while the fulfillment handler\nrepresents code that happens *after* the ``try``/``catch`` block.\nThat code then needs its own ``try``/``catch`` block.\n\nIn terms of promises, this means chaining your rejection handler:\n\n```javascript\nreturn foo()\n.then(function (value) {\n    throw new Error(\"Can't bar.\");\n})\n.fail(function (error) {
 \n    // We get here with either foo's error or bar's error\n});\n```\n\n### Progress Notification\n\nIt's possible for promises to report their progress, e.g. for tasks that take a\nlong time like a file upload. Not all promises will implement progress\nnotifications, but for those that do, you can consume the progress values using\na third parameter to ``then``:\n\n```javascript\nreturn uploadFile()\n.then(function () {\n    // Success uploading the file\n}, function (err) {\n    // There was an error, and we get the reason for error\n}, function (progress) {\n    // We get notified of the upload's progress as it is executed\n});\n```\n\nLike `fail`, Q also provides a shorthand for progress callbacks\ncalled `progress`:\n\n```javascript\nreturn uploadFile().progress(function (progress) {\n    // We get notified of the upload's progress\n});\n```\n\n### The End\n\nWhen you get to the end of a chain of promises, you should either\nreturn the last promise or end the chain.  Since han
 dlers catch\nerrors, it’s an unfortunate pattern that the exceptions can go\nunobserved.\n\nSo, either return it,\n\n```javascript\nreturn foo()\n.then(function () {\n    return \"bar\";\n});\n```\n\nOr, end it.\n\n```javascript\nfoo()\n.then(function () {\n    return \"bar\";\n})\n.done();\n```\n\nEnding a promise chain makes sure that, if an error doesn’t get\nhandled before the end, it will get rethrown and reported.\n\nThis is a stopgap. We are exploring ways to make unhandled errors\nvisible without any explicit handling.\n\n\n### The Beginning\n\nEverything above assumes you get a promise from somewhere else.  This\nis the common case.  Every once in a while, you will need to create a\npromise from scratch.\n\n#### Using ``Q.fcall``\n\nYou can create a promise from a value using ``Q.fcall``.  This returns a\npromise for 10.\n\n```javascript\nreturn Q.fcall(function () {\n    return 10;\n});\n```\n\nYou can also use ``fcall`` to get a promise for an exception.\n\n```javascr
 ipt\nreturn Q.fcall(function () {\n    throw new Error(\"Can't do it\");\n});\n```\n\nAs the name implies, ``fcall`` can call functions, or even promised\nfunctions.  This uses the ``eventualAdd`` function above to add two\nnumbers.\n\n```javascript\nreturn Q.fcall(eventualAdd, 2, 2);\n```\n\n\n#### Using Deferreds\n\nIf you have to interface with asynchronous functions that are callback-based\ninstead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and\nfriends). But much of the time, the solution will be to use *deferreds*.\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", function (error, text) {\n    if (error) {\n        deferred.reject(new Error(error));\n    } else {\n        deferred.resolve(text);\n    }\n});\nreturn deferred.promise;\n```\n\nNote that a deferred can be resolved with a value or a promise.  The\n``reject`` function is a shorthand for resolving with a rejected\npromise.\n\n```javascript\n// this:\ndeferred.reject
 (new Error(\"Can't do it\"));\n\n// is shorthand for:\nvar rejection = Q.fcall(function () {\n    throw new Error(\"Can't do it\");\n});\ndeferred.resolve(rejection);\n```\n\nThis is a simplified implementation of ``Q.delay``.\n\n```javascript\nfunction delay(ms) {\n    var deferred = Q.defer();\n    setTimeout(deferred.resolve, ms);\n    return deferred.promise;\n}\n```\n\nThis is a simplified implementation of ``Q.timeout``\n\n```javascript\nfunction timeout(promise, ms) {\n    var deferred = Q.defer();\n    Q.when(promise, deferred.resolve);\n    delay(ms).then(function () {\n        deferred.reject(new Error(\"Timed out\"));\n    });\n    return deferred.promise;\n}\n```\n\nFinally, you can send a progress notification to the promise with\n``deferred.notify``.\n\nFor illustration, this is a wrapper for XML HTTP requests in the browser. Note\nthat a more [thorough][XHR] implementation would be in order in practice.\n\n[XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f058498
 5accd6f2801ef3015b9763/browser.js#L29-L73\n\n```javascript\nfunction requestOkText(url) {\n    var request = new XMLHttpRequest();\n    var deferred = Q.defer();\n\n    request.open(\"GET\", url, true);\n    request.onload = onload;\n    request.onerror = onerror;\n    request.onprogress = onprogress;\n    request.send();\n\n    function onload() {\n        if (request.status === 200) {\n            deferred.resolve(request.responseText);\n        } else {\n            deferred.reject(new Error(\"Status code was \" + request.status));\n        }\n    }\n\n    function onerror() {\n        deferred.reject(new Error(\"Can't XHR \" + JSON.stringify(url)));\n    }\n\n    function onprogress(event) {\n        deferred.notify(event.loaded / event.total);\n    }\n\n    return deferred.promise;\n}\n```\n\nBelow is an example of how to use this ``requestOkText`` function:\n\n```javascript\nrequestOkText(\"http://localhost:3000\")\n.then(function (responseText) {\n    // If the HTTP response 
 returns 200 OK, log the response text.\n    console.log(responseText);\n}, function (error) {\n    // If there's an error or a non-200 status code, log the error.\n    console.error(error);\n}, function (progress) {\n    // Log the progress as it comes in.\n    console.log(\"Request progress: \" + Math.round(progress * 100) + \"%\");\n});\n```\n\n### The Middle\n\nIf you are using a function that may return a promise, but just might\nreturn a value if it doesn’t need to defer, you can use the “static”\nmethods of the Q library.\n\nThe ``when`` function is the static equivalent for ``then``.\n\n```javascript\nreturn Q.when(valueOrPromise, function (value) {\n}, function (error) {\n});\n```\n\nAll of the other methods on a promise have static analogs with the\nsame name.\n\nThe following are equivalent:\n\n```javascript\nreturn Q.all([a, b]);\n```\n\n```javascript\nreturn Q.fcall(function () {\n    return [a, b];\n})\n.all();\n```\n\nWhen working with promises provided by other 
 libraries, you should\nconvert it to a Q promise.  Not all promise libraries make the same\nguarantees as Q and certainly don’t provide all of the same methods.\nMost libraries only provide a partially functional ``then`` method.\nThis thankfully is all we need to turn them into vibrant Q promises.\n\n```javascript\nreturn Q($.ajax(...))\n.then(function () {\n});\n```\n\nIf there is any chance that the promise you receive is not a Q promise\nas provided by your library, you should wrap it using a Q function.\nYou can even use ``Q.invoke`` as a shorthand.\n\n```javascript\nreturn Q.invoke($, 'ajax', ...)\n.then(function () {\n});\n```\n\n\n### Over the Wire\n\nA promise can serve as a proxy for another object, even a remote\nobject.  There are methods that allow you to optimistically manipulate\nproperties or call functions.  All of these interactions return\npromises, so they can be chained.\n\n```\ndirect manipulation         using a promise as a proxy\n--------------------------
   -------------------------------\nvalue.foo                   promise.get(\"foo\")\nvalue.foo = value           promise.put(\"foo\", value)\ndelete value.foo            promise.del(\"foo\")\nvalue.foo(...args)          promise.post(\"foo\", [args])\nvalue.foo(...args)          promise.invoke(\"foo\", ...args)\nvalue(...args)              promise.fapply([args])\nvalue(...args)              promise.fcall(...args)\n```\n\nIf the promise is a proxy for a remote object, you can shave\nround-trips by using these functions instead of ``then``.  To take\nadvantage of promises for remote objects, check out [Q-Connection][].\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nEven in the case of non-remote objects, these methods can be used as\nshorthand for particularly-simple fulfillment handlers. For example, you\ncan replace\n\n```javascript\nreturn Q.fcall(function () {\n    return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.then(function (value) {\n    return value[0].foo;\
 n});\n```\n\nwith\n\n```javascript\nreturn Q.fcall(function () {\n    return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.get(0)\n.get(\"foo\");\n```\n\n\n### Adapting Node\n\nIf you're working with functions that make use of the Node.js callback pattern,\nwhere callbacks are in the form of `function(err, result)`, Q provides a few\nuseful utility functions for converting between them. The most straightforward\nare probably `Q.nfcall` and `Q.nfapply` (\"Node function call/apply\") for calling\nNode.js-style functions and getting back a promise:\n\n```javascript\nreturn Q.nfcall(FS.readFile, \"foo.txt\", \"utf-8\");\nreturn Q.nfapply(FS.readFile, [\"foo.txt\", \"utf-8\"]);\n```\n\nIf you are working with methods, instead of simple functions, you can easily\nrun in to the usual problems where passing a method to another function—like\n`Q.nfcall`—\"un-binds\" the method from its owner. To avoid this, you can either\nuse `Function.prototype.bind` or some nice shortcut methods we prov
 ide:\n\n```javascript\nreturn Q.ninvoke(redisClient, \"get\", \"user:1:id\");\nreturn Q.npost(redisClient, \"get\", [\"user:1:id\"]);\n```\n\nYou can also create reusable wrappers with `Q.denodeify` or `Q.nbind`:\n\n```javascript\nvar readFile = Q.denodeify(FS.readFile);\nreturn readFile(\"foo.txt\", \"utf-8\");\n\nvar redisClientGet = Q.nbind(redisClient.get, redisClient);\nreturn redisClientGet(\"user:1:id\");\n```\n\nFinally, if you're working with raw deferred objects, there is a\n`makeNodeResolver` method on deferreds that can be handy:\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", deferred.makeNodeResolver());\nreturn deferred.promise;\n```\n\n### Long Stack Traces\n\nQ comes with optional support for “long stack traces,” wherein the `stack`\nproperty of `Error` rejection reasons is rewritten to be traced along\nasynchronous jumps instead of stopping at the most recent one. As an example:\n\n```js\nfunction theDepthsOfMyProgram() {\n  Q.d
 elay(100).done(function explode() {\n    throw new Error(\"boo!\");\n  });\n}\n\ntheDepthsOfMyProgram();\n```\n\nusually would give a rather unhelpful stack trace looking something like\n\n```\nError: boo!\n    at explode (/path/to/test.js:3:11)\n    at _fulfilled (/path/to/test.js:q:54)\n    at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30)\n    at makePromise.promise.promiseDispatch (/path/to/q.js:496:13)\n    at pending (/path/to/q.js:397:39)\n    at process.startup.processNextTick.process._tickCallback (node.js:244:9)\n```\n\nBut, if you turn this feature on by setting\n\n```js\nQ.longStackSupport = true;\n```\n\nthen the above code gives a nice stack trace to the tune of\n\n```\nError: boo!\n    at explode (/path/to/test.js:3:11)\nFrom previous event:\n    at theDepthsOfMyProgram (/path/to/test.js:2:16)\n    at Object.<anonymous> (/path/to/test.js:7:1)\n```\n\nNote how you can see the the function that triggered the async operation in the\nstack trace! This is very h
 elpful for debugging, as otherwise you end up getting\nonly the first line, plus a bunch of Q internals, with no sign of where the\noperation started.\n\nThis feature does come with somewhat-serious performance and memory overhead,\nhowever. If you're working with lots of promises, or trying to scale a server\nto many users, you should probably keep it off. But in development, go for it!\n\n## Tests\n\nYou can view the results of the Q test suite [in your browser][tests]!\n\n[tests]: https://rawgithub.com/kriskowal/q/master/spec/q-spec.html\n\n## License\n\nCopyright 2009–2013 Kristopher Michael Kowal\nMIT License (enclosed)\n\n",
+  "readmeFilename": "README.md",
+  "_id": "q@0.9.7",
+  "_from": "q@~0.9"
+}


[3/4] Refactoring Android project-level and platform scripts to use Q.js

Posted by br...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/node_modules/q/q.js
----------------------------------------------------------------------
diff --git a/bin/node_modules/q/q.js b/bin/node_modules/q/q.js
new file mode 100644
index 0000000..66389fc
--- /dev/null
+++ b/bin/node_modules/q/q.js
@@ -0,0 +1,1937 @@
+// vim:ts=4:sts=4:sw=4:
+/*!
+ *
+ * Copyright 2009-2012 Kris Kowal under the terms of the MIT
+ * license found at http://github.com/kriskowal/q/raw/master/LICENSE
+ *
+ * With parts by Tyler Close
+ * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found
+ * at http://www.opensource.org/licenses/mit-license.html
+ * Forked at ref_send.js version: 2009-05-11
+ *
+ * With parts by Mark Miller
+ * Copyright (C) 2011 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+(function (definition) {
+    // Turn off strict mode for this function so we can assign to global.Q
+    /* jshint strict: false */
+
+    // This file will function properly as a <script> tag, or a module
+    // using CommonJS and NodeJS or RequireJS module formats.  In
+    // Common/Node/RequireJS, the module exports the Q API and when
+    // executed as a simple <script>, it creates a Q global instead.
+
+    // Montage Require
+    if (typeof bootstrap === "function") {
+        bootstrap("promise", definition);
+
+    // CommonJS
+    } else if (typeof exports === "object") {
+        module.exports = definition();
+
+    // RequireJS
+    } else if (typeof define === "function" && define.amd) {
+        define(definition);
+
+    // SES (Secure EcmaScript)
+    } else if (typeof ses !== "undefined") {
+        if (!ses.ok()) {
+            return;
+        } else {
+            ses.makeQ = definition;
+        }
+
+    // <script>
+    } else {
+        Q = definition();
+    }
+
+})(function () {
+"use strict";
+
+var hasStacks = false;
+try {
+    throw new Error();
+} catch (e) {
+    hasStacks = !!e.stack;
+}
+
+// All code after this point will be filtered from stack traces reported
+// by Q.
+var qStartingLine = captureLine();
+var qFileName;
+
+// shims
+
+// used for fallback in "allResolved"
+var noop = function () {};
+
+// Use the fastest possible means to execute a task in a future turn
+// of the event loop.
+var nextTick =(function () {
+    // linked list of tasks (single, with head node)
+    var head = {task: void 0, next: null};
+    var tail = head;
+    var flushing = false;
+    var requestTick = void 0;
+    var isNodeJS = false;
+
+    function flush() {
+        /* jshint loopfunc: true */
+
+        while (head.next) {
+            head = head.next;
+            var task = head.task;
+            head.task = void 0;
+            var domain = head.domain;
+
+            if (domain) {
+                head.domain = void 0;
+                domain.enter();
+            }
+
+            try {
+                task();
+
+            } catch (e) {
+                if (isNodeJS) {
+                    // In node, uncaught exceptions are considered fatal errors.
+                    // Re-throw them synchronously to interrupt flushing!
+
+                    // Ensure continuation if the uncaught exception is suppressed
+                    // listening "uncaughtException" events (as domains does).
+                    // Continue in next event to avoid tick recursion.
+                    if (domain) {
+                        domain.exit();
+                    }
+                    setTimeout(flush, 0);
+                    if (domain) {
+                        domain.enter();
+                    }
+
+                    throw e;
+
+                } else {
+                    // In browsers, uncaught exceptions are not fatal.
+                    // Re-throw them asynchronously to avoid slow-downs.
+                    setTimeout(function() {
+                       throw e;
+                    }, 0);
+                }
+            }
+
+            if (domain) {
+                domain.exit();
+            }
+        }
+
+        flushing = false;
+    }
+
+    nextTick = function (task) {
+        tail = tail.next = {
+            task: task,
+            domain: isNodeJS && process.domain,
+            next: null
+        };
+
+        if (!flushing) {
+            flushing = true;
+            requestTick();
+        }
+    };
+
+    if (typeof process !== "undefined" && process.nextTick) {
+        // Node.js before 0.9. Note that some fake-Node environments, like the
+        // Mocha test runner, introduce a `process` global without a `nextTick`.
+        isNodeJS = true;
+
+        requestTick = function () {
+            process.nextTick(flush);
+        };
+
+    } else if (typeof setImmediate === "function") {
+        // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
+        if (typeof window !== "undefined") {
+            requestTick = setImmediate.bind(window, flush);
+        } else {
+            requestTick = function () {
+                setImmediate(flush);
+            };
+        }
+
+    } else if (typeof MessageChannel !== "undefined") {
+        // modern browsers
+        // http://www.nonblocking.io/2011/06/windownexttick.html
+        var channel = new MessageChannel();
+        // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create
+        // working message ports the first time a page loads.
+        channel.port1.onmessage = function () {
+            requestTick = requestPortTick;
+            channel.port1.onmessage = flush;
+            flush();
+        };
+        var requestPortTick = function () {
+            // Opera requires us to provide a message payload, regardless of
+            // whether we use it.
+            channel.port2.postMessage(0);
+        };
+        requestTick = function () {
+            setTimeout(flush, 0);
+            requestPortTick();
+        };
+
+    } else {
+        // old browsers
+        requestTick = function () {
+            setTimeout(flush, 0);
+        };
+    }
+
+    return nextTick;
+})();
+
+// Attempt to make generics safe in the face of downstream
+// modifications.
+// There is no situation where this is necessary.
+// If you need a security guarantee, these primordials need to be
+// deeply frozen anyway, and if you don’t need a security guarantee,
+// this is just plain paranoid.
+// However, this does have the nice side-effect of reducing the size
+// of the code by reducing x.call() to merely x(), eliminating many
+// hard-to-minify characters.
+// See Mark Miller’s explanation of what this does.
+// http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
+var call = Function.call;
+function uncurryThis(f) {
+    return function () {
+        return call.apply(f, arguments);
+    };
+}
+// This is equivalent, but slower:
+// uncurryThis = Function_bind.bind(Function_bind.call);
+// http://jsperf.com/uncurrythis
+
+var array_slice = uncurryThis(Array.prototype.slice);
+
+var array_reduce = uncurryThis(
+    Array.prototype.reduce || function (callback, basis) {
+        var index = 0,
+            length = this.length;
+        // concerning the initial value, if one is not provided
+        if (arguments.length === 1) {
+            // seek to the first value in the array, accounting
+            // for the possibility that is is a sparse array
+            do {
+                if (index in this) {
+                    basis = this[index++];
+                    break;
+                }
+                if (++index >= length) {
+                    throw new TypeError();
+                }
+            } while (1);
+        }
+        // reduce
+        for (; index < length; index++) {
+            // account for the possibility that the array is sparse
+            if (index in this) {
+                basis = callback(basis, this[index], index);
+            }
+        }
+        return basis;
+    }
+);
+
+var array_indexOf = uncurryThis(
+    Array.prototype.indexOf || function (value) {
+        // not a very good shim, but good enough for our one use of it
+        for (var i = 0; i < this.length; i++) {
+            if (this[i] === value) {
+                return i;
+            }
+        }
+        return -1;
+    }
+);
+
+var array_map = uncurryThis(
+    Array.prototype.map || function (callback, thisp) {
+        var self = this;
+        var collect = [];
+        array_reduce(self, function (undefined, value, index) {
+            collect.push(callback.call(thisp, value, index, self));
+        }, void 0);
+        return collect;
+    }
+);
+
+var object_create = Object.create || function (prototype) {
+    function Type() { }
+    Type.prototype = prototype;
+    return new Type();
+};
+
+var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty);
+
+var object_keys = Object.keys || function (object) {
+    var keys = [];
+    for (var key in object) {
+        if (object_hasOwnProperty(object, key)) {
+            keys.push(key);
+        }
+    }
+    return keys;
+};
+
+var object_toString = uncurryThis(Object.prototype.toString);
+
+function isObject(value) {
+    return value === Object(value);
+}
+
+// generator related shims
+
+// FIXME: Remove this function once ES6 generators are in SpiderMonkey.
+function isStopIteration(exception) {
+    return (
+        object_toString(exception) === "[object StopIteration]" ||
+        exception instanceof QReturnValue
+    );
+}
+
+// FIXME: Remove this helper and Q.return once ES6 generators are in
+// SpiderMonkey.
+var QReturnValue;
+if (typeof ReturnValue !== "undefined") {
+    QReturnValue = ReturnValue;
+} else {
+    QReturnValue = function (value) {
+        this.value = value;
+    };
+}
+
+// Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only
+// engine that has a deployed base of browsers that support generators.
+// However, SM's generators use the Python-inspired semantics of
+// outdated ES6 drafts.  We would like to support ES6, but we'd also
+// like to make it possible to use generators in deployed browsers, so
+// we also support Python-style generators.  At some point we can remove
+// this block.
+var hasES6Generators;
+try {
+    /* jshint evil: true, nonew: false */
+    new Function("(function* (){ yield 1; })");
+    hasES6Generators = true;
+} catch (e) {
+    hasES6Generators = false;
+}
+
+// long stack traces
+
+var STACK_JUMP_SEPARATOR = "From previous event:";
+
+function makeStackTraceLong(error, promise) {
+    // If possible, transform the error stack trace by removing Node and Q
+    // cruft, then concatenating with the stack trace of `promise`. See #57.
+    if (hasStacks &&
+        promise.stack &&
+        typeof error === "object" &&
+        error !== null &&
+        error.stack &&
+        error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
+    ) {
+        var stacks = [];
+        for (var p = promise; !!p; p = p.source) {
+            if (p.stack) {
+                stacks.unshift(p.stack);
+            }
+        }
+        stacks.unshift(error.stack);
+
+        var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
+        error.stack = filterStackString(concatedStacks);
+    }
+}
+
+function filterStackString(stackString) {
+    var lines = stackString.split("\n");
+    var desiredLines = [];
+    for (var i = 0; i < lines.length; ++i) {
+        var line = lines[i];
+
+        if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
+            desiredLines.push(line);
+        }
+    }
+    return desiredLines.join("\n");
+}
+
+function isNodeFrame(stackLine) {
+    return stackLine.indexOf("(module.js:") !== -1 ||
+           stackLine.indexOf("(node.js:") !== -1;
+}
+
+function getFileNameAndLineNumber(stackLine) {
+    // Named functions: "at functionName (filename:lineNumber:columnNumber)"
+    // In IE10 function name can have spaces ("Anonymous function") O_o
+    var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
+    if (attempt1) {
+        return [attempt1[1], Number(attempt1[2])];
+    }
+
+    // Anonymous functions: "at filename:lineNumber:columnNumber"
+    var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
+    if (attempt2) {
+        return [attempt2[1], Number(attempt2[2])];
+    }
+
+    // Firefox style: "function@filename:lineNumber or @filename:lineNumber"
+    var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
+    if (attempt3) {
+        return [attempt3[1], Number(attempt3[2])];
+    }
+}
+
+function isInternalFrame(stackLine) {
+    var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
+
+    if (!fileNameAndLineNumber) {
+        return false;
+    }
+
+    var fileName = fileNameAndLineNumber[0];
+    var lineNumber = fileNameAndLineNumber[1];
+
+    return fileName === qFileName &&
+        lineNumber >= qStartingLine &&
+        lineNumber <= qEndingLine;
+}
+
+// discover own file name and line number range for filtering stack
+// traces
+function captureLine() {
+    if (!hasStacks) {
+        return;
+    }
+
+    try {
+        throw new Error();
+    } catch (e) {
+        var lines = e.stack.split("\n");
+        var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
+        var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
+        if (!fileNameAndLineNumber) {
+            return;
+        }
+
+        qFileName = fileNameAndLineNumber[0];
+        return fileNameAndLineNumber[1];
+    }
+}
+
+function deprecate(callback, name, alternative) {
+    return function () {
+        if (typeof console !== "undefined" &&
+            typeof console.warn === "function") {
+            console.warn(name + " is deprecated, use " + alternative +
+                         " instead.", new Error("").stack);
+        }
+        return callback.apply(callback, arguments);
+    };
+}
+
+// end of shims
+// beginning of real work
+
+/**
+ * Constructs a promise for an immediate reference, passes promises through, or
+ * coerces promises from different systems.
+ * @param value immediate reference or promise
+ */
+function Q(value) {
+    // If the object is already a Promise, return it directly.  This enables
+    // the resolve function to both be used to created references from objects,
+    // but to tolerably coerce non-promises to promises.
+    if (isPromise(value)) {
+        return value;
+    }
+
+    // assimilate thenables
+    if (isPromiseAlike(value)) {
+        return coerce(value);
+    } else {
+        return fulfill(value);
+    }
+}
+Q.resolve = Q;
+
+/**
+ * Performs a task in a future turn of the event loop.
+ * @param {Function} task
+ */
+Q.nextTick = nextTick;
+
+/**
+ * Controls whether or not long stack traces will be on
+ */
+Q.longStackSupport = false;
+
+/**
+ * Constructs a {promise, resolve, reject} object.
+ *
+ * `resolve` is a callback to invoke with a more resolved value for the
+ * promise. To fulfill the promise, invoke `resolve` with any value that is
+ * not a thenable. To reject the promise, invoke `resolve` with a rejected
+ * thenable, or invoke `reject` with the reason directly. To resolve the
+ * promise to another thenable, thus putting it in the same state, invoke
+ * `resolve` with that other thenable.
+ */
+Q.defer = defer;
+function defer() {
+    // if "messages" is an "Array", that indicates that the promise has not yet
+    // been resolved.  If it is "undefined", it has been resolved.  Each
+    // element of the messages array is itself an array of complete arguments to
+    // forward to the resolved promise.  We coerce the resolution value to a
+    // promise using the `resolve` function because it handles both fully
+    // non-thenable values and other thenables gracefully.
+    var messages = [], progressListeners = [], resolvedPromise;
+
+    var deferred = object_create(defer.prototype);
+    var promise = object_create(Promise.prototype);
+
+    promise.promiseDispatch = function (resolve, op, operands) {
+        var args = array_slice(arguments);
+        if (messages) {
+            messages.push(args);
+            if (op === "when" && operands[1]) { // progress operand
+                progressListeners.push(operands[1]);
+            }
+        } else {
+            nextTick(function () {
+                resolvedPromise.promiseDispatch.apply(resolvedPromise, args);
+            });
+        }
+    };
+
+    // XXX deprecated
+    promise.valueOf = deprecate(function () {
+        if (messages) {
+            return promise;
+        }
+        var nearerValue = nearer(resolvedPromise);
+        if (isPromise(nearerValue)) {
+            resolvedPromise = nearerValue; // shorten chain
+        }
+        return nearerValue;
+    }, "valueOf", "inspect");
+
+    promise.inspect = function () {
+        if (!resolvedPromise) {
+            return { state: "pending" };
+        }
+        return resolvedPromise.inspect();
+    };
+
+    if (Q.longStackSupport && hasStacks) {
+        try {
+            throw new Error();
+        } catch (e) {
+            // NOTE: don't try to use `Error.captureStackTrace` or transfer the
+            // accessor around; that causes memory leaks as per GH-111. Just
+            // reify the stack trace as a string ASAP.
+            //
+            // At the same time, cut off the first line; it's always just
+            // "[object Promise]\n", as per the `toString`.
+            promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
+        }
+    }
+
+    // NOTE: we do the checks for `resolvedPromise` in each method, instead of
+    // consolidating them into `become`, since otherwise we'd create new
+    // promises with the lines `become(whatever(value))`. See e.g. GH-252.
+
+    function become(newPromise) {
+        resolvedPromise = newPromise;
+        promise.source = newPromise;
+
+        array_reduce(messages, function (undefined, message) {
+            nextTick(function () {
+                newPromise.promiseDispatch.apply(newPromise, message);
+            });
+        }, void 0);
+
+        messages = void 0;
+        progressListeners = void 0;
+    }
+
+    deferred.promise = promise;
+    deferred.resolve = function (value) {
+        if (resolvedPromise) {
+            return;
+        }
+
+        become(Q(value));
+    };
+
+    deferred.fulfill = function (value) {
+        if (resolvedPromise) {
+            return;
+        }
+
+        become(fulfill(value));
+    };
+    deferred.reject = function (reason) {
+        if (resolvedPromise) {
+            return;
+        }
+
+        become(reject(reason));
+    };
+    deferred.notify = function (progress) {
+        if (resolvedPromise) {
+            return;
+        }
+
+        array_reduce(progressListeners, function (undefined, progressListener) {
+            nextTick(function () {
+                progressListener(progress);
+            });
+        }, void 0);
+    };
+
+    return deferred;
+}
+
+/**
+ * Creates a Node-style callback that will resolve or reject the deferred
+ * promise.
+ * @returns a nodeback
+ */
+defer.prototype.makeNodeResolver = function () {
+    var self = this;
+    return function (error, value) {
+        if (error) {
+            self.reject(error);
+        } else if (arguments.length > 2) {
+            self.resolve(array_slice(arguments, 1));
+        } else {
+            self.resolve(value);
+        }
+    };
+};
+
+/**
+ * @param resolver {Function} a function that returns nothing and accepts
+ * the resolve, reject, and notify functions for a deferred.
+ * @returns a promise that may be resolved with the given resolve and reject
+ * functions, or rejected by a thrown exception in resolver
+ */
+Q.promise = promise;
+function promise(resolver) {
+    if (typeof resolver !== "function") {
+        throw new TypeError("resolver must be a function.");
+    }
+    var deferred = defer();
+    try {
+        resolver(deferred.resolve, deferred.reject, deferred.notify);
+    } catch (reason) {
+        deferred.reject(reason);
+    }
+    return deferred.promise;
+}
+
+// XXX experimental.  This method is a way to denote that a local value is
+// serializable and should be immediately dispatched to a remote upon request,
+// instead of passing a reference.
+Q.passByCopy = function (object) {
+    //freeze(object);
+    //passByCopies.set(object, true);
+    return object;
+};
+
+Promise.prototype.passByCopy = function () {
+    //freeze(object);
+    //passByCopies.set(object, true);
+    return this;
+};
+
+/**
+ * If two promises eventually fulfill to the same value, promises that value,
+ * but otherwise rejects.
+ * @param x {Any*}
+ * @param y {Any*}
+ * @returns {Any*} a promise for x and y if they are the same, but a rejection
+ * otherwise.
+ *
+ */
+Q.join = function (x, y) {
+    return Q(x).join(y);
+};
+
+Promise.prototype.join = function (that) {
+    return Q([this, that]).spread(function (x, y) {
+        if (x === y) {
+            // TODO: "===" should be Object.is or equiv
+            return x;
+        } else {
+            throw new Error("Can't join: not the same: " + x + " " + y);
+        }
+    });
+};
+
+/**
+ * Returns a promise for the first of an array of promises to become fulfilled.
+ * @param answers {Array[Any*]} promises to race
+ * @returns {Any*} the first promise to be fulfilled
+ */
+Q.race = race;
+function race(answerPs) {
+    return promise(function(resolve, reject) {
+        // Switch to this once we can assume at least ES5
+        // answerPs.forEach(function(answerP) {
+        //     Q(answerP).then(resolve, reject);
+        // });
+        // Use this in the meantime
+        for (var i = 0, len = answerPs.length; i < len; i++) {
+            Q(answerPs[i]).then(resolve, reject);
+        }
+    });
+}
+
+Promise.prototype.race = function () {
+    return this.then(Q.race);
+};
+
+/**
+ * Constructs a Promise with a promise descriptor object and optional fallback
+ * function.  The descriptor contains methods like when(rejected), get(name),
+ * set(name, value), post(name, args), and delete(name), which all
+ * return either a value, a promise for a value, or a rejection.  The fallback
+ * accepts the operation name, a resolver, and any further arguments that would
+ * have been forwarded to the appropriate method above had a method been
+ * provided with the proper name.  The API makes no guarantees about the nature
+ * of the returned object, apart from that it is usable whereever promises are
+ * bought and sold.
+ */
+Q.makePromise = Promise;
+function Promise(descriptor, fallback, inspect) {
+    if (fallback === void 0) {
+        fallback = function (op) {
+            return reject(new Error(
+                "Promise does not support operation: " + op
+            ));
+        };
+    }
+    if (inspect === void 0) {
+        inspect = function () {
+            return {state: "unknown"};
+        };
+    }
+
+    var promise = object_create(Promise.prototype);
+
+    promise.promiseDispatch = function (resolve, op, args) {
+        var result;
+        try {
+            if (descriptor[op]) {
+                result = descriptor[op].apply(promise, args);
+            } else {
+                result = fallback.call(promise, op, args);
+            }
+        } catch (exception) {
+            result = reject(exception);
+        }
+        if (resolve) {
+            resolve(result);
+        }
+    };
+
+    promise.inspect = inspect;
+
+    // XXX deprecated `valueOf` and `exception` support
+    if (inspect) {
+        var inspected = inspect();
+        if (inspected.state === "rejected") {
+            promise.exception = inspected.reason;
+        }
+
+        promise.valueOf = deprecate(function () {
+            var inspected = inspect();
+            if (inspected.state === "pending" ||
+                inspected.state === "rejected") {
+                return promise;
+            }
+            return inspected.value;
+        });
+    }
+
+    return promise;
+}
+
+Promise.prototype.toString = function () {
+    return "[object Promise]";
+};
+
+Promise.prototype.then = function (fulfilled, rejected, progressed) {
+    var self = this;
+    var deferred = defer();
+    var done = false;   // ensure the untrusted promise makes at most a
+                        // single call to one of the callbacks
+
+    function _fulfilled(value) {
+        try {
+            return typeof fulfilled === "function" ? fulfilled(value) : value;
+        } catch (exception) {
+            return reject(exception);
+        }
+    }
+
+    function _rejected(exception) {
+        if (typeof rejected === "function") {
+            makeStackTraceLong(exception, self);
+            try {
+                return rejected(exception);
+            } catch (newException) {
+                return reject(newException);
+            }
+        }
+        return reject(exception);
+    }
+
+    function _progressed(value) {
+        return typeof progressed === "function" ? progressed(value) : value;
+    }
+
+    nextTick(function () {
+        self.promiseDispatch(function (value) {
+            if (done) {
+                return;
+            }
+            done = true;
+
+            deferred.resolve(_fulfilled(value));
+        }, "when", [function (exception) {
+            if (done) {
+                return;
+            }
+            done = true;
+
+            deferred.resolve(_rejected(exception));
+        }]);
+    });
+
+    // Progress propagator need to be attached in the current tick.
+    self.promiseDispatch(void 0, "when", [void 0, function (value) {
+        var newValue;
+        var threw = false;
+        try {
+            newValue = _progressed(value);
+        } catch (e) {
+            threw = true;
+            if (Q.onerror) {
+                Q.onerror(e);
+            } else {
+                throw e;
+            }
+        }
+
+        if (!threw) {
+            deferred.notify(newValue);
+        }
+    }]);
+
+    return deferred.promise;
+};
+
+/**
+ * Registers an observer on a promise.
+ *
+ * Guarantees:
+ *
+ * 1. that fulfilled and rejected will be called only once.
+ * 2. that either the fulfilled callback or the rejected callback will be
+ *    called, but not both.
+ * 3. that fulfilled and rejected will not be called in this turn.
+ *
+ * @param value      promise or immediate reference to observe
+ * @param fulfilled  function to be called with the fulfilled value
+ * @param rejected   function to be called with the rejection exception
+ * @param progressed function to be called on any progress notifications
+ * @return promise for the return value from the invoked callback
+ */
+Q.when = when;
+function when(value, fulfilled, rejected, progressed) {
+    return Q(value).then(fulfilled, rejected, progressed);
+}
+
+Promise.prototype.thenResolve = function (value) {
+    return this.then(function () { return value; });
+};
+
+Q.thenResolve = function (promise, value) {
+    return Q(promise).thenResolve(value);
+};
+
+Promise.prototype.thenReject = function (reason) {
+    return this.then(function () { throw reason; });
+};
+
+Q.thenReject = function (promise, reason) {
+    return Q(promise).thenReject(reason);
+};
+
+/**
+ * If an object is not a promise, it is as "near" as possible.
+ * If a promise is rejected, it is as "near" as possible too.
+ * If it’s a fulfilled promise, the fulfillment value is nearer.
+ * If it’s a deferred promise and the deferred has been resolved, the
+ * resolution is "nearer".
+ * @param object
+ * @returns most resolved (nearest) form of the object
+ */
+
+// XXX should we re-do this?
+Q.nearer = nearer;
+function nearer(value) {
+    if (isPromise(value)) {
+        var inspected = value.inspect();
+        if (inspected.state === "fulfilled") {
+            return inspected.value;
+        }
+    }
+    return value;
+}
+
+/**
+ * @returns whether the given object is a promise.
+ * Otherwise it is a fulfilled value.
+ */
+Q.isPromise = isPromise;
+function isPromise(object) {
+    return isObject(object) &&
+        typeof object.promiseDispatch === "function" &&
+        typeof object.inspect === "function";
+}
+
+Q.isPromiseAlike = isPromiseAlike;
+function isPromiseAlike(object) {
+    return isObject(object) && typeof object.then === "function";
+}
+
+/**
+ * @returns whether the given object is a pending promise, meaning not
+ * fulfilled or rejected.
+ */
+Q.isPending = isPending;
+function isPending(object) {
+    return isPromise(object) && object.inspect().state === "pending";
+}
+
+Promise.prototype.isPending = function () {
+    return this.inspect().state === "pending";
+};
+
+/**
+ * @returns whether the given object is a value or fulfilled
+ * promise.
+ */
+Q.isFulfilled = isFulfilled;
+function isFulfilled(object) {
+    return !isPromise(object) || object.inspect().state === "fulfilled";
+}
+
+Promise.prototype.isFulfilled = function () {
+    return this.inspect().state === "fulfilled";
+};
+
+/**
+ * @returns whether the given object is a rejected promise.
+ */
+Q.isRejected = isRejected;
+function isRejected(object) {
+    return isPromise(object) && object.inspect().state === "rejected";
+}
+
+Promise.prototype.isRejected = function () {
+    return this.inspect().state === "rejected";
+};
+
+//// BEGIN UNHANDLED REJECTION TRACKING
+
+// This promise library consumes exceptions thrown in handlers so they can be
+// handled by a subsequent promise.  The exceptions get added to this array when
+// they are created, and removed when they are handled.  Note that in ES6 or
+// shimmed environments, this would naturally be a `Set`.
+var unhandledReasons = [];
+var unhandledRejections = [];
+var unhandledReasonsDisplayed = false;
+var trackUnhandledRejections = true;
+function displayUnhandledReasons() {
+    if (
+        !unhandledReasonsDisplayed &&
+        typeof window !== "undefined" &&
+        !window.Touch &&
+        window.console
+    ) {
+        console.warn("[Q] Unhandled rejection reasons (should be empty):",
+                     unhandledReasons);
+    }
+
+    unhandledReasonsDisplayed = true;
+}
+
+function logUnhandledReasons() {
+    for (var i = 0; i < unhandledReasons.length; i++) {
+        var reason = unhandledReasons[i];
+        console.warn("Unhandled rejection reason:", reason);
+    }
+}
+
+function resetUnhandledRejections() {
+    unhandledReasons.length = 0;
+    unhandledRejections.length = 0;
+    unhandledReasonsDisplayed = false;
+
+    if (!trackUnhandledRejections) {
+        trackUnhandledRejections = true;
+
+        // Show unhandled rejection reasons if Node exits without handling an
+        // outstanding rejection.  (Note that Browserify presently produces a
+        // `process` global without the `EventEmitter` `on` method.)
+        if (typeof process !== "undefined" && process.on) {
+            process.on("exit", logUnhandledReasons);
+        }
+    }
+}
+
+function trackRejection(promise, reason) {
+    if (!trackUnhandledRejections) {
+        return;
+    }
+
+    unhandledRejections.push(promise);
+    if (reason && typeof reason.stack !== "undefined") {
+        unhandledReasons.push(reason.stack);
+    } else {
+        unhandledReasons.push("(no stack) " + reason);
+    }
+    displayUnhandledReasons();
+}
+
+function untrackRejection(promise) {
+    if (!trackUnhandledRejections) {
+        return;
+    }
+
+    var at = array_indexOf(unhandledRejections, promise);
+    if (at !== -1) {
+        unhandledRejections.splice(at, 1);
+        unhandledReasons.splice(at, 1);
+    }
+}
+
+Q.resetUnhandledRejections = resetUnhandledRejections;
+
+Q.getUnhandledReasons = function () {
+    // Make a copy so that consumers can't interfere with our internal state.
+    return unhandledReasons.slice();
+};
+
+Q.stopUnhandledRejectionTracking = function () {
+    resetUnhandledRejections();
+    if (typeof process !== "undefined" && process.on) {
+        process.removeListener("exit", logUnhandledReasons);
+    }
+    trackUnhandledRejections = false;
+};
+
+resetUnhandledRejections();
+
+//// END UNHANDLED REJECTION TRACKING
+
+/**
+ * Constructs a rejected promise.
+ * @param reason value describing the failure
+ */
+Q.reject = reject;
+function reject(reason) {
+    var rejection = Promise({
+        "when": function (rejected) {
+            // note that the error has been handled
+            if (rejected) {
+                untrackRejection(this);
+            }
+            return rejected ? rejected(reason) : this;
+        }
+    }, function fallback() {
+        return this;
+    }, function inspect() {
+        return { state: "rejected", reason: reason };
+    });
+
+    // Note that the reason has not been handled.
+    trackRejection(rejection, reason);
+
+    return rejection;
+}
+
+/**
+ * Constructs a fulfilled promise for an immediate reference.
+ * @param value immediate reference
+ */
+Q.fulfill = fulfill;
+function fulfill(value) {
+    return Promise({
+        "when": function () {
+            return value;
+        },
+        "get": function (name) {
+            return value[name];
+        },
+        "set": function (name, rhs) {
+            value[name] = rhs;
+        },
+        "delete": function (name) {
+            delete value[name];
+        },
+        "post": function (name, args) {
+            // Mark Miller proposes that post with no name should apply a
+            // promised function.
+            if (name === null || name === void 0) {
+                return value.apply(void 0, args);
+            } else {
+                return value[name].apply(value, args);
+            }
+        },
+        "apply": function (thisp, args) {
+            return value.apply(thisp, args);
+        },
+        "keys": function () {
+            return object_keys(value);
+        }
+    }, void 0, function inspect() {
+        return { state: "fulfilled", value: value };
+    });
+}
+
+/**
+ * Converts thenables to Q promises.
+ * @param promise thenable promise
+ * @returns a Q promise
+ */
+function coerce(promise) {
+    var deferred = defer();
+    nextTick(function () {
+        try {
+            promise.then(deferred.resolve, deferred.reject, deferred.notify);
+        } catch (exception) {
+            deferred.reject(exception);
+        }
+    });
+    return deferred.promise;
+}
+
+/**
+ * Annotates an object such that it will never be
+ * transferred away from this process over any promise
+ * communication channel.
+ * @param object
+ * @returns promise a wrapping of that object that
+ * additionally responds to the "isDef" message
+ * without a rejection.
+ */
+Q.master = master;
+function master(object) {
+    return Promise({
+        "isDef": function () {}
+    }, function fallback(op, args) {
+        return dispatch(object, op, args);
+    }, function () {
+        return Q(object).inspect();
+    });
+}
+
+/**
+ * Spreads the values of a promised array of arguments into the
+ * fulfillment callback.
+ * @param fulfilled callback that receives variadic arguments from the
+ * promised array
+ * @param rejected callback that receives the exception if the promise
+ * is rejected.
+ * @returns a promise for the return value or thrown exception of
+ * either callback.
+ */
+Q.spread = spread;
+function spread(value, fulfilled, rejected) {
+    return Q(value).spread(fulfilled, rejected);
+}
+
+Promise.prototype.spread = function (fulfilled, rejected) {
+    return this.all().then(function (array) {
+        return fulfilled.apply(void 0, array);
+    }, rejected);
+};
+
+/**
+ * The async function is a decorator for generator functions, turning
+ * them into asynchronous generators.  Although generators are only part
+ * of the newest ECMAScript 6 drafts, this code does not cause syntax
+ * errors in older engines.  This code should continue to work and will
+ * in fact improve over time as the language improves.
+ *
+ * ES6 generators are currently part of V8 version 3.19 with the
+ * --harmony-generators runtime flag enabled.  SpiderMonkey has had them
+ * for longer, but under an older Python-inspired form.  This function
+ * works on both kinds of generators.
+ *
+ * Decorates a generator function such that:
+ *  - it may yield promises
+ *  - execution will continue when that promise is fulfilled
+ *  - the value of the yield expression will be the fulfilled value
+ *  - it returns a promise for the return value (when the generator
+ *    stops iterating)
+ *  - the decorated function returns a promise for the return value
+ *    of the generator or the first rejected promise among those
+ *    yielded.
+ *  - if an error is thrown in the generator, it propagates through
+ *    every following yield until it is caught, or until it escapes
+ *    the generator function altogether, and is translated into a
+ *    rejection for the promise returned by the decorated generator.
+ */
+Q.async = async;
+function async(makeGenerator) {
+    return function () {
+        // when verb is "send", arg is a value
+        // when verb is "throw", arg is an exception
+        function continuer(verb, arg) {
+            var result;
+            if (hasES6Generators) {
+                try {
+                    result = generator[verb](arg);
+                } catch (exception) {
+                    return reject(exception);
+                }
+                if (result.done) {
+                    return result.value;
+                } else {
+                    return when(result.value, callback, errback);
+                }
+            } else {
+                // FIXME: Remove this case when SM does ES6 generators.
+                try {
+                    result = generator[verb](arg);
+                } catch (exception) {
+                    if (isStopIteration(exception)) {
+                        return exception.value;
+                    } else {
+                        return reject(exception);
+                    }
+                }
+                return when(result, callback, errback);
+            }
+        }
+        var generator = makeGenerator.apply(this, arguments);
+        var callback = continuer.bind(continuer, "next");
+        var errback = continuer.bind(continuer, "throw");
+        return callback();
+    };
+}
+
+/**
+ * The spawn function is a small wrapper around async that immediately
+ * calls the generator and also ends the promise chain, so that any
+ * unhandled errors are thrown instead of forwarded to the error
+ * handler. This is useful because it's extremely common to run
+ * generators at the top-level to work with libraries.
+ */
+Q.spawn = spawn;
+function spawn(makeGenerator) {
+    Q.done(Q.async(makeGenerator)());
+}
+
+// FIXME: Remove this interface once ES6 generators are in SpiderMonkey.
+/**
+ * Throws a ReturnValue exception to stop an asynchronous generator.
+ *
+ * This interface is a stop-gap measure to support generator return
+ * values in older Firefox/SpiderMonkey.  In browsers that support ES6
+ * generators like Chromium 29, just use "return" in your generator
+ * functions.
+ *
+ * @param value the return value for the surrounding generator
+ * @throws ReturnValue exception with the value.
+ * @example
+ * // ES6 style
+ * Q.async(function* () {
+ *      var foo = yield getFooPromise();
+ *      var bar = yield getBarPromise();
+ *      return foo + bar;
+ * })
+ * // Older SpiderMonkey style
+ * Q.async(function () {
+ *      var foo = yield getFooPromise();
+ *      var bar = yield getBarPromise();
+ *      Q.return(foo + bar);
+ * })
+ */
+Q["return"] = _return;
+function _return(value) {
+    throw new QReturnValue(value);
+}
+
+/**
+ * The promised function decorator ensures that any promise arguments
+ * are settled and passed as values (`this` is also settled and passed
+ * as a value).  It will also ensure that the result of a function is
+ * always a promise.
+ *
+ * @example
+ * var add = Q.promised(function (a, b) {
+ *     return a + b;
+ * });
+ * add(Q(a), Q(B));
+ *
+ * @param {function} callback The function to decorate
+ * @returns {function} a function that has been decorated.
+ */
+Q.promised = promised;
+function promised(callback) {
+    return function () {
+        return spread([this, all(arguments)], function (self, args) {
+            return callback.apply(self, args);
+        });
+    };
+}
+
+/**
+ * sends a message to a value in a future turn
+ * @param object* the recipient
+ * @param op the name of the message operation, e.g., "when",
+ * @param args further arguments to be forwarded to the operation
+ * @returns result {Promise} a promise for the result of the operation
+ */
+Q.dispatch = dispatch;
+function dispatch(object, op, args) {
+    return Q(object).dispatch(op, args);
+}
+
+Promise.prototype.dispatch = function (op, args) {
+    var self = this;
+    var deferred = defer();
+    nextTick(function () {
+        self.promiseDispatch(deferred.resolve, op, args);
+    });
+    return deferred.promise;
+};
+
+/**
+ * Gets the value of a property in a future turn.
+ * @param object    promise or immediate reference for target object
+ * @param name      name of property to get
+ * @return promise for the property value
+ */
+Q.get = function (object, key) {
+    return Q(object).dispatch("get", [key]);
+};
+
+Promise.prototype.get = function (key) {
+    return this.dispatch("get", [key]);
+};
+
+/**
+ * Sets the value of a property in a future turn.
+ * @param object    promise or immediate reference for object object
+ * @param name      name of property to set
+ * @param value     new value of property
+ * @return promise for the return value
+ */
+Q.set = function (object, key, value) {
+    return Q(object).dispatch("set", [key, value]);
+};
+
+Promise.prototype.set = function (key, value) {
+    return this.dispatch("set", [key, value]);
+};
+
+/**
+ * Deletes a property in a future turn.
+ * @param object    promise or immediate reference for target object
+ * @param name      name of property to delete
+ * @return promise for the return value
+ */
+Q.del = // XXX legacy
+Q["delete"] = function (object, key) {
+    return Q(object).dispatch("delete", [key]);
+};
+
+Promise.prototype.del = // XXX legacy
+Promise.prototype["delete"] = function (key) {
+    return this.dispatch("delete", [key]);
+};
+
+/**
+ * Invokes a method in a future turn.
+ * @param object    promise or immediate reference for target object
+ * @param name      name of method to invoke
+ * @param value     a value to post, typically an array of
+ *                  invocation arguments for promises that
+ *                  are ultimately backed with `resolve` values,
+ *                  as opposed to those backed with URLs
+ *                  wherein the posted value can be any
+ *                  JSON serializable object.
+ * @return promise for the return value
+ */
+// bound locally because it is used by other methods
+Q.mapply = // XXX As proposed by "Redsandro"
+Q.post = function (object, name, args) {
+    return Q(object).dispatch("post", [name, args]);
+};
+
+Promise.prototype.mapply = // XXX As proposed by "Redsandro"
+Promise.prototype.post = function (name, args) {
+    return this.dispatch("post", [name, args]);
+};
+
+/**
+ * Invokes a method in a future turn.
+ * @param object    promise or immediate reference for target object
+ * @param name      name of method to invoke
+ * @param ...args   array of invocation arguments
+ * @return promise for the return value
+ */
+Q.send = // XXX Mark Miller's proposed parlance
+Q.mcall = // XXX As proposed by "Redsandro"
+Q.invoke = function (object, name /*...args*/) {
+    return Q(object).dispatch("post", [name, array_slice(arguments, 2)]);
+};
+
+Promise.prototype.send = // XXX Mark Miller's proposed parlance
+Promise.prototype.mcall = // XXX As proposed by "Redsandro"
+Promise.prototype.invoke = function (name /*...args*/) {
+    return this.dispatch("post", [name, array_slice(arguments, 1)]);
+};
+
+/**
+ * Applies the promised function in a future turn.
+ * @param object    promise or immediate reference for target function
+ * @param args      array of application arguments
+ */
+Q.fapply = function (object, args) {
+    return Q(object).dispatch("apply", [void 0, args]);
+};
+
+Promise.prototype.fapply = function (args) {
+    return this.dispatch("apply", [void 0, args]);
+};
+
+/**
+ * Calls the promised function in a future turn.
+ * @param object    promise or immediate reference for target function
+ * @param ...args   array of application arguments
+ */
+Q["try"] =
+Q.fcall = function (object /* ...args*/) {
+    return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]);
+};
+
+Promise.prototype.fcall = function (/*...args*/) {
+    return this.dispatch("apply", [void 0, array_slice(arguments)]);
+};
+
+/**
+ * Binds the promised function, transforming return values into a fulfilled
+ * promise and thrown errors into a rejected one.
+ * @param object    promise or immediate reference for target function
+ * @param ...args   array of application arguments
+ */
+Q.fbind = function (object /*...args*/) {
+    var promise = Q(object);
+    var args = array_slice(arguments, 1);
+    return function fbound() {
+        return promise.dispatch("apply", [
+            this,
+            args.concat(array_slice(arguments))
+        ]);
+    };
+};
+Promise.prototype.fbind = function (/*...args*/) {
+    var promise = this;
+    var args = array_slice(arguments);
+    return function fbound() {
+        return promise.dispatch("apply", [
+            this,
+            args.concat(array_slice(arguments))
+        ]);
+    };
+};
+
+/**
+ * Requests the names of the owned properties of a promised
+ * object in a future turn.
+ * @param object    promise or immediate reference for target object
+ * @return promise for the keys of the eventually settled object
+ */
+Q.keys = function (object) {
+    return Q(object).dispatch("keys", []);
+};
+
+Promise.prototype.keys = function () {
+    return this.dispatch("keys", []);
+};
+
+/**
+ * Turns an array of promises into a promise for an array.  If any of
+ * the promises gets rejected, the whole array is rejected immediately.
+ * @param {Array*} an array (or promise for an array) of values (or
+ * promises for values)
+ * @returns a promise for an array of the corresponding values
+ */
+// By Mark Miller
+// http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled
+Q.all = all;
+function all(promises) {
+    return when(promises, function (promises) {
+        var countDown = 0;
+        var deferred = defer();
+        array_reduce(promises, function (undefined, promise, index) {
+            var snapshot;
+            if (
+                isPromise(promise) &&
+                (snapshot = promise.inspect()).state === "fulfilled"
+            ) {
+                promises[index] = snapshot.value;
+            } else {
+                ++countDown;
+                when(
+                    promise,
+                    function (value) {
+                        promises[index] = value;
+                        if (--countDown === 0) {
+                            deferred.resolve(promises);
+                        }
+                    },
+                    deferred.reject,
+                    function (progress) {
+                        deferred.notify({ index: index, value: progress });
+                    }
+                );
+            }
+        }, void 0);
+        if (countDown === 0) {
+            deferred.resolve(promises);
+        }
+        return deferred.promise;
+    });
+}
+
+Promise.prototype.all = function () {
+    return all(this);
+};
+
+/**
+ * Waits for all promises to be settled, either fulfilled or
+ * rejected.  This is distinct from `all` since that would stop
+ * waiting at the first rejection.  The promise returned by
+ * `allResolved` will never be rejected.
+ * @param promises a promise for an array (or an array) of promises
+ * (or values)
+ * @return a promise for an array of promises
+ */
+Q.allResolved = deprecate(allResolved, "allResolved", "allSettled");
+function allResolved(promises) {
+    return when(promises, function (promises) {
+        promises = array_map(promises, Q);
+        return when(all(array_map(promises, function (promise) {
+            return when(promise, noop, noop);
+        })), function () {
+            return promises;
+        });
+    });
+}
+
+Promise.prototype.allResolved = function () {
+    return allResolved(this);
+};
+
+/**
+ * @see Promise#allSettled
+ */
+Q.allSettled = allSettled;
+function allSettled(promises) {
+    return Q(promises).allSettled();
+}
+
+/**
+ * Turns an array of promises into a promise for an array of their states (as
+ * returned by `inspect`) when they have all settled.
+ * @param {Array[Any*]} values an array (or promise for an array) of values (or
+ * promises for values)
+ * @returns {Array[State]} an array of states for the respective values.
+ */
+Promise.prototype.allSettled = function () {
+    return this.then(function (promises) {
+        return all(array_map(promises, function (promise) {
+            promise = Q(promise);
+            function regardless() {
+                return promise.inspect();
+            }
+            return promise.then(regardless, regardless);
+        }));
+    });
+};
+
+/**
+ * Captures the failure of a promise, giving an oportunity to recover
+ * with a callback.  If the given promise is fulfilled, the returned
+ * promise is fulfilled.
+ * @param {Any*} promise for something
+ * @param {Function} callback to fulfill the returned promise if the
+ * given promise is rejected
+ * @returns a promise for the return value of the callback
+ */
+Q.fail = // XXX legacy
+Q["catch"] = function (object, rejected) {
+    return Q(object).then(void 0, rejected);
+};
+
+Promise.prototype.fail = // XXX legacy
+Promise.prototype["catch"] = function (rejected) {
+    return this.then(void 0, rejected);
+};
+
+/**
+ * Attaches a listener that can respond to progress notifications from a
+ * promise's originating deferred. This listener receives the exact arguments
+ * passed to ``deferred.notify``.
+ * @param {Any*} promise for something
+ * @param {Function} callback to receive any progress notifications
+ * @returns the given promise, unchanged
+ */
+Q.progress = progress;
+function progress(object, progressed) {
+    return Q(object).then(void 0, void 0, progressed);
+}
+
+Promise.prototype.progress = function (progressed) {
+    return this.then(void 0, void 0, progressed);
+};
+
+/**
+ * Provides an opportunity to observe the settling of a promise,
+ * regardless of whether the promise is fulfilled or rejected.  Forwards
+ * the resolution to the returned promise when the callback is done.
+ * The callback can return a promise to defer completion.
+ * @param {Any*} promise
+ * @param {Function} callback to observe the resolution of the given
+ * promise, takes no arguments.
+ * @returns a promise for the resolution of the given promise when
+ * ``fin`` is done.
+ */
+Q.fin = // XXX legacy
+Q["finally"] = function (object, callback) {
+    return Q(object)["finally"](callback);
+};
+
+Promise.prototype.fin = // XXX legacy
+Promise.prototype["finally"] = function (callback) {
+    callback = Q(callback);
+    return this.then(function (value) {
+        return callback.fcall().then(function () {
+            return value;
+        });
+    }, function (reason) {
+        // TODO attempt to recycle the rejection with "this".
+        return callback.fcall().then(function () {
+            throw reason;
+        });
+    });
+};
+
+/**
+ * Terminates a chain of promises, forcing rejections to be
+ * thrown as exceptions.
+ * @param {Any*} promise at the end of a chain of promises
+ * @returns nothing
+ */
+Q.done = function (object, fulfilled, rejected, progress) {
+    return Q(object).done(fulfilled, rejected, progress);
+};
+
+Promise.prototype.done = function (fulfilled, rejected, progress) {
+    var onUnhandledError = function (error) {
+        // forward to a future turn so that ``when``
+        // does not catch it and turn it into a rejection.
+        nextTick(function () {
+            makeStackTraceLong(error, promise);
+            if (Q.onerror) {
+                Q.onerror(error);
+            } else {
+                throw error;
+            }
+        });
+    };
+
+    // Avoid unnecessary `nextTick`ing via an unnecessary `when`.
+    var promise = fulfilled || rejected || progress ?
+        this.then(fulfilled, rejected, progress) :
+        this;
+
+    if (typeof process === "object" && process && process.domain) {
+        onUnhandledError = process.domain.bind(onUnhandledError);
+    }
+
+    promise.then(void 0, onUnhandledError);
+};
+
+/**
+ * Causes a promise to be rejected if it does not get fulfilled before
+ * some milliseconds time out.
+ * @param {Any*} promise
+ * @param {Number} milliseconds timeout
+ * @param {String} custom error message (optional)
+ * @returns a promise for the resolution of the given promise if it is
+ * fulfilled before the timeout, otherwise rejected.
+ */
+Q.timeout = function (object, ms, message) {
+    return Q(object).timeout(ms, message);
+};
+
+Promise.prototype.timeout = function (ms, message) {
+    var deferred = defer();
+    var timeoutId = setTimeout(function () {
+        deferred.reject(new Error(message || "Timed out after " + ms + " ms"));
+    }, ms);
+
+    this.then(function (value) {
+        clearTimeout(timeoutId);
+        deferred.resolve(value);
+    }, function (exception) {
+        clearTimeout(timeoutId);
+        deferred.reject(exception);
+    }, deferred.notify);
+
+    return deferred.promise;
+};
+
+/**
+ * Returns a promise for the given value (or promised value), some
+ * milliseconds after it resolved. Passes rejections immediately.
+ * @param {Any*} promise
+ * @param {Number} milliseconds
+ * @returns a promise for the resolution of the given promise after milliseconds
+ * time has elapsed since the resolution of the given promise.
+ * If the given promise rejects, that is passed immediately.
+ */
+Q.delay = function (object, timeout) {
+    if (timeout === void 0) {
+        timeout = object;
+        object = void 0;
+    }
+    return Q(object).delay(timeout);
+};
+
+Promise.prototype.delay = function (timeout) {
+    return this.then(function (value) {
+        var deferred = defer();
+        setTimeout(function () {
+            deferred.resolve(value);
+        }, timeout);
+        return deferred.promise;
+    });
+};
+
+/**
+ * Passes a continuation to a Node function, which is called with the given
+ * arguments provided as an array, and returns a promise.
+ *
+ *      Q.nfapply(FS.readFile, [__filename])
+ *      .then(function (content) {
+ *      })
+ *
+ */
+Q.nfapply = function (callback, args) {
+    return Q(callback).nfapply(args);
+};
+
+Promise.prototype.nfapply = function (args) {
+    var deferred = defer();
+    var nodeArgs = array_slice(args);
+    nodeArgs.push(deferred.makeNodeResolver());
+    this.fapply(nodeArgs).fail(deferred.reject);
+    return deferred.promise;
+};
+
+/**
+ * Passes a continuation to a Node function, which is called with the given
+ * arguments provided individually, and returns a promise.
+ * @example
+ * Q.nfcall(FS.readFile, __filename)
+ * .then(function (content) {
+ * })
+ *
+ */
+Q.nfcall = function (callback /*...args*/) {
+    var args = array_slice(arguments, 1);
+    return Q(callback).nfapply(args);
+};
+
+Promise.prototype.nfcall = function (/*...args*/) {
+    var nodeArgs = array_slice(arguments);
+    var deferred = defer();
+    nodeArgs.push(deferred.makeNodeResolver());
+    this.fapply(nodeArgs).fail(deferred.reject);
+    return deferred.promise;
+};
+
+/**
+ * Wraps a NodeJS continuation passing function and returns an equivalent
+ * version that returns a promise.
+ * @example
+ * Q.nfbind(FS.readFile, __filename)("utf-8")
+ * .then(console.log)
+ * .done()
+ */
+Q.nfbind =
+Q.denodeify = function (callback /*...args*/) {
+    var baseArgs = array_slice(arguments, 1);
+    return function () {
+        var nodeArgs = baseArgs.concat(array_slice(arguments));
+        var deferred = defer();
+        nodeArgs.push(deferred.makeNodeResolver());
+        Q(callback).fapply(nodeArgs).fail(deferred.reject);
+        return deferred.promise;
+    };
+};
+
+Promise.prototype.nfbind =
+Promise.prototype.denodeify = function (/*...args*/) {
+    var args = array_slice(arguments);
+    args.unshift(this);
+    return Q.denodeify.apply(void 0, args);
+};
+
+Q.nbind = function (callback, thisp /*...args*/) {
+    var baseArgs = array_slice(arguments, 2);
+    return function () {
+        var nodeArgs = baseArgs.concat(array_slice(arguments));
+        var deferred = defer();
+        nodeArgs.push(deferred.makeNodeResolver());
+        function bound() {
+            return callback.apply(thisp, arguments);
+        }
+        Q(bound).fapply(nodeArgs).fail(deferred.reject);
+        return deferred.promise;
+    };
+};
+
+Promise.prototype.nbind = function (/*thisp, ...args*/) {
+    var args = array_slice(arguments, 0);
+    args.unshift(this);
+    return Q.nbind.apply(void 0, args);
+};
+
+/**
+ * Calls a method of a Node-style object that accepts a Node-style
+ * callback with a given array of arguments, plus a provided callback.
+ * @param object an object that has the named method
+ * @param {String} name name of the method of object
+ * @param {Array} args arguments to pass to the method; the callback
+ * will be provided by Q and appended to these arguments.
+ * @returns a promise for the value or error
+ */
+Q.nmapply = // XXX As proposed by "Redsandro"
+Q.npost = function (object, name, args) {
+    return Q(object).npost(name, args);
+};
+
+Promise.prototype.nmapply = // XXX As proposed by "Redsandro"
+Promise.prototype.npost = function (name, args) {
+    var nodeArgs = array_slice(args || []);
+    var deferred = defer();
+    nodeArgs.push(deferred.makeNodeResolver());
+    this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
+    return deferred.promise;
+};
+
+/**
+ * Calls a method of a Node-style object that accepts a Node-style
+ * callback, forwarding the given variadic arguments, plus a provided
+ * callback argument.
+ * @param object an object that has the named method
+ * @param {String} name name of the method of object
+ * @param ...args arguments to pass to the method; the callback will
+ * be provided by Q and appended to these arguments.
+ * @returns a promise for the value or error
+ */
+Q.nsend = // XXX Based on Mark Miller's proposed "send"
+Q.nmcall = // XXX Based on "Redsandro's" proposal
+Q.ninvoke = function (object, name /*...args*/) {
+    var nodeArgs = array_slice(arguments, 2);
+    var deferred = defer();
+    nodeArgs.push(deferred.makeNodeResolver());
+    Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject);
+    return deferred.promise;
+};
+
+Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send"
+Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal
+Promise.prototype.ninvoke = function (name /*...args*/) {
+    var nodeArgs = array_slice(arguments, 1);
+    var deferred = defer();
+    nodeArgs.push(deferred.makeNodeResolver());
+    this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
+    return deferred.promise;
+};
+
+/**
+ * If a function would like to support both Node continuation-passing-style and
+ * promise-returning-style, it can end its internal promise chain with
+ * `nodeify(nodeback)`, forwarding the optional nodeback argument.  If the user
+ * elects to use a nodeback, the result will be sent there.  If they do not
+ * pass a nodeback, they will receive the result promise.
+ * @param object a result (or a promise for a result)
+ * @param {Function} nodeback a Node.js-style callback
+ * @returns either the promise or nothing
+ */
+Q.nodeify = nodeify;
+function nodeify(object, nodeback) {
+    return Q(object).nodeify(nodeback);
+}
+
+Promise.prototype.nodeify = function (nodeback) {
+    if (nodeback) {
+        this.then(function (value) {
+            nextTick(function () {
+                nodeback(null, value);
+            });
+        }, function (error) {
+            nextTick(function () {
+                nodeback(error);
+            });
+        });
+    } else {
+        return this;
+    }
+};
+
+// All code before this point will be filtered from stack traces.
+var qEndingLine = captureLine();
+
+return Q;
+
+});

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/node_modules/q/queue.js
----------------------------------------------------------------------
diff --git a/bin/node_modules/q/queue.js b/bin/node_modules/q/queue.js
new file mode 100644
index 0000000..1505fd0
--- /dev/null
+++ b/bin/node_modules/q/queue.js
@@ -0,0 +1,35 @@
+
+var Q = require("./q");
+
+module.exports = Queue;
+function Queue() {
+    var ends = Q.defer();
+    var closed = Q.defer();
+    return {
+        put: function (value) {
+            var next = Q.defer();
+            ends.resolve({
+                head: value,
+                tail: next.promise
+            });
+            ends.resolve = next.resolve;
+        },
+        get: function () {
+            var result = ends.promise.get("head");
+            ends.promise = ends.promise.get("tail");
+            return result.fail(function (error) {
+                closed.resolve(error);
+                throw error;
+            });
+        },
+        closed: closed.promise,
+        close: function (error) {
+            error = error || new Error("Can't get value from closed queue");
+            var end = {head: Q.reject(error)};
+            end.tail = end;
+            ends.resolve(end);
+            return closed.promise;
+        }
+    };
+}
+

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/package.json
----------------------------------------------------------------------
diff --git a/bin/package.json b/bin/package.json
index cceb151..87c8d99 100644
--- a/bin/package.json
+++ b/bin/package.json
@@ -5,7 +5,7 @@
     "homepage": "http://github.com/apache/cordova-android",
     "repository": {
         "type": "git",
-        "url": "https://git-wip-us.apache.org/repos/asf/cordova-andorid.git"
+        "url": "https://git-wip-us.apache.org/repos/asf/cordova-android.git"
     },
     "keywords": [
         "cli",
@@ -17,7 +17,8 @@
         "node": ">=0.10.0"
     },
     "dependencies": {
-        "shelljs" : "0.1.4"
+        "shelljs" : "0.1.4",
+        "q": "~0.9"
     },
     "devDependencies": {
     },
@@ -29,4 +30,4 @@
     },
     "contributors": [
     ]
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/build
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/build b/bin/templates/cordova/build
index 752945f..a38f3b6 100755
--- a/bin/templates/cordova/build
+++ b/bin/templates/cordova/build
@@ -27,9 +27,11 @@ var build = require('./lib/build'),
 if(args[2] == '--help' || args[2] == '/?' || args[2] == '-h' ||
                     args[2] == 'help' || args[2] == '-help' || args[2] == '/help') {
     build.help();
-} else if(reqs.run()) {
-    build.run(args[2]);
-    process.exit(0);
 } else {
-    process.exit(2);
-}
\ No newline at end of file
+    reqs.run().then(function() {
+        return build.run(args[2]);
+    }).done(null, function(err) {
+        console.error(err);
+        process.exit(2);
+    });
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/clean
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/clean b/bin/templates/cordova/clean
index 6b72e71..4e0808b 100755
--- a/bin/templates/cordova/clean
+++ b/bin/templates/cordova/clean
@@ -26,9 +26,11 @@ var clean = require('./lib/clean'),
 // Usage support for when args are given
 if(args.length > 2) {
     clean.help();
-} else if(reqs.run()) {
-    clean.run();
-    process.exit(0);
 } else {
-    process.exit(2);
-}
\ No newline at end of file
+    reqs.run().done(function() {
+        return clean.run();
+    }, function(err) {
+        console.error('ERROR: ' + err);
+        process.exit(2);
+    });
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/build.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/build.js b/bin/templates/cordova/lib/build.js
index 84e4e02..e57e26b 100644
--- a/bin/templates/cordova/lib/build.js
+++ b/bin/templates/cordova/lib/build.js
@@ -20,6 +20,8 @@
 */
 
 var shell   = require('shelljs'),
+    exec    = require('./exec'),
+    Q       = require('q'),
     clean   = require('./clean'),
     path    = require('path'),
     fs      = require('fs'),
@@ -27,6 +29,7 @@ var shell   = require('shelljs'),
 
 /*
  * Builds the project with ant.
+ * Returns a promise.
  */
 module.exports.run = function(build_type) {
     //default build type
@@ -34,29 +37,24 @@ module.exports.run = function(build_type) {
     var cmd;
     switch(build_type) {
         case '--debug' :
-            clean.run();
             cmd = 'ant debug -f ' + path.join(ROOT, 'build.xml');
             break;
         case '--release' :
-            clean.run();
             cmd = 'ant release -f ' + path.join(ROOT, 'build.xml');
             break;
         case '--nobuild' :
             console.log('Skipping build...');
-            break;
+            return Q();
         default :
-           console.error('Build option \'' + build_type + '\' not recognized.');
-           process.exit(2);
-           break;
+            return Q.reject('Build option \'' + build_type + '\' not recognized.');
     }
     if(cmd) {
-        var result = shell.exec(cmd, {silent:false, async:false});
-        if(result.code > 0) {
-            console.error('ERROR: Failed to build android project.');
-            console.error(result.output);
-            process.exit(2);
-        }
+        return clean.run() // TODO: Can we stop cleaning every time and let ant build incrementally?
+        .then(function() {
+            return exec(cmd);
+        });
     }
+    return Q();
 }
 
 /*
@@ -86,4 +84,4 @@ module.exports.help = function() {
     console.log('    \'--release\': will build project using ant release');
     console.log('    \'--nobuild\': will skip build process (can be used with run command)');
     process.exit(0);
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/clean.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/clean.js b/bin/templates/cordova/lib/clean.js
index 579a5fa..0f955f6 100644
--- a/bin/templates/cordova/lib/clean.js
+++ b/bin/templates/cordova/lib/clean.js
@@ -19,25 +19,20 @@
        under the License.
 */
 
-var shell = require('shelljs'),
+var exec  = require('./exec'),
     path  = require('path'),
     ROOT = path.join(__dirname, '..', '..');
 
 /*
  * Cleans the project using ant
+ * Returns a promise.
  */
 module.exports.run = function() {
-    var cmd = 'ant clean -f ' + path.join(ROOT, 'build.xml');
-    var result = shell.exec(cmd, {silent:false, async:false});
-    if (result.code > 0) {
-        console.error('ERROR: Failed to clean android project.');
-        console.error(result.output);
-        process.exit(2);
-    }
+    return exec('ant clean -f ' + path.join(ROOT, 'build.xml'));
 }
 
 module.exports.help = function() {
     console.log('Usage: ' + path.relative(process.cwd(), process.argv[1]));
     console.log('Cleans the project directory.');
     process.exit(0);
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/b57317bd/bin/templates/cordova/lib/device.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/device.js b/bin/templates/cordova/lib/device.js
index 46686b6..df2a33c 100644
--- a/bin/templates/cordova/lib/device.js
+++ b/bin/templates/cordova/lib/device.js
@@ -19,24 +19,20 @@
        under the License.
 */
 
-var shell = require('shelljs'),
+var exec  = require('./exec'),
+    Q     = require('q'),
     path  = require('path'),
     build = require('./build'),
     appinfo = require('./appinfo'),
-    exec  = require('child_process').exec,
     ROOT = path.join(__dirname, '..', '..');
 
 /**
- * Returns a list of the device ID's found
+ * Returns a promise for the list of the device ID's found
  */
 module.exports.list = function() {
-    var cmd = 'adb devices';
-    var result = shell.exec(cmd, {silent:true, async:false});
-    if (result.code > 0) {
-        console.error('Failed to execute android command \'' + cmd + '\'.');
-        process.exit(2);
-    } else {
-        var response = result.output.split('\n');
+    return exec('adb devices')
+    .then(function(output) {
+        var response = output.split('\n');
         var device_list = [];
         for (var i = 1; i < response.length; i++) {
             if (response[i].match(/\w+\tdevice/) && !response[i].match(/emulator/)) {
@@ -44,52 +40,47 @@ module.exports.list = function() {
             }
         }
         return device_list;
-    }
+    });
 }
 
 /*
  * Installs a previously built application on the device
  * and launches it.
+ * Returns a promise.
  */
 module.exports.install = function(target) {
-    var device_list = this.list();
-    if (device_list.length > 0) {
+    var launchName;
+    return this.list()
+    .then(function(device_list) {
+        if (!device_list || !device_list.length)
+            return Q.reject('ERROR: Failed to deploy to device, no devices found.');
+
         // default device
         target = typeof target !== 'undefined' ? target : device_list[0];
-        if (device_list.indexOf(target) > -1) {
-            var apk_path = build.get_apk();
-            var launchName = appinfo.getActivityName();
-            console.log('Installing app on device...');
-            cmd = 'adb -s ' + target + ' install -r ' + apk_path;
-            var install = shell.exec(cmd, {silent:false, async:false});
-            if (install.error || install.output.match(/Failure/)) {
-                console.error('ERROR : Failed to install apk to device : ');
-                console.error(install.output);
-                process.exit(2);
-            }
 
-            //unlock screen
-            cmd = 'adb -s ' + target + ' shell input keyevent 82';
-            shell.exec(cmd, {silent:true, async:false});
+        if (device_list.indexOf(target) < 0)
+            return Q.reject('ERROR: Unable to find target \'' + target + '\'.');
 
-            // launch the application
-            console.log('Launching application...');
-            cmd = 'adb -s ' + target + ' shell am start -W -a android.intent.action.MAIN -n ' + launchName;
-            var launch = shell.exec(cmd, {silent:true, async:false});
-            if(launch.code > 0) {
-                console.error('ERROR : Failed to launch application on emulator : ' + launch.error);
-                console.error(launch.output);
-                process.exit(2);
-            } else {
-                console.log('LANCH SUCCESS');
-            }
-        } else {
-            console.error('ERROR : Unable to find target \'' + target + '\'.');
-            console.error('Failed to deploy to device.');
-            process.exit(2);
-        }
-    } else {
-        console.error('ERROR : Failed to deploy to device, no devices found.');
-        process.exit(2);
-    }
+        var apk_path = build.get_apk();
+        launchName = appinfo.getActivityName();
+        console.log('Installing app on device...');
+        var cmd = 'adb -s ' + target + ' install -r ' + apk_path;
+        return exec(cmd);
+    }).then(function(output) {
+        if (output.match(/Failure/)) return Q.reject('ERROR: Failed to install apk to device: ' + output);
+
+        //unlock screen
+        var cmd = 'adb -s ' + target + ' shell input keyevent 82';
+        return exec(cmd);
+    }, function(err) { return Q.reject('ERROR: Failed to install apk to device: ' + err); })
+    .then(function() {
+        // launch the application
+        console.log('Launching application...');
+        var cmd = 'adb -s ' + target + ' shell am start -W -a android.intent.action.MAIN -n ' + launchName;
+        return exec(cmd);
+    }).then(function() {
+        console.log('LANCH SUCCESS');
+    }, function(err) {
+        return Q.reject('ERROR: Failed to launch application on device: ' + err);
+    });
 }