You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by an...@apache.org on 2015/10/20 11:21:20 UTC

[07/12] android commit: CB-9782 Implements PlatformApi contract for Android platform.

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/40028228/bin/templates/cordova/lib/build.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/build.js b/bin/templates/cordova/lib/build.js
index 1139719..db692e9 100644
--- a/bin/templates/cordova/lib/build.js
+++ b/bin/templates/cordova/lib/build.js
@@ -1,716 +1,301 @@
-#!/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.
-*/
-
-/* jshint sub:true */
-
-var shell   = require('shelljs'),
-    spawn   = require('./spawn'),
-    Q       = require('q'),
-    path    = require('path'),
-    fs      = require('fs'),
-    os      = require('os'),
-    ROOT    = path.join(__dirname, '..', '..');
-var check_reqs = require('./check_reqs');
-var exec  = require('./exec');
-
-
-var SIGNING_PROPERTIES = '-signing.properties';
-var MARKER = 'YOUR CHANGES WILL BE ERASED!';
-var TEMPLATE =
-    '# This file is automatically generated.\n' +
-    '# Do not modify this file -- ' + MARKER + '\n';
-
-function findApks(directory) {
-    var ret = [];
-    if (fs.existsSync(directory)) {
-        fs.readdirSync(directory).forEach(function(p) {
-            if (path.extname(p) == '.apk') {
-                ret.push(path.join(directory, p));
-            }
-        });
-    }
-    return ret;
-}
-
-function sortFilesByDate(files) {
-    return files.map(function(p) {
-        return { p: p, t: fs.statSync(p).mtime };
-    }).sort(function(a, b) {
-        var timeDiff = b.t - a.t;
-        return timeDiff === 0 ? a.p.length - b.p.length : timeDiff;
-    }).map(function(p) { return p.p; });
-}
-
-function isAutoGenerated(file) {
-    if(fs.existsSync(file)) {
-        var fileContents = fs.readFileSync(file, 'utf8');
-        return fileContents.indexOf(MARKER) > 0;
-    }
-    return false;
-}
-
-function findOutputApksHelper(dir, build_type, arch) {
-    var ret = findApks(dir).filter(function(candidate) {
-        var apkName = path.basename(candidate);
-        // Need to choose between release and debug .apk.
-        if (build_type === 'debug') {
-            return /-debug/.exec(apkName) && !/-unaligned|-unsigned/.exec(apkName);
-        }
-        if (build_type === 'release') {
-            return /-release/.exec(apkName) && !/-unaligned/.exec(apkName);
-        }
-        return true;
-    });
-    ret = sortFilesByDate(ret);
-    if (ret.length === 0) {
-        return ret;
-    }
-    // Assume arch-specific build if newest apk has -x86 or -arm.
-    var archSpecific = !!/-x86|-arm/.exec(path.basename(ret[0]));
-    // And show only arch-specific ones (or non-arch-specific)
-    ret = ret.filter(function(p) {
-        /*jshint -W018 */
-        return !!/-x86|-arm/.exec(path.basename(p)) == archSpecific;
-        /*jshint +W018 */
-    });
-    if (archSpecific && ret.length > 1) {
-        ret = ret.filter(function(p) {
-            return path.basename(p).indexOf('-' + arch) != -1;
-        });
-    }
-
-    return ret;
-}
-
-function hasCustomRules() {
-    return fs.existsSync(path.join(ROOT, 'custom_rules.xml'));
-}
-
-function extractRealProjectNameFromManifest(projectPath) {
-    var manifestPath = path.join(projectPath, 'AndroidManifest.xml');
-    var manifestData = fs.readFileSync(manifestPath, 'utf8');
-    var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);
-    if (!m) {
-        throw new Error('Could not find package name in ' + manifestPath);
-    }
-
-    var packageName=m[1];
-    var lastDotIndex = packageName.lastIndexOf('.');
-    return packageName.substring(lastDotIndex + 1);
-}
-
-function extractProjectNameFromManifest(projectPath) {
-    var manifestPath = path.join(projectPath, 'AndroidManifest.xml');
-    var manifestData = fs.readFileSync(manifestPath, 'utf8');
-    var m = /<activity[\s\S]*?android:name\s*=\s*"(.*?)"/i.exec(manifestData);
-    if (!m) {
-        throw new Error('Could not find activity name in ' + manifestPath);
-    }
-    return m[1];
-}
-
-function findAllUniq(data, r) {
-    var s = {};
-    var m;
-    while ((m = r.exec(data))) {
-        s[m[1]] = 1;
-    }
-    return Object.keys(s);
-}
-
-function readProjectProperties() {
-    var data = fs.readFileSync(path.join(ROOT, 'project.properties'), 'utf8');
-    return {
-        libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),
-        gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),
-        systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)
-    };
-}
-
-var builders = {
-    ant: {
-        getArgs: function(cmd, opts) {
-            var args = [cmd, '-f', path.join(ROOT, 'build.xml')];
-            // custom_rules.xml is required for incremental builds.
-            if (hasCustomRules()) {
-                args.push('-Dout.dir=ant-build', '-Dgen.absolute.dir=ant-gen');
-            }
-            if(opts.packageInfo) {
-                args.push('-propertyfile=' + path.join(ROOT, opts.buildType + SIGNING_PROPERTIES));
-            }
-            return args;
-        },
-
-        prepEnv: function(opts) {
-            return check_reqs.check_ant()
-            .then(function() {
-                // Copy in build.xml on each build so that:
-                // A) we don't require the Android SDK at project creation time, and
-                // B) we always use the SDK's latest version of it.
-                var sdkDir = process.env['ANDROID_HOME'];
-                var buildTemplate = fs.readFileSync(path.join(sdkDir, 'tools', 'lib', 'build.template'), 'utf8');
-                function writeBuildXml(projectPath) {
-                    var newData = buildTemplate.replace('PROJECT_NAME', extractProjectNameFromManifest(ROOT));
-                    fs.writeFileSync(path.join(projectPath, 'build.xml'), newData);
-                    if (!fs.existsSync(path.join(projectPath, 'local.properties'))) {
-                        fs.writeFileSync(path.join(projectPath, 'local.properties'), TEMPLATE);
-                    }
-                }
-                writeBuildXml(ROOT);
-                var propertiesObj = readProjectProperties();
-                var subProjects = propertiesObj.libs;
-                for (var i = 0; i < subProjects.length; ++i) {
-                    writeBuildXml(path.join(ROOT, subProjects[i]));
-                }
-                if (propertiesObj.systemLibs.length > 0) {
-                    throw new Error('Project contains at least one plugin that requires a system library. This is not supported with ANT. Please build using gradle.');
-                }
-
-                var propertiesFile = opts.buildType + SIGNING_PROPERTIES;
-                var propertiesFilePath = path.join(ROOT, propertiesFile);
-                if (opts.packageInfo) {
-                    fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());
-                } else if(isAutoGenerated(propertiesFilePath)) {
-                    shell.rm('-f', propertiesFilePath);
-                }
-            });
-        },
-
-        /*
-         * Builds the project with ant.
-         * Returns a promise.
-         */
-        build: function(opts) {
-            // Without our custom_rules.xml, we need to clean before building.
-            var ret = Q();
-            if (!hasCustomRules()) {
-                // clean will call check_ant() for us.
-                ret = this.clean(opts);
-            }
-
-            var args = this.getArgs(opts.buildType == 'debug' ? 'debug' : 'release', opts);
-            return check_reqs.check_ant()
-            .then(function() {
-                console.log('Executing: ant ' + args.join(' '));
-                return spawn('ant', args);
-            });
-        },
-
-        clean: function(opts) {
-            var args = this.getArgs('clean', opts);
-            return check_reqs.check_ant()
-            .then(function() {
-                return spawn('ant', args);
-            });
-        },
-
-        findOutputApks: function(build_type) {
-            var binDir = path.join(ROOT, hasCustomRules() ? 'ant-build' : 'bin');
-            return findOutputApksHelper(binDir, build_type, null);
-        }
-    },
-    gradle: {
-        getArgs: function(cmd, opts) {
-            if (cmd == 'release') {
-                cmd = 'cdvBuildRelease';
-            } else if (cmd == 'debug') {
-                cmd = 'cdvBuildDebug';
-            }
-            var args = [cmd, '-b', path.join(ROOT, 'build.gradle')];
-            if (opts.arch) {
-                args.push('-PcdvBuildArch=' + opts.arch);
-            }
-
-            // 10 seconds -> 6 seconds
-            args.push('-Dorg.gradle.daemon=true');
-            args.push.apply(args, opts.extraArgs);
-            // Shaves another 100ms, but produces a "try at own risk" warning. Not worth it (yet):
-            // args.push('-Dorg.gradle.parallel=true');
-            return args;
-        },
-
-        // Makes the project buildable, minus the gradle wrapper.
-        prepBuildFiles: function() {
-            var projectPath = ROOT;
-            // Update the version of build.gradle in each dependent library.
-            var pluginBuildGradle = path.join(projectPath, 'cordova', 'lib', 'plugin-build.gradle');
-            var propertiesObj = readProjectProperties();
-            var subProjects = propertiesObj.libs;
-            for (var i = 0; i < subProjects.length; ++i) {
-                if (subProjects[i] !== 'CordovaLib') {
-                    shell.cp('-f', pluginBuildGradle, path.join(ROOT, subProjects[i], 'build.gradle'));
-                }
-            }
-
-            var name = extractRealProjectNameFromManifest(ROOT);
-            //Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149
-            var settingsGradlePaths =  subProjects.map(function(p){
-                var realDir=p.replace(/[/\\]/g, ':');
-                var libName=realDir.replace(name+'-','');
-                var str='include ":'+libName+'"\n';
-                if(realDir.indexOf(name+'-')!==-1)
-                    str+='project(":'+libName+'").projectDir = new File("'+p+'")\n';
-                return str;
-            });
-
-            // Write the settings.gradle file.
-            fs.writeFileSync(path.join(projectPath, 'settings.gradle'),
-                '// GENERATED FILE - DO NOT EDIT\n' +
-                'include ":"\n' + settingsGradlePaths.join(''));
-            // Update dependencies within build.gradle.
-            var buildGradle = fs.readFileSync(path.join(projectPath, 'build.gradle'), 'utf8');
-            var depsList = '';
-            subProjects.forEach(function(p) {
-                var libName=p.replace(/[/\\]/g, ':').replace(name+'-','');
-                depsList += '    debugCompile project(path: "' + libName + '", configuration: "debug")\n';
-                depsList += '    releaseCompile project(path: "' + libName + '", configuration: "release")\n';
-            });
-            // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390
-            var SYSTEM_LIBRARY_MAPPINGS = [
-                [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],
-                [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']
-            ];
-            propertiesObj.systemLibs.forEach(function(p) {
-                var mavenRef;
-                // It's already in gradle form if it has two ':'s
-                if (/:.*:/.exec(p)) {
-                    mavenRef = p;
-                } else {
-                    for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {
-                        var pair = SYSTEM_LIBRARY_MAPPINGS[i];
-                        if (pair[0].exec(p)) {
-                            mavenRef = p.replace(pair[0], pair[1]);
-                            break;
-                        }
-                    }
-                    if (!mavenRef) {
-                        throw new Error('Unsupported system library (does not work with gradle): ' + p);
-                    }
-                }
-                depsList += '    compile "' + mavenRef + '"\n';
-            });
-            buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + '    $2');
-            var includeList = '';
-            propertiesObj.gradleIncludes.forEach(function(includePath) {
-                includeList += 'apply from: "' + includePath + '"\n';
-            });
-            buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');
-            fs.writeFileSync(path.join(projectPath, 'build.gradle'), buildGradle);
-        },
-
-        prepEnv: function(opts) {
-            var self = this;
-            return check_reqs.check_gradle()
-            .then(function() {
-                return self.prepBuildFiles();
-            }).then(function() {
-                // Copy the gradle wrapper on each build so that:
-                // A) we don't require the Android SDK at project creation time, and
-                // B) we always use the SDK's latest version of it.
-                var projectPath = ROOT;
-                // check_reqs ensures that this is set.
-                var sdkDir = process.env['ANDROID_HOME'];
-                var wrapperDir = path.join(sdkDir, 'tools', 'templates', 'gradle', 'wrapper');
-                if (process.platform == 'win32') {
-                    shell.rm('-f', path.join(projectPath, 'gradlew.bat'));
-                    shell.cp(path.join(wrapperDir, 'gradlew.bat'), projectPath);
-                } else {
-                    shell.rm('-f', path.join(projectPath, 'gradlew'));
-                    shell.cp(path.join(wrapperDir, 'gradlew'), projectPath);
-                }
-                shell.rm('-rf', path.join(projectPath, 'gradle', 'wrapper'));
-                shell.mkdir('-p', path.join(projectPath, 'gradle'));
-                shell.cp('-r', path.join(wrapperDir, 'gradle', 'wrapper'), path.join(projectPath, 'gradle'));
-
-                // If the gradle distribution URL is set, make sure it points to version we want.
-                // If it's not set, do nothing, assuming that we're using a future version of gradle that we don't want to mess with.
-                // For some reason, using ^ and $ don't work.  This does the job, though.
-                var distributionUrlRegex = /distributionUrl.*zip/;
-                var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'http\\://services.gradle.org/distributions/gradle-2.2.1-all.zip';
-                var gradleWrapperPropertiesPath = path.join(projectPath, 'gradle', 'wrapper', 'gradle-wrapper.properties');
-                shell.chmod('u+w', gradleWrapperPropertiesPath);
-                shell.sed('-i', distributionUrlRegex, 'distributionUrl='+distributionUrl, gradleWrapperPropertiesPath);
-
-                var propertiesFile = opts.buildType + SIGNING_PROPERTIES;
-                var propertiesFilePath = path.join(ROOT, propertiesFile);
-                if (opts.packageInfo) {
-                    fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());
-                } else if (isAutoGenerated(propertiesFilePath)) {
-                    shell.rm('-f', propertiesFilePath);
-                }
-            });
-        },
-
-        /*
-         * Builds the project with gradle.
-         * Returns a promise.
-         */
-        build: function(opts) {
-            var wrapper = path.join(ROOT, 'gradlew');
-            var args = this.getArgs(opts.buildType == 'debug' ? 'debug' : 'release', opts);
-            return Q().then(function() {
-                console.log('Running: ' + wrapper + ' ' + args.join(' '));
-                return spawn(wrapper, args);
-            });
-        },
-
-        clean: function(opts) {
-            var builder = this;
-            var wrapper = path.join(ROOT, 'gradlew');
-            var args = builder.getArgs('clean', opts);
-            return Q().then(function() {
-                console.log('Running: ' + wrapper + ' ' + args.join(' '));
-                return spawn(wrapper, args);
-            });
-        },
-
-        findOutputApks: function(build_type, arch) {
-            var binDir = path.join(ROOT, 'build', 'outputs', 'apk');
-            return findOutputApksHelper(binDir, build_type, arch);
-        }
-    },
-
-    none: {
-        prepEnv: function() {
-            return Q();
-        },
-        build: function() {
-            console.log('Skipping build...');
-            return Q(null);
-        },
-        clean: function() {
-            return Q();
-        },
-        findOutputApks: function(build_type, arch) {
-            return sortFilesByDate(builders.ant.findOutputApks(build_type, arch).concat(builders.gradle.findOutputApks(build_type, arch)));
-        }
-    }
-};
-
-module.exports.isBuildFlag = function(flag) {
-    return /^--(debug|release|ant|gradle|nobuild|versionCode=|minSdkVersion=|gradleArg=|keystore=|alias=|password=|storePassword=|keystoreType=|buildConfig=)/.exec(flag);
-};
-
-function parseOpts(options, resolvedTarget) {
-    // Backwards-compatibility: Allow a single string argument
-    if (typeof options == 'string') options = [options];
-
-    var ret = {
-        buildType: 'debug',
-        buildMethod: process.env['ANDROID_BUILD'] || 'gradle',
-        arch: null,
-        extraArgs: []
-    };
-
-    var multiValueArgs = {
-      'versionCode': true,
-      'minSdkVersion': true,
-      'gradleArg': true,
-      'keystore' : true,
-      'alias' : true,
-      'password' : true,
-      'storePassword' : true,
-      'keystoreType' : true,
-      'buildConfig' : true
-    };
-    var packageArgs = {};
-    var buildConfig;
-    // Iterate through command line options
-    for (var i=0; options && (i < options.length); ++i) {
-        if (/^--/.exec(options[i])) {
-            var keyValue = options[i].substring(2).split('=');
-            var flagName = keyValue.shift();
-            var flagValue = keyValue.join('=');
-            if (multiValueArgs[flagName] && !flagValue) {
-                flagValue = options[i + 1];
-                ++i;
-            }
-            switch(flagName) {
-                case 'debug':
-                case 'release':
-                    ret.buildType = flagName;
-                    break;
-                case 'ant':
-                case 'gradle':
-                    ret.buildMethod = flagName;
-                    break;
-                case 'device':
-                case 'emulator':
-                    // Don't need to do anything special to when building for device vs emulator.
-                    // iOS uses this flag to switch on architecture.
-                    break;
-                case 'prepenv' :
-                    ret.prepEnv = true;
-                    break;
-                case 'nobuild' :
-                    ret.buildMethod = 'none';
-                    break;
-                case 'versionCode':
-                    ret.extraArgs.push('-PcdvVersionCode=' + flagValue);
-                    break;
-                case 'minSdkVersion':
-                    ret.extraArgs.push('-PcdvMinSdkVersion=' + flagValue);
-                    break;
-                case 'gradleArg':
-                    ret.extraArgs.push(flagValue);
-                    break;
-                case 'keystore':
-                    packageArgs.keystore = path.relative(ROOT, path.resolve(flagValue));
-                    break;
-                case 'alias':
-                case 'storePassword':
-                case 'password':
-                case 'keystoreType':
-                    packageArgs[flagName] = flagValue;
-                    break;
-                case 'buildConfig':
-                    buildConfig = flagValue;
-                    break;
-                default :
-                    console.warn('Build option --\'' + flagName + '\' not recognized (ignoring).');
-            }
-        } else {
-            console.warn('Build option \'' + options[i] + '\' not recognized (ignoring).');
-        }
-    }
-
-    // If some values are not specified as command line arguments - use build config to supplement them.
-    // Command line arguemnts have precedence over build config.
-    if (buildConfig) {
-        if (!fs.existsSync(buildConfig)) {
-            throw new Error('Specified build config file does not exist: ' + buildConfig);
-        }
-        console.log('Reading build config file: '+ path.resolve(buildConfig));
-        var config = JSON.parse(fs.readFileSync(buildConfig, 'utf8'));
-        if (config.android && config.android[ret.buildType]) {
-            var androidInfo = config.android[ret.buildType];
-            if(androidInfo.keystore && !packageArgs.keystore) {
-                packageArgs.keystore = path.resolve(path.dirname(buildConfig), androidInfo.keystore);
-            }
-
-            ['alias', 'storePassword', 'password','keystoreType'].forEach(function (key){
-                packageArgs[key] = packageArgs[key] || androidInfo[key];
-            });
-        }
-    }
-    if (packageArgs.keystore && packageArgs.alias) {
-        ret.packageInfo = new PackageInfo(packageArgs.keystore, packageArgs.alias, packageArgs.storePassword,
-            packageArgs.password, packageArgs.keystoreType);
-    }
-
-    if(!ret.packageInfo) {
-        if(Object.keys(packageArgs).length > 0) {
-            console.warn('\'keystore\' and \'alias\' need to be specified to generate a signed archive.');
-        }
-    }
-    ret.arch = resolvedTarget && resolvedTarget.arch;
-
-    return ret;
-}
-
-/*
- * Builds the project with the specifed options
- * Returns a promise.
- */
-module.exports.runClean = function(options) {
-    var opts = parseOpts(options);
-    var builder = builders[opts.buildMethod];
-    return builder.prepEnv(opts)
-    .then(function() {
-        return builder.clean(opts);
-    }).then(function() {
-        shell.rm('-rf', path.join(ROOT, 'out'));
-
-        ['debug', 'release'].forEach(function(config) {
-            var propertiesFilePath = path.join(ROOT, config + SIGNING_PROPERTIES);
-            if(isAutoGenerated(propertiesFilePath)){
-                shell.rm('-f', propertiesFilePath);
-            }
-        });
-    });
-};
-
-/*
- * Builds the project with the specifed options
- * Returns a promise.
- */
-module.exports.run = function(options, optResolvedTarget) {
-    var opts = parseOpts(options, optResolvedTarget);
-    var builder = builders[opts.buildMethod];
-    return builder.prepEnv(opts)
-    .then(function() {
-        if (opts.prepEnv) {
-            console.log('Build file successfully prepared.');
-            return;
-        }
-        return builder.build(opts)
-        .then(function() {
-            var apkPaths = builder.findOutputApks(opts.buildType, opts.arch);
-            console.log('Built the following apk(s):');
-            console.log('    ' + apkPaths.join('\n    '));
-            return {
-                apkPaths: apkPaths,
-                buildType: opts.buildType,
-                buildMethod: opts.buildMethod
-            };
-        });
-    });
-};
-
-// Called by plugman after installing plugins, and by create script after creating project.
-module.exports.prepBuildFiles = function() {
-    var builder = builders['gradle'];
-    return builder.prepBuildFiles();
-};
-
-/*
- * Detects the architecture of a device/emulator
- * Returns "arm" or "x86".
- */
-module.exports.detectArchitecture = function(target) {
-    function helper() {
-        return exec('adb -s ' + target + ' shell cat /proc/cpuinfo', os.tmpdir())
-        .then(function(output) {
-            if (/intel/i.exec(output)) {
-                return 'x86';
-            }
-            return 'arm';
-        });
-    }
-    // It sometimes happens (at least on OS X), that this command will hang forever.
-    // To fix it, either unplug & replug device, or restart adb server.
-    return helper().timeout(1000, 'Device communication timed out. Try unplugging & replugging the device.')
-    .then(null, function(err) {
-        if (/timed out/.exec('' + err)) {
-            // adb kill-server doesn't seem to do the trick.
-            // Could probably find a x-platform version of killall, but I'm not actually
-            // sure that this scenario even happens on non-OSX machines.
-            return exec('killall adb')
-            .then(function() {
-                console.log('adb seems hung. retrying.');
-                return helper()
-                .then(null, function() {
-                    // The double kill is sadly often necessary, at least on mac.
-                    console.log('Now device not found... restarting adb again.');
-                    return exec('killall adb')
-                    .then(function() {
-                        return helper()
-                        .then(null, function() {
-                            return Q.reject('USB is flakey. Try unplugging & replugging the device.');
-                        });
-                    });
-                });
-            }, function() {
-                // For non-killall OS's.
-                return Q.reject(err);
-            });
-        }
-        throw err;
-    });
-};
-
-module.exports.findBestApkForArchitecture = function(buildResults, arch) {
-    var paths = buildResults.apkPaths.filter(function(p) {
-        var apkName = path.basename(p);
-        if (buildResults.buildType == 'debug') {
-            return /-debug/.exec(apkName);
-        }
-        return !/-debug/.exec(apkName);
-    });
-    var archPattern = new RegExp('-' + arch);
-    var hasArchPattern = /-x86|-arm/;
-    for (var i = 0; i < paths.length; ++i) {
-        var apkName = path.basename(paths[i]);
-        if (hasArchPattern.exec(apkName)) {
-            if (archPattern.exec(apkName)) {
-                return paths[i];
-            }
-        } else {
-            return paths[i];
-        }
-    }
-    throw new Error('Could not find apk architecture: ' + arch + ' build-type: ' + buildResults.buildType);
-};
-
-function PackageInfo(keystore, alias, storePassword, password, keystoreType) {
-    this.keystore = {
-        'name': 'key.store',
-        'value': keystore
-    };
-    this.alias = {
-        'name': 'key.alias',
-        'value': alias
-    };
-    if (storePassword) {
-        this.storePassword = {
-            'name': 'key.store.password',
-            'value': storePassword
-        };
-    }
-    if (password) {
-        this.password = {
-            'name': 'key.alias.password',
-            'value': password
-        };
-    }
-    if (keystoreType) {
-        this.keystoreType = {
-            'name': 'key.store.type',
-            'value': keystoreType
-        };
-    }
-}
-
-PackageInfo.prototype = {
-    toProperties: function() {
-        var self = this;
-        var result = '';
-        Object.keys(self).forEach(function(key) {
-            result += self[key].name;
-            result += '=';
-            result += self[key].value.replace(/\\/g, '\\\\');
-            result += '\n';
-        });
-        return result;
-    }
-};
-
-module.exports.help = function() {
-    console.log('Usage: ' + path.relative(process.cwd(), path.join(ROOT, 'cordova', 'build')) + ' [flags] [Signed APK flags]');
-    console.log('Flags:');
-    console.log('    \'--debug\': will build project in debug mode (default)');
-    console.log('    \'--release\': will build project for release');
-    console.log('    \'--ant\': will build project with ant');
-    console.log('    \'--gradle\': will build project with gradle (default)');
-    console.log('    \'--nobuild\': will skip build process (useful when using run command)');
-    console.log('    \'--prepenv\': don\'t build, but copy in build scripts where necessary');
-    console.log('    \'--versionCode=#\': Override versionCode for this build. Useful for uploading multiple APKs. Requires --gradle.');
-    console.log('    \'--minSdkVersion=#\': Override minSdkVersion for this build. Useful for uploading multiple APKs. Requires --gradle.');
-    console.log('    \'--gradleArg=<gradle command line arg>\': Extra args to pass to the gradle command. Use one flag per arg. Ex. --gradleArg=-PcdvBuildMultipleApks=true');
-    console.log('');
-    console.log('Signed APK flags (overwrites debug/release-signing.proprties) :');
-    console.log('    \'--keystore=<path to keystore>\': Key store used to build a signed archive. (Required)');
-    console.log('    \'--alias=\': Alias for the key store. (Required)');
-    console.log('    \'--storePassword=\': Password for the key store. (Optional - prompted)');
-    console.log('    \'--password=\': Password for the key. (Optional - prompted)');
-    console.log('    \'--keystoreType\': Type of the keystore. (Optional)');
-    process.exit(0);
-};
+#!/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 Q       = require('q'),
+    path    = require('path'),
+    fs      = require('fs'),
+    nopt = require('nopt');
+
+var Adb = require('./Adb');
+
+var builders = require('./builders/builders');
+var events = require('cordova-common').events;
+var spawn = require('cordova-common').superspawn.spawn;
+var CordovaError = require('cordova-common').CordovaError;
+
+function parseOpts(options, resolvedTarget) {
+    options = options || {};
+    options.argv = nopt({
+        gradle: Boolean,
+        ant: Boolean,
+        prepenv: Boolean,
+        versionCode: String,
+        minSdkVersion: String,
+        gradleArg: String,
+        keystore: path,
+        alias: String,
+        storePassword: String,
+        password: String,
+        keystoreType: String
+    }, {}, options.argv, 0);
+
+    var ret = {
+        buildType: options.release ? 'release' : 'debug',
+        buildMethod: process.env.ANDROID_BUILD || 'gradle',
+        prepEnv: options.argv.prepenv,
+        arch: resolvedTarget && resolvedTarget.arch,
+        extraArgs: []
+    };
+
+    if (options.argv.ant || options.argv.gradle)
+        ret.buildMethod = options.argv.ant ? 'ant' : 'gradle';
+
+    if (options.nobuild) ret.buildMethod = 'none';
+
+    if (options.argv.versionCode)
+        ret.extraArgs.push('-PcdvVersionCode=' + options.versionCode);
+
+    if (options.argv.minSdkVersion)
+        ret.extraArgs.push('-PcdvMinSdkVersion=' + options.minSdkVersion);
+
+    if (options.argv.gradleArg)
+        ret.extraArgs.push(options.gradleArg);
+
+    var packageArgs = {};
+
+    if (options.argv.keystore)
+        packageArgs.keystore = path.relative(this.root, path.resolve(options.argv.keystore));
+
+    ['alias','storePassword','password','keystoreType'].forEach(function (flagName) {
+        if (options.argv[flagName])
+            packageArgs[flagName] = options.argv[flagName];
+    });
+
+    var buildConfig = options.buildConfig;
+
+    // If some values are not specified as command line arguments - use build config to supplement them.
+    // Command line arguemnts have precedence over build config.
+    if (buildConfig) {
+        if (!fs.existsSync(buildConfig)) {
+            throw new Error('Specified build config file does not exist: ' + buildConfig);
+        }
+        events.emit('log', 'Reading build config file: '+ path.resolve(buildConfig));
+        var config = JSON.parse(fs.readFileSync(buildConfig, 'utf8'));
+        if (config.android && config.android[ret.buildType]) {
+            var androidInfo = config.android[ret.buildType];
+            if(androidInfo.keystore && !packageArgs.keystore) {
+                packageArgs.keystore = path.resolve(path.dirname(buildConfig), androidInfo.keystore);
+            }
+
+            ['alias', 'storePassword', 'password','keystoreType'].forEach(function (key){
+                packageArgs[key] = packageArgs[key] || androidInfo[key];
+            });
+        }
+    }
+
+    if (packageArgs.keystore && packageArgs.alias) {
+        ret.packageInfo = new PackageInfo(packageArgs.keystore, packageArgs.alias, packageArgs.storePassword,
+            packageArgs.password, packageArgs.keystoreType);
+    }
+
+    if(!ret.packageInfo) {
+        if(Object.keys(packageArgs).length > 0) {
+            events.emit('warn', '\'keystore\' and \'alias\' need to be specified to generate a signed archive.');
+        }
+    }
+
+    return ret;
+}
+
+/*
+ * Builds the project with the specifed options
+ * Returns a promise.
+ */
+module.exports.runClean = function(options) {
+    var opts = parseOpts(options);
+    var builder = builders.getBuilder(opts.buildMethod);
+    return builder.prepEnv(opts)
+    .then(function() {
+        return builder.clean(opts);
+    });
+};
+
+/**
+ * Builds the project with the specifed options.
+ *
+ * @param   {BuildOptions}  options      A set of options. See PlatformApi.build
+ *   method documentation for reference.
+ * @param   {Object}  optResolvedTarget  A deployment target. Used to pass
+ *   target architecture from upstream 'run' call. TODO: remove this option in
+ *   favor of setting buildOptions.archs field.
+ *
+ * @return  {Promise<Object>}            Promise, resolved with built packages
+ *   information.
+ */
+module.exports.run = function(options, optResolvedTarget) {
+    var opts = parseOpts(options, optResolvedTarget);
+    var builder = builders.getBuilder(opts.buildMethod);
+    var self = this;
+    return builder.prepEnv(opts)
+    .then(function() {
+        if (opts.prepEnv) {
+            self.events.emit('verbose', 'Build file successfully prepared.');
+            return;
+        }
+        return builder.build(opts)
+        .then(function() {
+            var apkPaths = builder.findOutputApks(opts.buildType, opts.arch);
+            self.events.emit('log', 'Built the following apk(s): \n\t' + apkPaths.join('\n\t'));
+            return {
+                apkPaths: apkPaths,
+                buildType: opts.buildType,
+                buildMethod: opts.buildMethod
+            };
+        });
+    });
+};
+
+// Called by plugman after installing plugins, and by create script after creating project.
+module.exports.prepBuildFiles = function() {
+    return builders.getBuilder('gradle').prepBuildFiles();
+};
+
+/*
+ * Detects the architecture of a device/emulator
+ * Returns "arm" or "x86".
+ */
+module.exports.detectArchitecture = function(target) {
+    function helper() {
+        return Adb.shell(target, 'cat /proc/cpuinfo')
+        .then(function(output) {
+            return /intel/i.exec(output) ? 'x86' : 'arm';
+        });
+    }
+    // It sometimes happens (at least on OS X), that this command will hang forever.
+    // To fix it, either unplug & replug device, or restart adb server.
+    return helper()
+    .timeout(1000, new CordovaError('Device communication timed out. Try unplugging & replugging the device.'))
+    .then(null, function(err) {
+        if (/timed out/.exec('' + err)) {
+            // adb kill-server doesn't seem to do the trick.
+            // Could probably find a x-platform version of killall, but I'm not actually
+            // sure that this scenario even happens on non-OSX machines.
+            return spawn('killall', ['adb'])
+            .then(function() {
+                events.emit('verbose', 'adb seems hung. retrying.');
+                return helper()
+                .then(null, function() {
+                    // The double kill is sadly often necessary, at least on mac.
+                    events.emit('warn', 'Now device not found... restarting adb again.');
+                    return spawn('killall', ['adb'])
+                    .then(function() {
+                        return helper()
+                        .then(null, function() {
+                            return Q.reject(new CordovaError('USB is flakey. Try unplugging & replugging the device.'));
+                        });
+                    });
+                });
+            }, function() {
+                // For non-killall OS's.
+                return Q.reject(err);
+            });
+        }
+        throw err;
+    });
+};
+
+module.exports.findBestApkForArchitecture = function(buildResults, arch) {
+    var paths = buildResults.apkPaths.filter(function(p) {
+        var apkName = path.basename(p);
+        if (buildResults.buildType == 'debug') {
+            return /-debug/.exec(apkName);
+        }
+        return !/-debug/.exec(apkName);
+    });
+    var archPattern = new RegExp('-' + arch);
+    var hasArchPattern = /-x86|-arm/;
+    for (var i = 0; i < paths.length; ++i) {
+        var apkName = path.basename(paths[i]);
+        if (hasArchPattern.exec(apkName)) {
+            if (archPattern.exec(apkName)) {
+                return paths[i];
+            }
+        } else {
+            return paths[i];
+        }
+    }
+    throw new Error('Could not find apk architecture: ' + arch + ' build-type: ' + buildResults.buildType);
+};
+
+function PackageInfo(keystore, alias, storePassword, password, keystoreType) {
+    this.keystore = {
+        'name': 'key.store',
+        'value': keystore
+    };
+    this.alias = {
+        'name': 'key.alias',
+        'value': alias
+    };
+    if (storePassword) {
+        this.storePassword = {
+            'name': 'key.store.password',
+            'value': storePassword
+        };
+    }
+    if (password) {
+        this.password = {
+            'name': 'key.alias.password',
+            'value': password
+        };
+    }
+    if (keystoreType) {
+        this.keystoreType = {
+            'name': 'key.store.type',
+            'value': keystoreType
+        };
+    }
+}
+
+PackageInfo.prototype = {
+    toProperties: function() {
+        var self = this;
+        var result = '';
+        Object.keys(self).forEach(function(key) {
+            result += self[key].name;
+            result += '=';
+            result += self[key].value.replace(/\\/g, '\\\\');
+            result += '\n';
+        });
+        return result;
+    }
+};
+
+module.exports.help = function() {
+    console.log('Usage: ' + path.relative(process.cwd(), path.join('../build')) + ' [flags] [Signed APK flags]');
+    console.log('Flags:');
+    console.log('    \'--debug\': will build project in debug mode (default)');
+    console.log('    \'--release\': will build project for release');
+    console.log('    \'--ant\': will build project with ant');
+    console.log('    \'--gradle\': will build project with gradle (default)');
+    console.log('    \'--nobuild\': will skip build process (useful when using run command)');
+    console.log('    \'--prepenv\': don\'t build, but copy in build scripts where necessary');
+    console.log('    \'--versionCode=#\': Override versionCode for this build. Useful for uploading multiple APKs. Requires --gradle.');
+    console.log('    \'--minSdkVersion=#\': Override minSdkVersion for this build. Useful for uploading multiple APKs. Requires --gradle.');
+    console.log('    \'--gradleArg=<gradle command line arg>\': Extra args to pass to the gradle command. Use one flag per arg. Ex. --gradleArg=-PcdvBuildMultipleApks=true');
+    console.log('');
+    console.log('Signed APK flags (overwrites debug/release-signing.proprties) :');
+    console.log('    \'--keystore=<path to keystore>\': Key store used to build a signed archive. (Required)');
+    console.log('    \'--alias=\': Alias for the key store. (Required)');
+    console.log('    \'--storePassword=\': Password for the key store. (Optional - prompted)');
+    console.log('    \'--password=\': Password for the key. (Optional - prompted)');
+    console.log('    \'--keystoreType\': Type of the keystore. (Optional)');
+    process.exit(0);
+};

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/40028228/bin/templates/cordova/lib/builders/AntBuilder.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/builders/AntBuilder.js b/bin/templates/cordova/lib/builders/AntBuilder.js
new file mode 100644
index 0000000..dd47227
--- /dev/null
+++ b/bin/templates/cordova/lib/builders/AntBuilder.js
@@ -0,0 +1,141 @@
+/*
+       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 Q = require('q');
+var fs = require('fs');
+var path = require('path');
+var util = require('util');
+var shell = require('shelljs');
+var spawn = require('cordova-common').superspawn.spawn;
+var CordovaError = require('cordova-common').CordovaError;
+var check_reqs = require('../check_reqs');
+
+var SIGNING_PROPERTIES = '-signing.properties';
+var MARKER = 'YOUR CHANGES WILL BE ERASED!';
+var TEMPLATE =
+    '# This file is automatically generated.\n' +
+    '# Do not modify this file -- ' + MARKER + '\n';
+
+var GenericBuilder = require('./GenericBuilder');
+
+function AntBuilder (projectRoot) {
+    GenericBuilder.call(this, projectRoot);
+
+    this.binDirs = {ant: this.binDirs.ant};
+}
+
+util.inherits(AntBuilder, GenericBuilder);
+
+AntBuilder.prototype.getArgs = function(cmd, opts) {
+    var args = [cmd, '-f', path.join(this.root, 'build.xml')];
+    // custom_rules.xml is required for incremental builds.
+    if (hasCustomRules()) {
+        args.push('-Dout.dir=ant-build', '-Dgen.absolute.dir=ant-gen');
+    }
+    if(opts.packageInfo) {
+        args.push('-propertyfile=' + path.join(this.root, opts.buildType + SIGNING_PROPERTIES));
+    }
+    return args;
+};
+
+AntBuilder.prototype.prepEnv = function(opts) {
+    var self = this;
+    return check_reqs.check_ant()
+    .then(function() {
+        // Copy in build.xml on each build so that:
+        // A) we don't require the Android SDK at project creation time, and
+        // B) we always use the SDK's latest version of it.
+        /*jshint -W069 */
+        var sdkDir = process.env['ANDROID_HOME'];
+        /*jshint +W069 */
+        var buildTemplate = fs.readFileSync(path.join(sdkDir, 'tools', 'lib', 'build.template'), 'utf8');
+        function writeBuildXml(projectPath) {
+            var newData = buildTemplate.replace('PROJECT_NAME', self.extractRealProjectNameFromManifest());
+            fs.writeFileSync(path.join(projectPath, 'build.xml'), newData);
+            if (!fs.existsSync(path.join(projectPath, 'local.properties'))) {
+                fs.writeFileSync(path.join(projectPath, 'local.properties'), TEMPLATE);
+            }
+        }
+        writeBuildXml(self.root);
+        var propertiesObj = self.readProjectProperties();
+        var subProjects = propertiesObj.libs;
+        for (var i = 0; i < subProjects.length; ++i) {
+            writeBuildXml(path.join(self.root, subProjects[i]));
+        }
+        if (propertiesObj.systemLibs.length > 0) {
+            throw new CordovaError('Project contains at least one plugin that requires a system library. This is not supported with ANT. Please build using gradle.');
+        }
+
+        var propertiesFile = opts.buildType + SIGNING_PROPERTIES;
+        var propertiesFilePath = path.join(self.root, propertiesFile);
+        if (opts.packageInfo) {
+            fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());
+        } else if(isAutoGenerated(propertiesFilePath)) {
+            shell.rm('-f', propertiesFilePath);
+        }
+    });
+};
+
+/*
+ * Builds the project with ant.
+ * Returns a promise.
+ */
+AntBuilder.prototype.build = function(opts) {
+    // Without our custom_rules.xml, we need to clean before building.
+    var ret = Q();
+    if (!hasCustomRules()) {
+        // clean will call check_ant() for us.
+        ret = this.clean(opts);
+    }
+
+    var args = this.getArgs(opts.buildType == 'debug' ? 'debug' : 'release', opts);
+    return check_reqs.check_ant()
+    .then(function() {
+        return spawn('ant', args, {stdio: 'inherit'});
+    });
+};
+
+AntBuilder.prototype.clean = function(opts) {
+    var args = this.getArgs('clean', opts);
+    var self = this;
+    return check_reqs.check_ant()
+    .then(function() {
+        return spawn('ant', args, {stdio: 'inherit'});
+    })
+    .then(function () {
+        shell.rm('-rf', path.join(self.root, 'out'));
+
+        ['debug', 'release'].forEach(function(config) {
+            var propertiesFilePath = path.join(self.root, config + SIGNING_PROPERTIES);
+            if(isAutoGenerated(propertiesFilePath)){
+                shell.rm('-f', propertiesFilePath);
+            }
+        });
+    });
+};
+
+module.exports = AntBuilder;
+
+function hasCustomRules(projectRoot) {
+    return fs.existsSync(path.join(projectRoot, 'custom_rules.xml'));
+}
+
+function isAutoGenerated(file) {
+    return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/40028228/bin/templates/cordova/lib/builders/GenericBuilder.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/builders/GenericBuilder.js b/bin/templates/cordova/lib/builders/GenericBuilder.js
new file mode 100644
index 0000000..6363b29
--- /dev/null
+++ b/bin/templates/cordova/lib/builders/GenericBuilder.js
@@ -0,0 +1,138 @@
+/*
+       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 Q = require('q');
+var fs = require('fs');
+var path = require('path');
+var shell = require('shelljs');
+var events = require('cordova-common').events;
+var CordovaError = require('cordova-common').CordovaError;
+
+function GenericBuilder (projectDir) {
+    this.root = projectDir || path.resolve(__dirname, '../../..');
+    this.binDirs = {
+        ant: path.join(this.root, hasCustomRules(this.root) ? 'ant-build' : 'bin'),
+        gradle: path.join(this.root, 'build', 'outputs', 'apk')
+    };
+}
+
+function hasCustomRules(projectRoot) {
+    return fs.existsSync(path.join(projectRoot, 'custom_rules.xml'));
+}
+
+GenericBuilder.prototype.prepEnv = function() {
+    return Q();
+};
+
+GenericBuilder.prototype.build = function() {
+    events.emit('log', 'Skipping build...');
+    return Q(null);
+};
+
+GenericBuilder.prototype.clean = function() {
+    return Q();
+};
+
+GenericBuilder.prototype.findOutputApks = function(build_type, arch) {
+    var self = this;
+    return Object.keys(this.binDirs)
+    .reduce(function (result, builderName) {
+        var binDir = self.binDirs[builderName];
+        return result.concat(findOutputApksHelper(binDir, build_type, builderName === 'ant' ? null : arch));
+    }, [])
+    .sort(apkSorter);
+};
+
+GenericBuilder.prototype.readProjectProperties = function () {
+    function findAllUniq(data, r) {
+        var s = {};
+        var m;
+        while ((m = r.exec(data))) {
+            s[m[1]] = 1;
+        }
+        return Object.keys(s);
+    }
+
+    var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');
+    return {
+        libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),
+        gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),
+        systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)
+    };
+};
+
+GenericBuilder.prototype.extractRealProjectNameFromManifest = function () {
+    var manifestPath = path.join(this.root, 'AndroidManifest.xml');
+    var manifestData = fs.readFileSync(manifestPath, 'utf8');
+    var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);
+    if (!m) {
+        throw new CordovaError('Could not find package name in ' + manifestPath);
+    }
+
+    var packageName=m[1];
+    var lastDotIndex = packageName.lastIndexOf('.');
+    return packageName.substring(lastDotIndex + 1);
+};
+
+module.exports = GenericBuilder;
+
+function apkSorter(fileA, fileB) {
+    var timeDiff = fs.statSync(fileA).mtime - fs.statSync(fileB).mtime;
+    return timeDiff === 0 ? fileA.length - fileB.length : timeDiff;
+}
+
+function findOutputApksHelper(dir, build_type, arch) {
+    var shellSilent = shell.config.silent;
+    shell.config.silent = true;
+
+    var ret = shell.ls(path.join(dir, '*.apk'))
+    .filter(function(candidate) {
+        var apkName = path.basename(candidate);
+        // Need to choose between release and debug .apk.
+        if (build_type === 'debug') {
+            return /-debug/.exec(apkName) && !/-unaligned|-unsigned/.exec(apkName);
+        }
+        if (build_type === 'release') {
+            return /-release/.exec(apkName) && !/-unaligned/.exec(apkName);
+        }
+        return true;
+    })
+    .sort(apkSorter);
+
+    shellSilent = shellSilent;
+
+    if (ret.length === 0) {
+        return ret;
+    }
+    // Assume arch-specific build if newest apk has -x86 or -arm.
+    var archSpecific = !!/-x86|-arm/.exec(path.basename(ret[0]));
+    // And show only arch-specific ones (or non-arch-specific)
+    ret = ret.filter(function(p) {
+        /*jshint -W018 */
+        return !!/-x86|-arm/.exec(path.basename(p)) == archSpecific;
+        /*jshint +W018 */
+    });
+    if (archSpecific && ret.length > 1) {
+        ret = ret.filter(function(p) {
+            return path.basename(p).indexOf('-' + arch) != -1;
+        });
+    }
+
+    return ret;
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/40028228/bin/templates/cordova/lib/builders/GradleBuilder.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/builders/GradleBuilder.js b/bin/templates/cordova/lib/builders/GradleBuilder.js
new file mode 100644
index 0000000..7611423
--- /dev/null
+++ b/bin/templates/cordova/lib/builders/GradleBuilder.js
@@ -0,0 +1,213 @@
+/*
+       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 Q = require('q');
+var fs = require('fs');
+var util = require('util');
+var path = require('path');
+var shell = require('shelljs');
+var spawn = require('cordova-common').superspawn.spawn;
+var CordovaError = require('cordova-common').CordovaError;
+var check_reqs = require('../check_reqs');
+
+var GenericBuilder = require('./GenericBuilder');
+
+var MARKER = 'YOUR CHANGES WILL BE ERASED!';
+var SIGNING_PROPERTIES = '-signing.properties';
+var TEMPLATE =
+    '# This file is automatically generated.\n' +
+    '# Do not modify this file -- ' + MARKER + '\n';
+
+function GradleBuilder (projectRoot) {
+    GenericBuilder.call(this, projectRoot);
+
+    this.binDirs = {gradle: this.binDirs.gradle};
+}
+
+util.inherits(GradleBuilder, GenericBuilder);
+
+GradleBuilder.prototype.getArgs = function(cmd, opts) {
+    if (cmd == 'release') {
+        cmd = 'cdvBuildRelease';
+    } else if (cmd == 'debug') {
+        cmd = 'cdvBuildDebug';
+    }
+    var args = [cmd, '-b', path.join(this.root, 'build.gradle')];
+    if (opts.arch) {
+        args.push('-PcdvBuildArch=' + opts.arch);
+    }
+
+    // 10 seconds -> 6 seconds
+    args.push('-Dorg.gradle.daemon=true');
+    args.push.apply(args, opts.extraArgs);
+    // Shaves another 100ms, but produces a "try at own risk" warning. Not worth it (yet):
+    // args.push('-Dorg.gradle.parallel=true');
+    return args;
+};
+
+// Makes the project buildable, minus the gradle wrapper.
+GradleBuilder.prototype.prepBuildFiles = function() {
+    // Update the version of build.gradle in each dependent library.
+    var pluginBuildGradle = path.join(this.root, 'cordova', 'lib', 'plugin-build.gradle');
+    var propertiesObj = this.readProjectProperties();
+    var subProjects = propertiesObj.libs;
+    for (var i = 0; i < subProjects.length; ++i) {
+        if (subProjects[i] !== 'CordovaLib') {
+            shell.cp('-f', pluginBuildGradle, path.join(this.root, subProjects[i], 'build.gradle'));
+        }
+    }
+
+    var name = this.extractRealProjectNameFromManifest();
+    //Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149
+    var settingsGradlePaths =  subProjects.map(function(p){
+        var realDir=p.replace(/[/\\]/g, ':');
+        var libName=realDir.replace(name+'-','');
+        var str='include ":'+libName+'"\n';
+        if(realDir.indexOf(name+'-')!==-1)
+            str+='project(":'+libName+'").projectDir = new File("'+p+'")\n';
+        return str;
+    });
+
+    // Write the settings.gradle file.
+    fs.writeFileSync(path.join(this.root, 'settings.gradle'),
+        '// GENERATED FILE - DO NOT EDIT\n' +
+        'include ":"\n' + settingsGradlePaths.join(''));
+    // Update dependencies within build.gradle.
+    var buildGradle = fs.readFileSync(path.join(this.root, 'build.gradle'), 'utf8');
+    var depsList = '';
+    subProjects.forEach(function(p) {
+        var libName=p.replace(/[/\\]/g, ':').replace(name+'-','');
+        depsList += '    debugCompile project(path: "' + libName + '", configuration: "debug")\n';
+        depsList += '    releaseCompile project(path: "' + libName + '", configuration: "release")\n';
+    });
+    // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390
+    var SYSTEM_LIBRARY_MAPPINGS = [
+        [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],
+        [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']
+    ];
+    propertiesObj.systemLibs.forEach(function(p) {
+        var mavenRef;
+        // It's already in gradle form if it has two ':'s
+        if (/:.*:/.exec(p)) {
+            mavenRef = p;
+        } else {
+            for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {
+                var pair = SYSTEM_LIBRARY_MAPPINGS[i];
+                if (pair[0].exec(p)) {
+                    mavenRef = p.replace(pair[0], pair[1]);
+                    break;
+                }
+            }
+            if (!mavenRef) {
+                throw new CordovaError('Unsupported system library (does not work with gradle): ' + p);
+            }
+        }
+        depsList += '    compile "' + mavenRef + '"\n';
+    });
+    buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + '    $2');
+    var includeList = '';
+    propertiesObj.gradleIncludes.forEach(function(includePath) {
+        includeList += 'apply from: "' + includePath + '"\n';
+    });
+    buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');
+    fs.writeFileSync(path.join(this.root, 'build.gradle'), buildGradle);
+};
+
+GradleBuilder.prototype.prepEnv = function(opts) {
+    var self = this;
+    return check_reqs.check_gradle()
+    .then(function() {
+        return self.prepBuildFiles();
+    }).then(function() {
+        // Copy the gradle wrapper on each build so that:
+        // A) we don't require the Android SDK at project creation time, and
+        // B) we always use the SDK's latest version of it.
+        // check_reqs ensures that this is set.
+        /*jshint -W069 */
+        var sdkDir = process.env['ANDROID_HOME'];
+        /*jshint +W069 */
+        var wrapperDir = path.join(sdkDir, 'tools', 'templates', 'gradle', 'wrapper');
+        if (process.platform == 'win32') {
+            shell.rm('-f', path.join(self.root, 'gradlew.bat'));
+            shell.cp(path.join(wrapperDir, 'gradlew.bat'), self.root);
+        } else {
+            shell.rm('-f', path.join(self.root, 'gradlew'));
+            shell.cp(path.join(wrapperDir, 'gradlew'), self.root);
+        }
+        shell.rm('-rf', path.join(self.root, 'gradle', 'wrapper'));
+        shell.mkdir('-p', path.join(self.root, 'gradle'));
+        shell.cp('-r', path.join(wrapperDir, 'gradle', 'wrapper'), path.join(self.root, 'gradle'));
+
+        // If the gradle distribution URL is set, make sure it points to version we want.
+        // If it's not set, do nothing, assuming that we're using a future version of gradle that we don't want to mess with.
+        // For some reason, using ^ and $ don't work.  This does the job, though.
+        var distributionUrlRegex = /distributionUrl.*zip/;
+        /*jshint -W069 */
+        var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'http\\://services.gradle.org/distributions/gradle-2.2.1-all.zip';
+        /*jshint +W069 */
+        var gradleWrapperPropertiesPath = path.join(self.root, 'gradle', 'wrapper', 'gradle-wrapper.properties');
+        shell.chmod('u+w', gradleWrapperPropertiesPath);
+        shell.sed('-i', distributionUrlRegex, 'distributionUrl='+distributionUrl, gradleWrapperPropertiesPath);
+
+        var propertiesFile = opts.buildType + SIGNING_PROPERTIES;
+        var propertiesFilePath = path.join(self.root, propertiesFile);
+        if (opts.packageInfo) {
+            fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());
+        } else if (isAutoGenerated(propertiesFilePath)) {
+            shell.rm('-f', propertiesFilePath);
+        }
+    });
+};
+
+/*
+ * Builds the project with gradle.
+ * Returns a promise.
+ */
+GradleBuilder.prototype.build = function(opts) {
+    var wrapper = path.join(this.root, 'gradlew');
+    var args = this.getArgs(opts.buildType == 'debug' ? 'debug' : 'release', opts);
+    return Q().then(function() {
+        return spawn(wrapper, args, {stdio: 'inherit'});
+    });
+};
+
+GradleBuilder.prototype.clean = function(opts) {
+    var builder = this;
+    var wrapper = path.join(this.root, 'gradlew');
+    var args = builder.getArgs('clean', opts);
+    return Q().then(function() {
+        return spawn(wrapper, args, {stdio: 'inherit'});
+    })
+    .then(function () {
+        shell.rm('-rf', path.join(builder.root, 'out'));
+
+        ['debug', 'release'].forEach(function(config) {
+            var propertiesFilePath = path.join(builder.root, config + SIGNING_PROPERTIES);
+            if(isAutoGenerated(propertiesFilePath)){
+                shell.rm('-f', propertiesFilePath);
+            }
+        });
+    });
+};
+
+module.exports = GradleBuilder;
+
+function isAutoGenerated(file) {
+    return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;
+}

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/40028228/bin/templates/cordova/lib/builders/builders.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/builders/builders.js b/bin/templates/cordova/lib/builders/builders.js
new file mode 100644
index 0000000..4921c49
--- /dev/null
+++ b/bin/templates/cordova/lib/builders/builders.js
@@ -0,0 +1,47 @@
+/*
+       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 CordovaError = require('cordova-common').CordovaError;
+
+var knownBuilders = {
+    ant: 'AntBuilder',
+    gradle: 'GradleBuilder',
+    none: 'GenericBuilder'
+};
+
+/**
+ * Helper method that instantiates and returns a builder for specified build
+ *   type.
+ *
+ * @param   {String}  builderType   Builder name to construct and return. Must
+ *   be one of 'ant', 'gradle' or 'none'
+ *
+ * @return  {Builder}               A builder instance for specified build type.
+ */
+module.exports.getBuilder = function (builderType, projectRoot) {
+    if (!knownBuilders[builderType])
+        throw new CordovaError('Builder ' + builderType + ' is not supported.');
+
+    try {
+        var Builder = require('./' + knownBuilders[builderType]);
+        return new Builder(projectRoot);
+    } catch (err) {
+        throw new CordovaError('Failed to instantiate ' + knownBuilders[builderType] + ' builder: ' + err);
+    }
+};

