mirror of
https://github.com/apache/cordova-android.git
synced 2025-02-20 23:56:20 +08:00
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.
This commit is contained in:
parent
1f49f29183
commit
b57317bdc2
@ -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);
|
||||
});
|
||||
|
||||
|
@ -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);
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -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()]);
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
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);
|
||||
|
||||
// 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...');
|
||||
|
||||
// build from source. distro should have these files
|
||||
ensureJarIsBuilt(VERSION, target_api);
|
||||
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'));
|
||||
|
||||
console.log('Copying template files...');
|
||||
// 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);
|
||||
|
||||
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'));
|
||||
// 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);
|
||||
|
||||
// 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);
|
||||
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);
|
||||
});
|
||||
};
|
||||
|
||||
|
40
bin/node_modules/q/CONTRIBUTING.md
generated
vendored
Normal file
40
bin/node_modules/q/CONTRIBUTING.md
generated
vendored
Normal file
@ -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.
|
||||
|
19
bin/node_modules/q/LICENSE
generated
vendored
Normal file
19
bin/node_modules/q/LICENSE
generated
vendored
Normal file
@ -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.
|
813
bin/node_modules/q/README.md
generated
vendored
Normal file
813
bin/node_modules/q/README.md
generated
vendored
Normal file
@ -0,0 +1,813 @@
|
||||
[](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)
|
||||
|
71
bin/node_modules/q/benchmark/compare-with-callbacks.js
generated
vendored
Normal file
71
bin/node_modules/q/benchmark/compare-with-callbacks.js
generated
vendored
Normal file
@ -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);
|
||||
}
|
||||
});
|
||||
});
|
36
bin/node_modules/q/benchmark/scenarios.js
generated
vendored
Normal file
36
bin/node_modules/q/benchmark/scenarios.js
generated
vendored
Normal file
@ -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();
|
||||
});
|
||||
});
|
93
bin/node_modules/q/package.json
generated
vendored
Normal file
93
bin/node_modules/q/package.json
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
1937
bin/node_modules/q/q.js
generated
vendored
Normal file
1937
bin/node_modules/q/q.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
35
bin/node_modules/q/queue.js
generated
vendored
Normal file
35
bin/node_modules/q/queue.js
generated
vendored
Normal file
@ -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;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@ -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": [
|
||||
]
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
reqs.run().then(function() {
|
||||
return build.run(args[2]);
|
||||
}).done(null, function(err) {
|
||||
console.error(err);
|
||||
process.exit(2);
|
||||
});
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
reqs.run().done(function() {
|
||||
return clean.run();
|
||||
}, function(err) {
|
||||
console.error('ERROR: ' + err);
|
||||
process.exit(2);
|
||||
});
|
||||
}
|
||||
|
24
bin/templates/cordova/lib/build.js
vendored
24
bin/templates/cordova/lib/build.js
vendored
@ -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);
|
||||
}
|
||||
}
|
||||
|
13
bin/templates/cordova/lib/clean.js
vendored
13
bin/templates/cordova/lib/clean.js
vendored
@ -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);
|
||||
}
|
||||
}
|
||||
|
85
bin/templates/cordova/lib/device.js
vendored
85
bin/templates/cordova/lib/device.js
vendored
@ -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);
|
||||
});
|
||||
}
|
||||
|
349
bin/templates/cordova/lib/emulator.js
vendored
349
bin/templates/cordova/lib/emulator.js
vendored
@ -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);
|
||||
}
|
||||
if (!emulator_id) return Q.reject('ERROR : Failed to start emulator, could not find new emulator');
|
||||
|
||||
//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');
|
||||
//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');
|
||||
|
||||
//unlock screen
|
||||
cmd = 'adb -s ' + emulator_id + ' shell input keyevent 82';
|
||||
shell.exec(cmd, {silent:false, async:false});
|
||||
|
||||
//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) {
|
||||
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);
|
||||
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.');
|
||||
}
|
||||
|
||||
//unlock screen
|
||||
cmd = 'adb -s ' + target + ' shell input keyevent 82';
|
||||
shell.exec(cmd, {silent:true, async:false});
|
||||
// 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();
|
||||
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
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
43
bin/templates/cordova/lib/exec.js
vendored
Normal file
43
bin/templates/cordova/lib/exec.js
vendored
Normal file
@ -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;
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
device.install().done(null, function(err) {
|
||||
console.error('ERROR: ' + err);
|
||||
process.exit(2);
|
||||
});
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
emulator.install(install_target).done(null, function(err) {
|
||||
console.error('ERROR: ' + err);
|
||||
process.exit(2);
|
||||
});
|
||||
|
@ -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]);
|
||||
}
|
||||
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);
|
||||
});
|
||||
|
||||
|
@ -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);
|
||||
}
|
||||
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);
|
||||
});
|
||||
|
@ -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);
|
||||
}
|
||||
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);
|
||||
});
|
||||
|
30
bin/templates/cordova/lib/log.js
vendored
30
bin/templates/cordova/lib/log.js
vendored
@ -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);
|
||||
}
|
||||
}
|
||||
|
124
bin/templates/cordova/lib/run.js
vendored
124
bin/templates/cordova/lib/run.js
vendored
@ -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;
|
||||
}
|
||||
}
|
||||
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);
|
||||
|
||||
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 {
|
||||
emulator.start();
|
||||
// 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');
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// 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 {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
emulator.start(install_target).done(null, function(err) {
|
||||
console.error('ERROR: ' + err);
|
||||
process.exit(2);
|
||||
});
|
||||
|
||||
|
@ -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);
|
||||
}
|
||||
reqs.run().done(function() {
|
||||
return log.run();
|
||||
}, function(err) {
|
||||
console.error('ERROR: ' + err);
|
||||
process.exit(2);
|
||||
});
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
reqs.run().done(function() {
|
||||
return run.run(args);
|
||||
}, function(err) {
|
||||
console.error('ERROR: ' + err);
|
||||
process.exit(2);
|
||||
});
|
||||
}
|
||||
|
@ -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);
|
||||
});
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user