http://git-wip-us.apache.org/repos/asf/cordova-android/blob/40028228/bin/templates/cordova/lib/device.js
----------------------------------------------------------------------
diff --git a/bin/templates/cordova/lib/device.js b/bin/templates/cordova/lib/device.js
index f0d6f89..5dd79b5 100644
--- a/bin/templates/cordova/lib/device.js
+++ b/bin/templates/cordova/lib/device.js
@@ -1,128 +1,106 @@
-#!/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 exec  = require('./exec'),
-    Q     = require('q'),
-    os    = require('os'),
-    build = require('./build'),
-    appinfo = require('./appinfo');
-
-/**
- * Returns a promise for the list of the device ID's found
- * @param lookHarder When true, try restarting adb if no devices are found.
- */
-module.exports.list = function(lookHarder) {
-    function helper() {
-        return exec('adb devices', os.tmpdir())
-        .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/)) {
-                    device_list.push(response[i].replace(/\tdevice/, '').replace('\r', ''));
-                }
-            }
-            return device_list;
-        });
-    }
-    return helper()
-    .then(function(list) {
-        if (list.length === 0 && lookHarder) {
-            // adb kill-server doesn't seem to do the trick.
-            // Could probably find a x-platform version of killall, but I'm not actually
-            // sure that this scenario even happens on non-OSX machines.
-            return exec('killall adb')
-            .then(function() {
-                console.log('Restarting adb to see if more devices are detected.');
-                return helper();
-            }, function() {
-                // For non-killall OS's.
-                return list;
-            });
-        }
-        return list;
-    });
-};
-
-module.exports.resolveTarget = function(target) {
-    return this.list(true)
-    .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 = target || device_list[0];
-
-        if (device_list.indexOf(target) < 0) {
-            return Q.reject('ERROR: Unable to find target \'' + target + '\'.');
-        }
-
-        return build.detectArchitecture(target)
-        .then(function(arch) {
-            return { target: target, arch: arch, isEmulator: false };
-        });
-    });
-};
-
-/*
- * Installs a previously built application on the device
- * and launches it.
- * Returns a promise.
- */
-module.exports.install = function(target, buildResults) {
-    return Q().then(function() {
-        if (target && typeof target == 'object') {
-            return target;
-        }
-        return module.exports.resolveTarget(target);
-    }).then(function(resolvedTarget) {
-        var apk_path = build.findBestApkForArchitecture(buildResults, resolvedTarget.arch);
-        var launchName = appinfo.getActivityName();
-        var pkgName = appinfo.getPackageName();
-        console.log('Using apk: ' + apk_path);
-        console.log('Uninstalling ' + pkgName + ' from device...');
-        // This promise is always resolved, even if 'adb uninstall' fails to uninstall app
-        // or the app doesn't installed at all, so no error catching needed.
-        return exec('adb -s ' + resolvedTarget.target + ' uninstall ' + pkgName, os.tmpdir())
-        .then(function() {
-            console.log('Installing app on device...');
-            var cmd = 'adb -s ' + resolvedTarget.target + ' install -r "' + apk_path + '"';
-            return exec(cmd, os.tmpdir());
-        })
-        .then(function(output) {
-            if (output.match(/Failure/)) return Q.reject('ERROR: Failed to install apk to device: ' + output);
-
-            //unlock screen
-            var cmd = 'adb -s ' + resolvedTarget.target + ' shell input keyevent 82';
-            return exec(cmd, os.tmpdir());
-        }, 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 ' + resolvedTarget.target + ' shell am start -W -a android.intent.action.MAIN -n ' + launchName;
-            return exec(cmd, os.tmpdir());
-        }).then(function() {
-            console.log('LAUNCH SUCCESS');
-        }, function(err) {
-            return Q.reject('ERROR: Failed to launch application on device: ' + err);
-        });
-    });
-};
+#!/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 Q     = require('q'),
+    build = require('./build');
+var path = require('path');
+var Adb = require('./Adb');
+var AndroidManifest = require('./AndroidManifest');
+var spawn = require('cordova-common').superspawn.spawn;
+var CordovaError = require('cordova-common').CordovaError;
+var events = require('cordova-common').events;
+
+/**
+ * Returns a promise for the list of the device ID's found
+ * @param lookHarder When true, try restarting adb if no devices are found.
+ */
+module.exports.list = function(lookHarder) {
+    return Adb.devices()
+    .then(function(list) {
+        if (list.length === 0 && lookHarder) {
+            // adb kill-server doesn't seem to do the trick.
+            // Could probably find a x-platform version of killall, but I'm not actually
+            // sure that this scenario even happens on non-OSX machines.
+            return spawn('killall', ['adb'])
+            .then(function() {
+                events.emit('verbose', 'Restarting adb to see if more devices are detected.');
+                return Adb.devices();
+            }, function() {
+                // For non-killall OS's.
+                return list;
+            });
+        }
+        return list;
+    });
+};
+
+module.exports.resolveTarget = function(target) {
+    return this.list(true)
+    .then(function(device_list) {
+        if (!device_list || !device_list.length) {
+            return Q.reject(new CordovaError('Failed to deploy to device, no devices found.'));
+        }
+        // default device
+        target = target || device_list[0];
+
+        if (device_list.indexOf(target) < 0) {
+            return Q.reject('ERROR: Unable to find target \'' + target + '\'.');
+        }
+
+        return build.detectArchitecture(target)
+        .then(function(arch) {
+            return { target: target, arch: arch, isEmulator: false };
+        });
+    });
+};
+
+/*
+ * Installs a previously built application on the device
+ * and launches it.
+ * Returns a promise.
+ */
+module.exports.install = function(target, buildResults) {
+    return Q().then(function() {
+        if (target && typeof target == 'object') {
+            return target;
+        }
+        return module.exports.resolveTarget(target);
+    }).then(function(resolvedTarget) {
+        var apk_path = build.findBestApkForArchitecture(buildResults, resolvedTarget.arch);
+        var manifest = new AndroidManifest(path.join(__dirname, '../../AndroidManifest.xml'));
+        var pkgName = manifest.getPackageId();
+        var launchName = pkgName + '/.' + manifest.getActivity().getName();
+        events.emit('log', 'Using apk: ' + apk_path);
+        // This promise is always resolved, even if 'adb uninstall' fails to uninstall app
+        // or the app doesn't installed at all, so no error catching needed.
+        return Adb.uninstall(resolvedTarget.target, pkgName)
+        .then(function() {
+            return Adb.install(resolvedTarget.target, apk_path, {replace: true});
+        }).then(function() {
+            //unlock screen
+            return Adb.shell(resolvedTarget.target, 'input keyevent 82');
+        }).then(function() {
+            return Adb.start(resolvedTarget.target, launchName);
+        }).then(function() {
+            events.emit('log', 'LAUNCH SUCCESS');
+        });
+    });
+};


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cordova.apache.org
For additional commands, e-mail: commits-help@cordova.apache.org