<commit_before>#!/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 shelljs = require('shelljs'),
    child_process = require('child_process'),
    Q     = require('q'),
    path  = require('path'),
    fs    = require('fs'),
    which = require('which'),
    ROOT  = path.join(__dirname, '..', '..');

var isWindows = process.platform == 'win32';

function forgivingWhichSync(cmd) {
    try {
        // TODO: Should use shelljs.which() here to have one less dependency.
        return fs.realpathSync(which.sync(cmd));
    } catch (e) {
        return '';
    }
}

function tryCommand(cmd, errMsg, catchStderr) {
    var d = Q.defer();
    child_process.exec(cmd, function(err, stdout, stderr) {
        if (err) d.reject(new Error(errMsg));
        // Sometimes it is necessary to return an stderr instead of stdout in case of success, since
        // some commands prints theirs output to stderr instead of stdout. 'javac' is the example
        else d.resolve((catchStderr ? stderr : stdout).trim());
    });
    return d.promise;
}

// Get valid target from framework/project.properties
module.exports.get_target = function() {
    function extractFromFile(filePath) {
        var target = shelljs.grep(/\btarget=/, filePath);
        if (!target) {
            throw new Error('Could not find android target within: ' + filePath);
        }
        return target.split('=')[1].trim();
    }
    if (fs.existsSync(path.join(ROOT, 'framework', 'project.properties'))) {
        return extractFromFile(path.join(ROOT, 'framework', 'project.properties'));
    }
    if (fs.existsSync(path.join(ROOT, 'project.properties'))) {
        // if no target found, we're probably in a project and project.properties is in ROOT.
        return extractFromFile(path.join(ROOT, 'project.properties'));
    }
    throw new Error('Could not find android target. File missing: ' + path.join(ROOT, 'project.properties'));
};

// Returns a promise. Called only by build and clean commands.
module.exports.check_ant = function() {
    return tryCommand('ant -version', 'Failed to run "ant -version", make sure you have ant installed and added to your PATH.')
    .then(function (output) {
        // Parse Ant version from command output
        return /version ((?:\d+\.)+(?:\d+))/i.exec(output)[1];
    });
};

// Returns a promise. Called only by build and clean commands.
module.exports.check_gradle = function() {
    var sdkDir = process.env['ANDROID_HOME'];
    var message = 'Could not find gradle wrapper within Android SDK. ';
    if (!sdkDir) return Q.reject(message + 'Might need to install Android SDK or set up \'ADROID_HOME\' env variable.');
    var wrapper = path.join(sdkDir, 'tools', 'templates', 'gradle', 'wrapper', 'gradlew');
    return tryCommand('"' + wrapper + '" -v', message + 'Might need to update your Android SDK.\n' +
            'Looked here: ' + path.dirname(wrapper))
    .then(function (output) {
        // Parse Gradle version from command output
        return/^gradle ((?:\d+\.)+(?:\d+))/gim.exec(output)[1];
    });
};

// Returns a promise.
module.exports.check_java = function() {
    var javacPath = forgivingWhichSync('javac');
    var hasJavaHome = !!process.env['JAVA_HOME'];
    return Q().then(function() {
        if (hasJavaHome) {
            // Windows java installer doesn't add javac to PATH, nor set JAVA_HOME (ugh).
            if (!javacPath) {
                process.env['PATH'] += path.delimiter + path.join(process.env['JAVA_HOME'], 'bin');
            }
        } else {
            if (javacPath) {
                var msg = 'Failed to find \'JAVA_HOME\' environment variable. Try setting setting it manually.';
                // OS X has a command for finding JAVA_HOME.
                if (fs.existsSync('/usr/libexec/java_home')) {
                    return tryCommand('/usr/libexec/java_home', msg)
                    .then(function(stdout) {
                        process.env['JAVA_HOME'] = stdout.trim();
                    });
                } else {
                    // See if we can derive it from javac's location.
                    // fs.realpathSync is require on Ubuntu, which symplinks from /usr/bin -> JDK
                    var maybeJavaHome = path.dirname(path.dirname(javacPath));
                    if (fs.existsSync(path.join(maybeJavaHome, 'lib', 'tools.jar'))) {
                        process.env['JAVA_HOME'] = maybeJavaHome;
                    } else {
                        throw new Error(msg);
                    }
                }
            } else if (isWindows) {
                // Try to auto-detect java in the default install paths.
                var oldSilent = shelljs.config.silent;
                shelljs.config.silent = true;
                var firstJdkDir =
                    shelljs.ls(process.env['ProgramFiles'] + '\\java\\jdk*')[0] ||
                    shelljs.ls('C:\\Program Files\\java\\jdk*')[0] ||
                    shelljs.ls('C:\\Program Files (x86)\\java\\jdk*')[0];
                shelljs.config.silent = oldSilent;
                if (firstJdkDir) {
                    // shelljs always uses / in paths.
                    firstJdkDir = firstJdkDir.replace(/\//g, path.sep);
                    if (!javacPath) {
                        process.env['PATH'] += path.delimiter + path.join(firstJdkDir, 'bin');
                    }
                    process.env['JAVA_HOME'] = firstJdkDir;
                }
            }
        }
    }).then(function() {
        var msg =
            'Failed to run "java -version", make sure that you have a JDK installed.\n' +
            'You can get it from: http://www.oracle.com/technetwork/java/javase/downloads.\n';
        if (process.env['JAVA_HOME']) {
            msg += 'Your JAVA_HOME is invalid: ' + process.env['JAVA_HOME'] + '\n';
        }
        return tryCommand('java -version', msg)
        .then(function() {
            // We use tryCommand with catchStderr = true, because
            // javac writes version info to stderr instead of stdout
            return tryCommand('javac -version', msg, true);
        }).then(function (output) {
            return /^javac ((?:\d+\.)+(?:\d+))/i.exec(output)[1];
        });
    });
};

// Returns a promise.
module.exports.check_android = function() {
    return Q().then(function() {
        var androidCmdPath = forgivingWhichSync('android');
        var adbInPath = !!forgivingWhichSync('adb');
        var hasAndroidHome = !!process.env['ANDROID_HOME'] && fs.existsSync(process.env['ANDROID_HOME']);
        function maybeSetAndroidHome(value) {
            if (!hasAndroidHome && fs.existsSync(value)) {
                hasAndroidHome = true;
                process.env['ANDROID_HOME'] = value;
            }
        }
        if (!hasAndroidHome && !androidCmdPath) {
            if (isWindows) {
                // Android Studio 1.0 installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'sdk'));
                // Android Studio pre-1.0 installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-studio', 'sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-studio', 'sdk'));
                // Stand-alone installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-sdk'));
            } else if (process.platform == 'darwin') {
                // Android Studio 1.0 installer
                maybeSetAndroidHome(path.join(process.env['HOME'], 'Library', 'Android', 'sdk'));
                // Android Studio pre-1.0 installer
                maybeSetAndroidHome('/Applications/Android Studio.app/sdk');
                // Stand-alone zip file that user might think to put under /Applications
                maybeSetAndroidHome('/Applications/android-sdk-macosx');
                maybeSetAndroidHome('/Applications/android-sdk');
            }
            if (process.env['HOME']) {
                // Stand-alone zip file that user might think to put under their home directory
                maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk-macosx'));
                maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk'));
            }
        }
        if (hasAndroidHome && !androidCmdPath) {
            process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'tools');
        }
        if (androidCmdPath && !hasAndroidHome) {
            var parentDir = path.dirname(androidCmdPath);
            var grandParentDir = path.dirname(parentDir);
            if (path.basename(parentDir) == 'tools') {
                process.env['ANDROID_HOME'] = path.dirname(parentDir);
                hasAndroidHome = true;
            } else if (fs.existsSync(path.join(grandParentDir, 'tools', 'android'))) {
                process.env['ANDROID_HOME'] = grandParentDir;
                hasAndroidHome = true;
            } else {
                throw new Error('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' +
                    'Detected \'android\' command at ' + parentDir + ' but no \'tools\' directory found near.\n' +
                    'Try reinstall Android SDK or update your PATH to include path to valid SDK directory.');
            }
        }
        if (hasAndroidHome && !adbInPath) {
            process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'platform-tools');
        }
        if (!process.env['ANDROID_HOME']) {
            throw new Error('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' +
                'Failed to find \'android\' command in your \'PATH\'. Try update your \'PATH\' to include path to valid SDK directory.');
        }
        if (!fs.existsSync(process.env['ANDROID_HOME'])) {
            throw new Error('\'ANDROID_HOME\' environment variable is set to non-existent path: ' + process.env['ANDROID_HOME'] +
                '\nTry update it manually to point to valid SDK directory.');
        }
    });
};

module.exports.getAbsoluteAndroidCmd = function() {
    return forgivingWhichSync('android').replace(/(\s)/g, '\\$1');
};

module.exports.check_android_target = function(valid_target) {
    // valid_target can look like:
    //   android-19
    //   android-L
    //   Google Inc.:Google APIs:20
    //   Google Inc.:Glass Development Kit Preview:20
    if (!valid_target) valid_target = module.exports.get_target();
    var msg = 'Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.';
    return tryCommand('android list targets --compact', msg)
    .then(function(output) {
        var targets = output.split('\n');
        if (targets.indexOf(valid_target) >= 0) {
            return targets;
        }

        var androidCmd = module.exports.getAbsoluteAndroidCmd();
        throw new Error('Please install Android target: "' + valid_target + '".\n\n' +
            'Hint: Open the SDK manager by running: ' + androidCmd + '\n' +
            'You will require:\n' +
            '1. "SDK Platform" for ' + valid_target + '\n' +
            '2. "Android SDK Platform-tools (latest)\n' +
            '3. "Android SDK Build-tools" (latest)');
    });
};

// Returns a promise.
module.exports.run = function() {
    return Q.all([this.check_java(), this.check_android().then(this.check_android_target)])
    .then(function() {
        console.log('ANDROID_HOME=' + process.env['ANDROID_HOME']);
        console.log('JAVA_HOME=' + process.env['JAVA_HOME']);
    });
};

/**
 * Object thar represents one of requirements for current platform.
 * @param {String} id         The unique identifier for this requirements.
 * @param {String} name       The name of requirements. Human-readable field.
 * @param {String} version    The version of requirement installed. In some cases could be an array of strings
 *                            (for example, check_android_target returns an array of android targets installed)
 * @param {Boolean} installed Indicates whether the requirement is installed or not
 */
var Requirement = function (id, name, version, installed) {
    this.id = id;
    this.name = name;
    this.installed = installed || false;
    this.metadata = {
        version: version,
    };
};

/**
 * Methods that runs all checks one by one and returns a result of checks
 * as an array of Requirement objects. This method intended to be used by cordova-lib check_reqs method
 *
 * @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.
 */
module.exports.check_all = function() {

    var requirements = [
        new Requirement('java', 'Java JDK'),
        new Requirement('androidSdk', 'Android SDK'),
        new Requirement('androidTarget', 'Android target'),
        new Requirement('gradle', 'Gradle')
    ];

    var checkFns = [
        this.check_java,
        this.check_android,
        this.check_android_target,
        this.check_gradle
    ];

    // Then execute requirement checks one-by-one
    return checkFns.reduce(function (promise, checkFn, idx) {
        // Update each requirement with results
        var requirement = requirements[idx];
        return promise.then(checkFn)
        .then(function (version) {
            requirement.installed = true;
            requirement.metadata.version = version;
        }, function (err) {
            requirement.metadata.reason = err;
        });
    }, Q())
    .then(function () {
        // When chain is completed, return requirements array to upstream API
        return requirements;
    });
};
<commit_msg>CB-9389 Fixes build/check_reqs hang<commit_after>#!/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 shelljs = require('shelljs'),
    child_process = require('child_process'),
    Q     = require('q'),
    path  = require('path'),
    fs    = require('fs'),
    which = require('which'),
    ROOT  = path.join(__dirname, '..', '..');

var isWindows = process.platform == 'win32';

function forgivingWhichSync(cmd) {
    try {
        // TODO: Should use shelljs.which() here to have one less dependency.
        return fs.realpathSync(which.sync(cmd));
    } catch (e) {
        return '';
    }
}

function tryCommand(cmd, errMsg, catchStderr) {
    var d = Q.defer();
    child_process.exec(cmd, function(err, stdout, stderr) {
        if (err) d.reject(new Error(errMsg));
        // Sometimes it is necessary to return an stderr instead of stdout in case of success, since
        // some commands prints theirs output to stderr instead of stdout. 'javac' is the example
        else d.resolve((catchStderr ? stderr : stdout).trim());
    });
    return d.promise;
}

// Get valid target from framework/project.properties
module.exports.get_target = function() {
    function extractFromFile(filePath) {
        var target = shelljs.grep(/\btarget=/, filePath);
        if (!target) {
            throw new Error('Could not find android target within: ' + filePath);
        }
        return target.split('=')[1].trim();
    }
    if (fs.existsSync(path.join(ROOT, 'framework', 'project.properties'))) {
        return extractFromFile(path.join(ROOT, 'framework', 'project.properties'));
    }
    if (fs.existsSync(path.join(ROOT, 'project.properties'))) {
        // if no target found, we're probably in a project and project.properties is in ROOT.
        return extractFromFile(path.join(ROOT, 'project.properties'));
    }
    throw new Error('Could not find android target. File missing: ' + path.join(ROOT, 'project.properties'));
};

// Returns a promise. Called only by build and clean commands.
module.exports.check_ant = function() {
    return tryCommand('ant -version', 'Failed to run "ant -version", make sure you have ant installed and added to your PATH.')
    .then(function (output) {
        // Parse Ant version from command output
        return /version ((?:\d+\.)+(?:\d+))/i.exec(output)[1];
    });
};

// Returns a promise. Called only by build and clean commands.
module.exports.check_gradle = function() {
    var sdkDir = process.env['ANDROID_HOME'];
    var wrapperDir = path.join(sdkDir, 'tools', 'templates', 'gradle', 'wrapper');
    if (!fs.existsSync(wrapperDir)) {
        return Q.reject(new Error('Could not find gradle wrapper within android sdk. Might need to update your Android SDK.\n' +
            'Looked here: ' + wrapperDir));
    }
    return Q.when();
};

// Returns a promise.
module.exports.check_java = function() {
    var javacPath = forgivingWhichSync('javac');
    var hasJavaHome = !!process.env['JAVA_HOME'];
    return Q().then(function() {
        if (hasJavaHome) {
            // Windows java installer doesn't add javac to PATH, nor set JAVA_HOME (ugh).
            if (!javacPath) {
                process.env['PATH'] += path.delimiter + path.join(process.env['JAVA_HOME'], 'bin');
            }
        } else {
            if (javacPath) {
                var msg = 'Failed to find \'JAVA_HOME\' environment variable. Try setting setting it manually.';
                // OS X has a command for finding JAVA_HOME.
                if (fs.existsSync('/usr/libexec/java_home')) {
                    return tryCommand('/usr/libexec/java_home', msg)
                    .then(function(stdout) {
                        process.env['JAVA_HOME'] = stdout.trim();
                    });
                } else {
                    // See if we can derive it from javac's location.
                    // fs.realpathSync is require on Ubuntu, which symplinks from /usr/bin -> JDK
                    var maybeJavaHome = path.dirname(path.dirname(javacPath));
                    if (fs.existsSync(path.join(maybeJavaHome, 'lib', 'tools.jar'))) {
                        process.env['JAVA_HOME'] = maybeJavaHome;
                    } else {
                        throw new Error(msg);
                    }
                }
            } else if (isWindows) {
                // Try to auto-detect java in the default install paths.
                var oldSilent = shelljs.config.silent;
                shelljs.config.silent = true;
                var firstJdkDir =
                    shelljs.ls(process.env['ProgramFiles'] + '\\java\\jdk*')[0] ||
                    shelljs.ls('C:\\Program Files\\java\\jdk*')[0] ||
                    shelljs.ls('C:\\Program Files (x86)\\java\\jdk*')[0];
                shelljs.config.silent = oldSilent;
                if (firstJdkDir) {
                    // shelljs always uses / in paths.
                    firstJdkDir = firstJdkDir.replace(/\//g, path.sep);
                    if (!javacPath) {
                        process.env['PATH'] += path.delimiter + path.join(firstJdkDir, 'bin');
                    }
                    process.env['JAVA_HOME'] = firstJdkDir;
                }
            }
        }
    }).then(function() {
        var msg =
            'Failed to run "java -version", make sure that you have a JDK installed.\n' +
            'You can get it from: http://www.oracle.com/technetwork/java/javase/downloads.\n';
        if (process.env['JAVA_HOME']) {
            msg += 'Your JAVA_HOME is invalid: ' + process.env['JAVA_HOME'] + '\n';
        }
        return tryCommand('java -version', msg)
        .then(function() {
            // We use tryCommand with catchStderr = true, because
            // javac writes version info to stderr instead of stdout
            return tryCommand('javac -version', msg, true);
        }).then(function (output) {
            return /^javac ((?:\d+\.)+(?:\d+))/i.exec(output)[1];
        });
    });
};

// Returns a promise.
module.exports.check_android = function() {
    return Q().then(function() {
        var androidCmdPath = forgivingWhichSync('android');
        var adbInPath = !!forgivingWhichSync('adb');
        var hasAndroidHome = !!process.env['ANDROID_HOME'] && fs.existsSync(process.env['ANDROID_HOME']);
        function maybeSetAndroidHome(value) {
            if (!hasAndroidHome && fs.existsSync(value)) {
                hasAndroidHome = true;
                process.env['ANDROID_HOME'] = value;
            }
        }
        if (!hasAndroidHome && !androidCmdPath) {
            if (isWindows) {
                // Android Studio 1.0 installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'sdk'));
                // Android Studio pre-1.0 installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-studio', 'sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-studio', 'sdk'));
                // Stand-alone installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-sdk'));
            } else if (process.platform == 'darwin') {
                // Android Studio 1.0 installer
                maybeSetAndroidHome(path.join(process.env['HOME'], 'Library', 'Android', 'sdk'));
                // Android Studio pre-1.0 installer
                maybeSetAndroidHome('/Applications/Android Studio.app/sdk');
                // Stand-alone zip file that user might think to put under /Applications
                maybeSetAndroidHome('/Applications/android-sdk-macosx');
                maybeSetAndroidHome('/Applications/android-sdk');
            }
            if (process.env['HOME']) {
                // Stand-alone zip file that user might think to put under their home directory
                maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk-macosx'));
                maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk'));
            }
        }
        if (hasAndroidHome && !androidCmdPath) {
            process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'tools');
        }
        if (androidCmdPath && !hasAndroidHome) {
            var parentDir = path.dirname(androidCmdPath);
            var grandParentDir = path.dirname(parentDir);
            if (path.basename(parentDir) == 'tools') {
                process.env['ANDROID_HOME'] = path.dirname(parentDir);
                hasAndroidHome = true;
            } else if (fs.existsSync(path.join(grandParentDir, 'tools', 'android'))) {
                process.env['ANDROID_HOME'] = grandParentDir;
                hasAndroidHome = true;
            } else {
                throw new Error('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' +
                    'Detected \'android\' command at ' + parentDir + ' but no \'tools\' directory found near.\n' +
                    'Try reinstall Android SDK or update your PATH to include path to valid SDK directory.');
            }
        }
        if (hasAndroidHome && !adbInPath) {
            process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'platform-tools');
        }
        if (!process.env['ANDROID_HOME']) {
            throw new Error('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' +
                'Failed to find \'android\' command in your \'PATH\'. Try update your \'PATH\' to include path to valid SDK directory.');
        }
        if (!fs.existsSync(process.env['ANDROID_HOME'])) {
            throw new Error('\'ANDROID_HOME\' environment variable is set to non-existent path: ' + process.env['ANDROID_HOME'] +
                '\nTry update it manually to point to valid SDK directory.');
        }
    });
};

module.exports.getAbsoluteAndroidCmd = function() {
    return forgivingWhichSync('android').replace(/(\s)/g, '\\$1');
};

module.exports.check_android_target = function(valid_target) {
    // valid_target can look like:
    //   android-19
    //   android-L
    //   Google Inc.:Google APIs:20
    //   Google Inc.:Glass Development Kit Preview:20
    if (!valid_target) valid_target = module.exports.get_target();
    var msg = 'Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.';
    return tryCommand('android list targets --compact', msg)
    .then(function(output) {
        var targets = output.split('\n');
        if (targets.indexOf(valid_target) >= 0) {
            return targets;
        }

        var androidCmd = module.exports.getAbsoluteAndroidCmd();
        throw new Error('Please install Android target: "' + valid_target + '".\n\n' +
            'Hint: Open the SDK manager by running: ' + androidCmd + '\n' +
            'You will require:\n' +
            '1. "SDK Platform" for ' + valid_target + '\n' +
            '2. "Android SDK Platform-tools (latest)\n' +
            '3. "Android SDK Build-tools" (latest)');
    });
};

// Returns a promise.
module.exports.run = function() {
    return Q.all([this.check_java(), this.check_android().then(this.check_android_target)])
    .then(function() {
        console.log('ANDROID_HOME=' + process.env['ANDROID_HOME']);
        console.log('JAVA_HOME=' + process.env['JAVA_HOME']);
    });
};

/**
 * Object thar represents one of requirements for current platform.
 * @param {String} id         The unique identifier for this requirements.
 * @param {String} name       The name of requirements. Human-readable field.
 * @param {String} version    The version of requirement installed. In some cases could be an array of strings
 *                            (for example, check_android_target returns an array of android targets installed)
 * @param {Boolean} installed Indicates whether the requirement is installed or not
 */
var Requirement = function (id, name, version, installed) {
    this.id = id;
    this.name = name;
    this.installed = installed || false;
    this.metadata = {
        version: version,
    };
};

/**
 * Methods that runs all checks one by one and returns a result of checks
 * as an array of Requirement objects. This method intended to be used by cordova-lib check_reqs method
 *
 * @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.
 */
module.exports.check_all = function() {

    var requirements = [
        new Requirement('java', 'Java JDK'),
        new Requirement('androidSdk', 'Android SDK'),
        new Requirement('androidTarget', 'Android target'),
        new Requirement('gradle', 'Gradle')
    ];

    var checkFns = [
        this.check_java,
        this.check_android,
        this.check_android_target,
        this.check_gradle
    ];

    // Then execute requirement checks one-by-one
    return checkFns.reduce(function (promise, checkFn, idx) {
        // Update each requirement with results
        var requirement = requirements[idx];
        return promise.then(checkFn)
        .then(function (version) {
            requirement.installed = true;
            requirement.metadata.version = version;
        }, function (err) {
            requirement.metadata.reason = err;
        });
    }, Q())
    .then(function () {
        // When chain is completed, return requirements array to upstream API
        return requirements;
    });
};
<|endoftext|>


<commit_before>#!/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 shelljs = require('shelljs'),
    child_process = require('child_process'),
    Q     = require('q'),
    path  = require('path'),
    fs    = require('fs'),
    which = require('which'),
    ROOT  = path.join(__dirname, '..', '..');

var isWindows = process.platform == 'win32';

function forgivingWhichSync(cmd) {
    try {
        // TODO: Should use shelljs.which() here to have one less dependency.
        return fs.realpathSync(which.sync(cmd));
    } catch (e) {
        return '';
    }
}

function tryCommand(cmd, errMsg, catchStderr) {
    var d = Q.defer();
    child_process.exec(cmd, function(err, stdout, stderr) {
        if (err) d.reject(new Error(errMsg));
        // Sometimes it is necessary to return an stderr instead of stdout in case of success, since
        // some commands prints theirs output to stderr instead of stdout. 'javac' is the example
        else d.resolve((catchStderr ? stderr : stdout).trim());
    });
    return d.promise;
}

// Get valid target from framework/project.properties
module.exports.get_target = function() {
    function extractFromFile(filePath) {
        var target = shelljs.grep(/\btarget=/, filePath);
        if (!target) {
            throw new Error('Could not find android target within: ' + filePath);
        }
        return target.split('=')[1].trim();
    }
    if (fs.existsSync(path.join(ROOT, 'framework', 'project.properties'))) {
        return extractFromFile(path.join(ROOT, 'framework', 'project.properties'));
    }
    if (fs.existsSync(path.join(ROOT, 'project.properties'))) {
        // if no target found, we're probably in a project and project.properties is in ROOT.
        return extractFromFile(path.join(ROOT, 'project.properties'));
    }
    throw new Error('Could not find android target. File missing: ' + path.join(ROOT, 'project.properties'));
};

// Returns a promise. Called only by build and clean commands.
module.exports.check_ant = function() {
    return tryCommand('ant -version', 'Failed to run "ant -version", make sure you have ant installed and added to your PATH.')
    .then(function (output) {
        // Parse Ant version from command output
        return /version ((?:\d+\.)+(?:\d+))/i.exec(output)[1];
    });
};

// Returns a promise. Called only by build and clean commands.
module.exports.check_gradle = function() {
    var sdkDir = process.env['ANDROID_HOME'];
    var message = 'Could not find gradle wrapper within Android SDK. ';
    if (!sdkDir) return Q.reject(message + 'Might need to install Android SDK or set up \'ADROID_HOME\' env variable.');
    var wrapper = path.join(sdkDir, 'tools', 'templates', 'gradle', 'wrapper', 'gradlew');
    return tryCommand(wrapper + ' -v', message + 'Might need to update your Android SDK.\n' +
            'Looked here: ' + path.basename(wrapper))
    .then(function (output) {
        // Parse Gradle version from command output
        return/^gradle ((?:\d+\.)+(?:\d+))/gim.exec(output)[1];
    });
};

// Returns a promise.
module.exports.check_java = function() {
    var javacPath = forgivingWhichSync('javac');
    var hasJavaHome = !!process.env['JAVA_HOME'];
    return Q().then(function() {
        if (hasJavaHome) {
            // Windows java installer doesn't add javac to PATH, nor set JAVA_HOME (ugh).
            if (!javacPath) {
                process.env['PATH'] += path.delimiter + path.join(process.env['JAVA_HOME'], 'bin');
            }
        } else {
            if (javacPath) {
                var msg = 'Failed to find \'JAVA_HOME\' environment variable. Try setting setting it manually.';
                // OS X has a command for finding JAVA_HOME.
                if (fs.existsSync('/usr/libexec/java_home')) {
                    return tryCommand('/usr/libexec/java_home', msg)
                    .then(function(stdout) {
                        process.env['JAVA_HOME'] = stdout.trim();
                    });
                } else {
                    // See if we can derive it from javac's location.
                    // fs.realpathSync is require on Ubuntu, which symplinks from /usr/bin -> JDK
                    var maybeJavaHome = path.dirname(path.dirname(javacPath));
                    if (fs.existsSync(path.join(maybeJavaHome, 'lib', 'tools.jar'))) {
                        process.env['JAVA_HOME'] = maybeJavaHome;
                    } else {
                        throw new Error(msg);
                    }
                }
            } else if (isWindows) {
                // Try to auto-detect java in the default install paths.
                var oldSilent = shelljs.config.silent;
                shelljs.config.silent = true;
                var firstJdkDir =
                    shelljs.ls(process.env['ProgramFiles'] + '\\java\\jdk*')[0] ||
                    shelljs.ls('C:\\Program Files\\java\\jdk*')[0] ||
                    shelljs.ls('C:\\Program Files (x86)\\java\\jdk*')[0];
                shelljs.config.silent = oldSilent;
                if (firstJdkDir) {
                    // shelljs always uses / in paths.
                    firstJdkDir = firstJdkDir.replace(/\//g, path.sep);
                    if (!javacPath) {
                        process.env['PATH'] += path.delimiter + path.join(firstJdkDir, 'bin');
                    }
                    process.env['JAVA_HOME'] = firstJdkDir;
                }
            }
        }
    }).then(function() {
        var msg =
            'Failed to run "java -version", make sure that you have a JDK installed.\n' +
            'You can get it from: http://www.oracle.com/technetwork/java/javase/downloads.\n';
        if (process.env['JAVA_HOME']) {
            msg += 'Your JAVA_HOME is invalid: ' + process.env['JAVA_HOME'] + '\n';
        }
        return tryCommand('java -version', msg)
        .then(function() {
            // We use tryCommand with catchStderr = true, because
            // javac writes version info to stderr instead of stdout
            return tryCommand('javac -version', msg, true);
        }).then(function (output) {
            return /^javac ((?:\d+\.)+(?:\d+))/i.exec(output)[1];
        });
    });
};

// Returns a promise.
module.exports.check_android = function() {
    return Q().then(function() {
        var androidCmdPath = forgivingWhichSync('android');
        var adbInPath = !!forgivingWhichSync('adb');
        var hasAndroidHome = !!process.env['ANDROID_HOME'] && fs.existsSync(process.env['ANDROID_HOME']);
        function maybeSetAndroidHome(value) {
            if (!hasAndroidHome && fs.existsSync(value)) {
                hasAndroidHome = true;
                process.env['ANDROID_HOME'] = value;
            }
        }
        if (!hasAndroidHome && !androidCmdPath) {
            if (isWindows) {
                // Android Studio 1.0 installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'sdk'));
                // Android Studio pre-1.0 installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-studio', 'sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-studio', 'sdk'));
                // Stand-alone installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-sdk'));
            } else if (process.platform == 'darwin') {
                // Android Studio 1.0 installer
                maybeSetAndroidHome(path.join(process.env['HOME'], 'Library', 'Android', 'sdk'));
                // Android Studio pre-1.0 installer
                maybeSetAndroidHome('/Applications/Android Studio.app/sdk');
                // Stand-alone zip file that user might think to put under /Applications
                maybeSetAndroidHome('/Applications/android-sdk-macosx');
                maybeSetAndroidHome('/Applications/android-sdk');
            }
            if (process.env['HOME']) {
                // Stand-alone zip file that user might think to put under their home directory
                maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk-macosx'));
                maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk'));
            }
        }
        if (hasAndroidHome && !androidCmdPath) {
            process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'tools');
        }
        if (androidCmdPath && !hasAndroidHome) {
            var parentDir = path.dirname(androidCmdPath);
            var grandParentDir = path.dirname(parentDir);
            if (path.basename(parentDir) == 'tools') {
                process.env['ANDROID_HOME'] = path.dirname(parentDir);
                hasAndroidHome = true;
            } else if (fs.existsSync(path.join(grandParentDir, 'tools', 'android'))) {
                process.env['ANDROID_HOME'] = grandParentDir;
                hasAndroidHome = true;
            } else {
                throw new Error('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' +
                    'Detected \'android\' command at ' + parentDir + ' but no \'tools\' directory found near.\n' +
                    'Try reinstall Android SDK or update your PATH to include path to valid SDK directory.');
            }
        }
        if (hasAndroidHome && !adbInPath) {
            process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'platform-tools');
        }
        if (!process.env['ANDROID_HOME']) {
            throw new Error('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' +
                'Failed to find \'android\' command in your \'PATH\'. Try update your \'PATH\' to include path to valid SDK directory.');
        }
        if (!fs.existsSync(process.env['ANDROID_HOME'])) {
            throw new Error('\'ANDROID_HOME\' environment variable is set to non-existent path: ' + process.env['ANDROID_HOME'] +
                '\nTry update it manually to point to valid SDK directory.');
        }
    });
};

module.exports.getAbsoluteAndroidCmd = function() {
    return forgivingWhichSync('android').replace(/(\s)/g, '\\$1');
};

module.exports.check_android_target = function(valid_target) {
    // valid_target can look like:
    //   android-19
    //   android-L
    //   Google Inc.:Google APIs:20
    //   Google Inc.:Glass Development Kit Preview:20
    if (!valid_target) valid_target = module.exports.get_target();
    var msg = 'Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.';
    return tryCommand('android list targets --compact', msg)
    .then(function(output) {
        var targets = output.split('\n');
        if (targets.indexOf(valid_target) >= 0) {
            return targets;
        }

        var androidCmd = module.exports.getAbsoluteAndroidCmd();
        throw new Error('Please install Android target: "' + valid_target + '".\n\n' +
            'Hint: Open the SDK manager by running: ' + androidCmd + '\n' +
            'You will require:\n' +
            '1. "SDK Platform" for ' + valid_target + '\n' +
            '2. "Android SDK Platform-tools (latest)\n' +
            '3. "Android SDK Build-tools" (latest)');
    });
};

// Returns a promise.
module.exports.run = function() {
    return Q.all([this.check_java(), this.check_android(), this.check_android_target()])
    .then(function() {
        console.log('ANDROID_HOME=' + process.env['ANDROID_HOME']);
        console.log('JAVA_HOME=' + process.env['JAVA_HOME']);
    });
};

/**
 * Object thar represents one of requirements for current platform.
 * @param {String} id         The unique identifier for this requirements.
 * @param {String} name       The name of requirements. Human-readable field.
 * @param {String} version    The version of requirement installed. In some cases could be an array of strings
 *                            (for example, check_android_target returns an array of android targets installed)
 * @param {Boolean} installed Indicates whether the requirement is installed or not
 */
var Requirement = function (id, name, version, installed) {
    this.id = id;
    this.name = name;
    this.installed = installed || false;
    this.metadata = {
        version: version,
    };
};

/**
 * Methods that runs all checks one by one and returns a result of checks
 * as an array of Requirement objects. This method intended to be used by cordova-lib check_reqs method
 *
 * @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.
 */
module.exports.check_all = function() {

    var requirements = [
        new Requirement('java', 'Java JDK'),
        new Requirement('androidSdk', 'Android SDK'),
        new Requirement('androidTarget', 'Android target'),
        new Requirement('gradle', 'Gradle')
    ];

    var checkFns = [
        this.check_java,
        this.check_android,
        this.check_android_target,
        this.check_gradle
    ];

    // Then execute requirement checks one-by-one
    return checkFns.reduce(function (promise, checkFn, idx) {
        // Update each requirement with results
        var requirement = requirements[idx];
        return promise.then(checkFn)
        .then(function (version) {
            requirement.installed = true;
            requirement.metadata.version = version;
        }, function (err) {
            requirement.metadata.reason = err;
        });
    }, Q())
    .then(function () {
        // When chain is completed, return requirements array to upstream API
        return requirements;
    });
};
<commit_msg>CB-8898 Fixes gradle check failure due to missing quotes<commit_after>#!/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 shelljs = require('shelljs'),
    child_process = require('child_process'),
    Q     = require('q'),
    path  = require('path'),
    fs    = require('fs'),
    which = require('which'),
    ROOT  = path.join(__dirname, '..', '..');

var isWindows = process.platform == 'win32';

function forgivingWhichSync(cmd) {
    try {
        // TODO: Should use shelljs.which() here to have one less dependency.
        return fs.realpathSync(which.sync(cmd));
    } catch (e) {
        return '';
    }
}

function tryCommand(cmd, errMsg, catchStderr) {
    var d = Q.defer();
    child_process.exec(cmd, function(err, stdout, stderr) {
        if (err) d.reject(new Error(errMsg));
        // Sometimes it is necessary to return an stderr instead of stdout in case of success, since
        // some commands prints theirs output to stderr instead of stdout. 'javac' is the example
        else d.resolve((catchStderr ? stderr : stdout).trim());
    });
    return d.promise;
}

// Get valid target from framework/project.properties
module.exports.get_target = function() {
    function extractFromFile(filePath) {
        var target = shelljs.grep(/\btarget=/, filePath);
        if (!target) {
            throw new Error('Could not find android target within: ' + filePath);
        }
        return target.split('=')[1].trim();
    }
    if (fs.existsSync(path.join(ROOT, 'framework', 'project.properties'))) {
        return extractFromFile(path.join(ROOT, 'framework', 'project.properties'));
    }
    if (fs.existsSync(path.join(ROOT, 'project.properties'))) {
        // if no target found, we're probably in a project and project.properties is in ROOT.
        return extractFromFile(path.join(ROOT, 'project.properties'));
    }
    throw new Error('Could not find android target. File missing: ' + path.join(ROOT, 'project.properties'));
};

// Returns a promise. Called only by build and clean commands.
module.exports.check_ant = function() {
    return tryCommand('ant -version', 'Failed to run "ant -version", make sure you have ant installed and added to your PATH.')
    .then(function (output) {
        // Parse Ant version from command output
        return /version ((?:\d+\.)+(?:\d+))/i.exec(output)[1];
    });
};

// Returns a promise. Called only by build and clean commands.
module.exports.check_gradle = function() {
    var sdkDir = process.env['ANDROID_HOME'];
    var message = 'Could not find gradle wrapper within Android SDK. ';
    if (!sdkDir) return Q.reject(message + 'Might need to install Android SDK or set up \'ADROID_HOME\' env variable.');
    var wrapper = path.join(sdkDir, 'tools', 'templates', 'gradle', 'wrapper', 'gradlew');
    return tryCommand('"' + wrapper + '" -v', message + 'Might need to update your Android SDK.\n' +
            'Looked here: ' + path.basename(wrapper))
    .then(function (output) {
        // Parse Gradle version from command output
        return/^gradle ((?:\d+\.)+(?:\d+))/gim.exec(output)[1];
    });
};

// Returns a promise.
module.exports.check_java = function() {
    var javacPath = forgivingWhichSync('javac');
    var hasJavaHome = !!process.env['JAVA_HOME'];
    return Q().then(function() {
        if (hasJavaHome) {
            // Windows java installer doesn't add javac to PATH, nor set JAVA_HOME (ugh).
            if (!javacPath) {
                process.env['PATH'] += path.delimiter + path.join(process.env['JAVA_HOME'], 'bin');
            }
        } else {
            if (javacPath) {
                var msg = 'Failed to find \'JAVA_HOME\' environment variable. Try setting setting it manually.';
                // OS X has a command for finding JAVA_HOME.
                if (fs.existsSync('/usr/libexec/java_home')) {
                    return tryCommand('/usr/libexec/java_home', msg)
                    .then(function(stdout) {
                        process.env['JAVA_HOME'] = stdout.trim();
                    });
                } else {
                    // See if we can derive it from javac's location.
                    // fs.realpathSync is require on Ubuntu, which symplinks from /usr/bin -> JDK
                    var maybeJavaHome = path.dirname(path.dirname(javacPath));
                    if (fs.existsSync(path.join(maybeJavaHome, 'lib', 'tools.jar'))) {
                        process.env['JAVA_HOME'] = maybeJavaHome;
                    } else {
                        throw new Error(msg);
                    }
                }
            } else if (isWindows) {
                // Try to auto-detect java in the default install paths.
                var oldSilent = shelljs.config.silent;
                shelljs.config.silent = true;
                var firstJdkDir =
                    shelljs.ls(process.env['ProgramFiles'] + '\\java\\jdk*')[0] ||
                    shelljs.ls('C:\\Program Files\\java\\jdk*')[0] ||
                    shelljs.ls('C:\\Program Files (x86)\\java\\jdk*')[0];
                shelljs.config.silent = oldSilent;
                if (firstJdkDir) {
                    // shelljs always uses / in paths.
                    firstJdkDir = firstJdkDir.replace(/\//g, path.sep);
                    if (!javacPath) {
                        process.env['PATH'] += path.delimiter + path.join(firstJdkDir, 'bin');
                    }
                    process.env['JAVA_HOME'] = firstJdkDir;
                }
            }
        }
    }).then(function() {
        var msg =
            'Failed to run "java -version", make sure that you have a JDK installed.\n' +
            'You can get it from: http://www.oracle.com/technetwork/java/javase/downloads.\n';
        if (process.env['JAVA_HOME']) {
            msg += 'Your JAVA_HOME is invalid: ' + process.env['JAVA_HOME'] + '\n';
        }
        return tryCommand('java -version', msg)
        .then(function() {
            // We use tryCommand with catchStderr = true, because
            // javac writes version info to stderr instead of stdout
            return tryCommand('javac -version', msg, true);
        }).then(function (output) {
            return /^javac ((?:\d+\.)+(?:\d+))/i.exec(output)[1];
        });
    });
};

// Returns a promise.
module.exports.check_android = function() {
    return Q().then(function() {
        var androidCmdPath = forgivingWhichSync('android');
        var adbInPath = !!forgivingWhichSync('adb');
        var hasAndroidHome = !!process.env['ANDROID_HOME'] && fs.existsSync(process.env['ANDROID_HOME']);
        function maybeSetAndroidHome(value) {
            if (!hasAndroidHome && fs.existsSync(value)) {
                hasAndroidHome = true;
                process.env['ANDROID_HOME'] = value;
            }
        }
        if (!hasAndroidHome && !androidCmdPath) {
            if (isWindows) {
                // Android Studio 1.0 installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'sdk'));
                // Android Studio pre-1.0 installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-studio', 'sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-studio', 'sdk'));
                // Stand-alone installer
                maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-sdk'));
                maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-sdk'));
            } else if (process.platform == 'darwin') {
                // Android Studio 1.0 installer
                maybeSetAndroidHome(path.join(process.env['HOME'], 'Library', 'Android', 'sdk'));
                // Android Studio pre-1.0 installer
                maybeSetAndroidHome('/Applications/Android Studio.app/sdk');
                // Stand-alone zip file that user might think to put under /Applications
                maybeSetAndroidHome('/Applications/android-sdk-macosx');
                maybeSetAndroidHome('/Applications/android-sdk');
            }
            if (process.env['HOME']) {
                // Stand-alone zip file that user might think to put under their home directory
                maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk-macosx'));
                maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk'));
            }
        }
        if (hasAndroidHome && !androidCmdPath) {
            process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'tools');
        }
        if (androidCmdPath && !hasAndroidHome) {
            var parentDir = path.dirname(androidCmdPath);
            var grandParentDir = path.dirname(parentDir);
            if (path.basename(parentDir) == 'tools') {
                process.env['ANDROID_HOME'] = path.dirname(parentDir);
                hasAndroidHome = true;
            } else if (fs.existsSync(path.join(grandParentDir, 'tools', 'android'))) {
                process.env['ANDROID_HOME'] = grandParentDir;
                hasAndroidHome = true;
            } else {
                throw new Error('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' +
                    'Detected \'android\' command at ' + parentDir + ' but no \'tools\' directory found near.\n' +
                    'Try reinstall Android SDK or update your PATH to include path to valid SDK directory.');
            }
        }
        if (hasAndroidHome && !adbInPath) {
            process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'platform-tools');
        }
        if (!process.env['ANDROID_HOME']) {
            throw new Error('Failed to find \'ANDROID_HOME\' environment variable. Try setting setting it manually.\n' +
                'Failed to find \'android\' command in your \'PATH\'. Try update your \'PATH\' to include path to valid SDK directory.');
        }
        if (!fs.existsSync(process.env['ANDROID_HOME'])) {
            throw new Error('\'ANDROID_HOME\' environment variable is set to non-existent path: ' + process.env['ANDROID_HOME'] +
                '\nTry update it manually to point to valid SDK directory.');
        }
    });
};

module.exports.getAbsoluteAndroidCmd = function() {
    return forgivingWhichSync('android').replace(/(\s)/g, '\\$1');
};

module.exports.check_android_target = function(valid_target) {
    // valid_target can look like:
    //   android-19
    //   android-L
    //   Google Inc.:Google APIs:20
    //   Google Inc.:Glass Development Kit Preview:20
    if (!valid_target) valid_target = module.exports.get_target();
    var msg = 'Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.';
    return tryCommand('android list targets --compact', msg)
    .then(function(output) {
        var targets = output.split('\n');
        if (targets.indexOf(valid_target) >= 0) {
            return targets;
        }

        var androidCmd = module.exports.getAbsoluteAndroidCmd();
        throw new Error('Please install Android target: "' + valid_target + '".\n\n' +
            'Hint: Open the SDK manager by running: ' + androidCmd + '\n' +
            'You will require:\n' +
            '1. "SDK Platform" for ' + valid_target + '\n' +
            '2. "Android SDK Platform-tools (latest)\n' +
            '3. "Android SDK Build-tools" (latest)');
    });
};

// Returns a promise.
module.exports.run = function() {
    return Q.all([this.check_java(), this.check_android(), this.check_android_target()])
    .then(function() {
        console.log('ANDROID_HOME=' + process.env['ANDROID_HOME']);
        console.log('JAVA_HOME=' + process.env['JAVA_HOME']);
    });
};

/**
 * Object thar represents one of requirements for current platform.
 * @param {String} id         The unique identifier for this requirements.
 * @param {String} name       The name of requirements. Human-readable field.
 * @param {String} version    The version of requirement installed. In some cases could be an array of strings
 *                            (for example, check_android_target returns an array of android targets installed)
 * @param {Boolean} installed Indicates whether the requirement is installed or not
 */
var Requirement = function (id, name, version, installed) {
    this.id = id;
    this.name = name;
    this.installed = installed || false;
    this.metadata = {
        version: version,
    };
};

/**
 * Methods that runs all checks one by one and returns a result of checks
 * as an array of Requirement objects. This method intended to be used by cordova-lib check_reqs method
 *
 * @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.
 */
module.exports.check_all = function() {

    var requirements = [
        new Requirement('java', 'Java JDK'),
        new Requirement('androidSdk', 'Android SDK'),
        new Requirement('androidTarget', 'Android target'),
        new Requirement('gradle', 'Gradle')
    ];

    var checkFns = [
        this.check_java,
        this.check_android,
        this.check_android_target,
        this.check_gradle
    ];

    // Then execute requirement checks one-by-one
    return checkFns.reduce(function (promise, checkFn, idx) {
        // Update each requirement with results
        var requirement = requirements[idx];
        return promise.then(checkFn)
        .then(function (version) {
            requirement.installed = true;
            requirement.metadata.version = version;
        }, function (err) {
            requirement.metadata.reason = err;
        });
    }, Q())
    .then(function () {
        // When chain is completed, return requirements array to upstream API
        return requirements;
    });
};
<|endoftext|>


<commit_before>/*
 * Part of: "grunt-html-head-urls-min-toggle"
 * https://github.com/pinestec/grunt-html-head-urls-min-toggle
 *
 * Copyright (c) 2017 Michael Hartung
 * Licensed under the MIT license.
 */

'use strict';

function check_filename(filename_to_be_verified) {
	if (filename_to_be_verified !== undefined) {
		var valid_filename__pattern = /^(?:[a-zA-Z]{1}\:\\|\/[a-zA-Z]{1}\/)?(?:(?:\.{0,2}(?:\/|\\))|(?:[\w\x20\(\)\.-]+(?:\/|\\)))*[\w-]+\.json$/i;
		if (filename_to_be_verified.search(valid_filename__pattern) !== -1) {
			console.log(filename_to_be_verified);
			return true;
		} else {
			console.log("IRREGULAR FILENAME \"" + filename_to_be_verified + "\" FOUND... PLEASE READJUST...!");
			return false;
		}
	} else {
		console.log("PLEASE STATE A FILENAME...!");
		return false;
	}
}

// var test_string_one = "asS";
var test_string_two = "etc/global_options.json";
check_filename(test_string_two);
// check_filename(test_string_two);
return false

// Current reference object template that will be written to disk...:
var object_to_be_written = {
  action : [ 'switch', 'clean' ],
  chattiness : [ 'true', 'false' ],
  direction : [ 'min', 'regular' ],
  file_source : [ 'wildcard', 'list' ],
};

var global_file_name = '';

function global_help_output() {
	var plain_file_name_extractor_RegExp = new RegExp("([^/\\\\]*)$");
	var result_array = plain_file_name_extractor_RegExp.exec(process.argv[1]);
	if (result_array !== null) {
		console.log("usage:\t" + result_array[1] + " -f|--file entire_filename.json [-h|--help] \n");
		console.log("Writing internally defined \"reference object\" to disk with the help of \"JSON.stringify\".");
		console
		    .log("Just to be loaded and become an object again with the help \"JSON.parse\" for later use together with any package.");
		console.log("Find the current reference object template at the top of this script: \"" + result_array[1] + "\"\n");
		console.log("optional arguments:");
		console.log("-h, --help\t\t\tShow this help message and exit.");
		console.log("-f, --file proper_filename.json\tState a proper filename to store the \"JSON.stringified\" object in.");
	}
}

var help_needed__pattern = /^--?h(elp)?$/i;
var file_name__pattern = /^--?f(ile)?$/i;
function scan_arguments_for_help(value, index, array) {
	if (index > 1) {
		if (value.search(help_needed__pattern) !== -1) {
			throw 'help';
		}
	}
}

function scan_arguments(value, index, array) {
	if (index > 1) {
		if (value.search(file_name__pattern) !== -1) {
			if (check_filename(array[index + 1])) {
				global_file_name = array[index + 1];
				throw 'file';
			} else {
				return false;
			}
		}
	}
}

try {
	process.argv.forEach(scan_arguments_for_help);
} catch (exception) {
	global_help_output();
	return false;
}

var global_functions = {};
global_functions = require('../tasks/html_head_urls_min_toggle__global_functions.js');
var fileSystem_Module = global_functions.globalModule_Try('fs');

try {
	process.argv.forEach(scan_arguments);
} catch (exception) {
	switch (exception) {
	case 'help':
		global_help_output();
		return false;
	case 'file':
		if (fileSystem_Module.existsSync(global_file_name)) {
			console.log("Overwriting file: \"" + global_file_name + "\"...");
		} else {
			console.log("Creating new file: \"" + global_file_name + "\"...");
		}
		var currentFileHandle = fileSystem_Module.openSync(global_file_name, 'w');
		fileSystem_Module.writeFileSync(currentFileHandle, JSON.stringify(object_to_be_written));
		fileSystem_Module.closeSync(currentFileHandle);
		return true;
	default:
		console.log("DEFAULT EXCEPTION: \"" + exception + "\"");
		return false;
	}
}
global_help_output();<commit_msg>Fast now with really weird paths... - MH - PT<commit_after>/*
 * Part of: "grunt-html-head-urls-min-toggle"
 * https://github.com/pinestec/grunt-html-head-urls-min-toggle
 *
 * Copyright (c) 2017 Michael Hartung
 * Licensed under the MIT license.
 */

'use strict';

function check_filename(filename_to_be_verified) {
	if (filename_to_be_verified !== undefined) {
		var valid_filename__pattern = /^(?:[a-zA-Z]{1}\:\\|\/[a-zA-Z]{1}\/)?(?:(?:\.{0,2}(?:\/|\\))|(?:[\w\x20\(\)\.-]+(?:\/|\\)))*[\w-]+\.json$/i;
		if (filename_to_be_verified.search(valid_filename__pattern) !== -1) {
			console.log(filename_to_be_verified);
			return true;
		} else {
			console.log("IRREGULAR FILENAME \"" + filename_to_be_verified + "\" FOUND... PLEASE READJUST...!");
			return false;
		}
	} else {
		console.log("PLEASE STATE A FILENAME...!");
		return false;
	}
}

// var test_string_one = "asS";
var test_string_two = "../.././../Default\\ User/Pictures/global_options.jsXon";
check_filename(test_string_two);
// check_filename(test_string_two);
return false

// Current reference object template that will be written to disk...:
var object_to_be_written = {
  action : [ 'switch', 'clean' ],
  chattiness : [ 'true', 'false' ],
  direction : [ 'min', 'regular' ],
  file_source : [ 'wildcard', 'list' ],
};

var global_file_name = '';

function global_help_output() {
	var plain_file_name_extractor_RegExp = new RegExp("([^/\\\\]*)$");
	var result_array = plain_file_name_extractor_RegExp.exec(process.argv[1]);
	if (result_array !== null) {
		console.log("usage:\t" + result_array[1] + " -f|--file entire_filename.json [-h|--help] \n");
		console.log("Writing internally defined \"reference object\" to disk with the help of \"JSON.stringify\".");
		console
		    .log("Just to be loaded and become an object again with the help \"JSON.parse\" for later use together with any package.");
		console.log("Find the current reference object template at the top of this script: \"" + result_array[1] + "\"\n");
		console.log("optional arguments:");
		console.log("-h, --help\t\t\tShow this help message and exit.");
		console.log("-f, --file proper_filename.json\tState a proper filename to store the \"JSON.stringified\" object in.");
	}
}

var help_needed__pattern = /^--?h(elp)?$/i;
var file_name__pattern = /^--?f(ile)?$/i;
function scan_arguments_for_help(value, index, array) {
	if (index > 1) {
		if (value.search(help_needed__pattern) !== -1) {
			throw 'help';
		}
	}
}

function scan_arguments(value, index, array) {
	if (index > 1) {
		if (value.search(file_name__pattern) !== -1) {
			if (check_filename(array[index + 1])) {
				global_file_name = array[index + 1];
				throw 'file';
			} else {
				return false;
			}
		}
	}
}

try {
	process.argv.forEach(scan_arguments_for_help);
} catch (exception) {
	global_help_output();
	return false;
}

var global_functions = {};
global_functions = require('../tasks/html_head_urls_min_toggle__global_functions.js');
var fileSystem_Module = global_functions.globalModule_Try('fs');

try {
	process.argv.forEach(scan_arguments);
} catch (exception) {
	switch (exception) {
	case 'help':
		global_help_output();
		return false;
	case 'file':
		if (fileSystem_Module.existsSync(global_file_name)) {
			console.log("Overwriting file: \"" + global_file_name + "\"...");
		} else {
			console.log("Creating new file: \"" + global_file_name + "\"...");
		}
		var currentFileHandle = fileSystem_Module.openSync(global_file_name, 'w');
		fileSystem_Module.writeFileSync(currentFileHandle, JSON.stringify(object_to_be_written));
		fileSystem_Module.closeSync(currentFileHandle);
		return true;
	default:
		console.log("DEFAULT EXCEPTION: \"" + exception + "\"");
		return false;
	}
}
global_help_output();<|endoftext|>


<commit_before>var _ = require('lodash');
var path = require('canonical-path');

var titleCase = function(text) {
  return text.replace(/(.)(.*)/, function(_, first, rest) {
    return first.toUpperCase() + rest;
  });
};

/*
* Create _data.json file for Harp pages
*
* http://harpjs.com/docs/development/metadata
*
* This method creates the meta data required for each page
* such as the title, description, etc. This meta data is used
* in the harp static site generator to create the title for headers
* and the navigation used in the API docs
*
*/

module.exports = function addJadeDataDocsProcessor() {
  return {
    $runAfter: ['adding-extra-docs'],
    $runBefore: ['extra-docs-added'],
    $process: function(docs) {
      var extraDocs = [];
      var modules = [];
      var data = {};

      var appDataDoc = {
        id: 'api-list-data',
        aliases: ['api-list-data'],
        docType: 'api-list-data',
        data: data
      };
      extraDocs.push(appDataDoc);

      // create additional doc for auditing
      var appDataAuditDoc = {
        id: 'api-list-audit',
        aliases: ['api-list-audit'],
        docType: 'api-list-audit',
        data: data
      };
      extraDocs.push(appDataAuditDoc);

      /*
      * Create Data for Modules
      *
      * Modules must be public and have content
      */

      _.forEach(docs, function(doc) {
        if (doc.docType === 'module' && !doc.internal && doc.exports.length) {
          modules.push(doc);

          // GET DATA FOR INDEX PAGE OF MODULE SECTION
          var indexPageInfo = [{
            name: 'index',
            title: _.map(path.basename(doc.fileInfo.baseName).split('_'), function(part) {
              return titleCase(part);
            }).join(' '),
            intro: doc.description.replace('"', '\"').replace(/\s*(\r?\n|\r)\s*/g," "),
            docType: 'module'
          }];

          // GET DATA FOR EACH PAGE (CLASS, VARS, FUNCTIONS)
          var modulePageInfo  = _(doc.exports)
          .map(function(exportDoc) {

            // STABILITY STATUS
            // Supported tags:
            // @stable
            // @experimental
            // @deprecated
            // Default is the empty string (no badge)
            // Do not capitalize the strings, they are intended for use in constructing a css class from _hero.scss
            // and used in _hero.jade
            var stability = '';
            if (_.has(exportDoc, 'stable')) {
              stability = 'stable';
            } else if (_.has(exportDoc, 'experimental')) {
              stability = 'experimental';
            } else if (_.has(exportDoc, 'deprecated')) {
              stability = 'deprecated';
              exportDoc.showDeprecatedNotes = true;
            }

            var howToUse = '';
            if(_.has(exportDoc, 'howToUse')) {
              var howToUseArray = exportDoc.tags.tags.filter(function(tag) {
                return tag.tagName === 'howToUse'
              });

              // Remove line breaks, there should only be one tag
              howToUse = howToUseArray[0].description.replace(/(\r\n|\n|\r)/gm,"");
            }

            var whatItDoes = '';
            if(_.has(exportDoc, 'whatItDoes')) {
              var whatItDoesArray = exportDoc.tags.tags.filter(function(tag) {
                return tag.tagName === 'whatItDoes'
              });

              // Remove line breaks, there should only be one tag
              whatItDoes = whatItDoesArray[0].description.replace(/(\r\n|\n|\r)/gm,"");
            }

            // SECURITY STATUS
            // Supported tags:
            // @security
            // Default is no security risk assessed for api
            var security = false;
            if (_.has(exportDoc, 'security')) {
              var securityArray = exportDoc.tags.tags.filter(function(tag) {
                return tag.tagName === 'security'
              });

              // Remove line breaks, there should only be one tag
              security = securityArray[0].description.replace(/(\r\n|\n|\r)/gm,"");

              exportDoc.showSecurityNotes = true;
            }

            // Data inserted into jade-data.template.html
            var dataDoc = {
              name: exportDoc.name + '-' + exportDoc.docType,
              title: exportDoc.name,
              docType: exportDoc.docType,
              exportDoc: exportDoc,
              stability: stability,
              howToUse: howToUse,
              whatItDoes: whatItDoes,
              security: security
            };

            if (exportDoc.symbolTypeName) dataDoc.varType = titleCase(exportDoc.symbolTypeName);
            if (exportDoc.originalModule) dataDoc.originalModule = exportDoc.originalModule;
            return dataDoc;
          })
          .sortBy('name')
          .value();

          doc.childPages = modulePageInfo;

          // ADD TO APP DATA DOC
          data[doc.id] = modulePageInfo;

          // COMBINE WITH INDEX PAGE DATA
          var allPageData = indexPageInfo.concat(modulePageInfo);

          // PUSH JADE DATA DOC TO EXTRA DOCS ARRAY
          extraDocs.push({
            id: doc.id + "-data",
            aliases: [doc.id + "-data"],
            docType: 'jade-data',
            originalDoc: doc,
            data: allPageData
          });
        }
      });

      return docs.concat(extraDocs);
    }
  };
};
<commit_msg>fix(api-builder/addJadeDataDocs): handle newlines better (#2296)<commit_after>var _ = require('lodash');
var path = require('canonical-path');

var titleCase = function(text) {
  return text.replace(/(.)(.*)/, function(_, first, rest) {
    return first.toUpperCase() + rest;
  });
};

/*
* Create _data.json file for Harp pages
*
* http://harpjs.com/docs/development/metadata
*
* This method creates the meta data required for each page
* such as the title, description, etc. This meta data is used
* in the harp static site generator to create the title for headers
* and the navigation used in the API docs
*
*/

module.exports = function addJadeDataDocsProcessor() {
  return {
    $runAfter: ['adding-extra-docs'],
    $runBefore: ['extra-docs-added'],
    $process: function(docs) {
      var extraDocs = [];
      var modules = [];
      var data = {};

      var appDataDoc = {
        id: 'api-list-data',
        aliases: ['api-list-data'],
        docType: 'api-list-data',
        data: data
      };
      extraDocs.push(appDataDoc);

      // create additional doc for auditing
      var appDataAuditDoc = {
        id: 'api-list-audit',
        aliases: ['api-list-audit'],
        docType: 'api-list-audit',
        data: data
      };
      extraDocs.push(appDataAuditDoc);

      /*
      * Create Data for Modules
      *
      * Modules must be public and have content
      */

      _.forEach(docs, function(doc) {
        if (doc.docType === 'module' && !doc.internal && doc.exports.length) {
          modules.push(doc);

          // GET DATA FOR INDEX PAGE OF MODULE SECTION
          var indexPageInfo = [{
            name: 'index',
            title: _.map(path.basename(doc.fileInfo.baseName).split('_'), function(part) {
              return titleCase(part);
            }).join(' '),
            intro: doc.description.replace('"', '\"').replace(/\s*(\r?\n|\r)\s*/g," "),
            docType: 'module'
          }];

          // GET DATA FOR EACH PAGE (CLASS, VARS, FUNCTIONS)
          var modulePageInfo  = _(doc.exports)
          .map(function(exportDoc) {

            // STABILITY STATUS
            // Supported tags:
            // @stable
            // @experimental
            // @deprecated
            // Default is the empty string (no badge)
            // Do not capitalize the strings, they are intended for use in constructing a css class from _hero.scss
            // and used in _hero.jade
            var stability = '';
            if (_.has(exportDoc, 'stable')) {
              stability = 'stable';
            } else if (_.has(exportDoc, 'experimental')) {
              stability = 'experimental';
            } else if (_.has(exportDoc, 'deprecated')) {
              stability = 'deprecated';
              exportDoc.showDeprecatedNotes = true;
            }

            var howToUse = '';
            if(_.has(exportDoc, 'howToUse')) {
              var howToUseArray = exportDoc.tags.tags.filter(function(tag) {
                return tag.tagName === 'howToUse'
              });

              // Remove line breaks, there should only be one tag
              howToUse = howToUseArray[0].description.replace(/(\r\n|\n|\r)/gm," ");
            }

            var whatItDoes = '';
            if(_.has(exportDoc, 'whatItDoes')) {
              var whatItDoesArray = exportDoc.tags.tags.filter(function(tag) {
                return tag.tagName === 'whatItDoes'
              });

              // Remove line breaks, there should only be one tag
              whatItDoes = whatItDoesArray[0].description.replace(/(\r\n|\n|\r)/gm," ");
            }

            // SECURITY STATUS
            // Supported tags:
            // @security
            // Default is no security risk assessed for api
            var security = false;
            if (_.has(exportDoc, 'security')) {
              var securityArray = exportDoc.tags.tags.filter(function(tag) {
                return tag.tagName === 'security'
              });

              // Remove line breaks, there should only be one tag
              security = securityArray[0].description.replace(/(\r\n|\n|\r)/gm," ");

              exportDoc.showSecurityNotes = true;
            }

            // Data inserted into jade-data.template.html
            var dataDoc = {
              name: exportDoc.name + '-' + exportDoc.docType,
              title: exportDoc.name,
              docType: exportDoc.docType,
              exportDoc: exportDoc,
              stability: stability,
              howToUse: howToUse,
              whatItDoes: whatItDoes,
              security: security
            };

            if (exportDoc.symbolTypeName) dataDoc.varType = titleCase(exportDoc.symbolTypeName);
            if (exportDoc.originalModule) dataDoc.originalModule = exportDoc.originalModule;
            return dataDoc;
          })
          .sortBy('name')
          .value();

          doc.childPages = modulePageInfo;

          // ADD TO APP DATA DOC
          data[doc.id] = modulePageInfo;

          // COMBINE WITH INDEX PAGE DATA
          var allPageData = indexPageInfo.concat(modulePageInfo);

          // PUSH JADE DATA DOC TO EXTRA DOCS ARRAY
          extraDocs.push({
            id: doc.id + "-data",
            aliases: [doc.id + "-data"],
            docType: 'jade-data',
            originalDoc: doc,
            data: allPageData
          });
        }
      });

      return docs.concat(extraDocs);
    }
  };
};
<|endoftext|>


<commit_before>class JSRange {
  constructor (el, options) {
    this._updateObject = this._update
    this._eventsObject = this._events

    this.options = options
    this.selected = {
      from: this.options.min,
      to: this.options.max
    }

    this._createBody(el)
    this._bindEvents()
    this.update()
  }

  // Propably we want to update everything
  update () {
    this._update.all()
  }

  set (hash = {}) {
    if (hash.from) {
      this.selected.from = hash.from
    }

    if (hash.to) {
      this.selected.to = hash.to
    }

    this.update()
  }

  _createBody (el) {
    this.body = {}

    this.body.parent = document.querySelector(el)
    this.body.parent.classList.add('jsr')

    this.body.rail = document.createElement('div')
    this.body.rail.classList.add('jsr_rail')

    this.body.sliders = {}
    this.body.sliders.from = document.createElement('div')
    this.body.sliders.from.classList.add('jsr_slider', 'jsr_slider--from')
    this.body.sliders.from.dataset.jsrType = 'from'
    this.body.sliders.to = document.createElement('div')
    this.body.sliders.to.classList.add('jsr_slider', 'jsr_slider--to')
    this.body.sliders.to.dataset.jsrType = 'to'

    this.body.info = {}
    this.body.info.min = document.createElement('span')
    this.body.info.min.classList.add('jsr_info', 'jsr_info--min')
    this.body.info.max = document.createElement('span')
    this.body.info.max.classList.add('jsr_info', 'jsr_info--max')
    this.body.info.from = document.createElement('span')
    this.body.info.from.classList.add('jsr_info', 'jsr_info--from')
    this.body.info.to = document.createElement('span')
    this.body.info.to.classList.add('jsr_info', 'jsr_info--to')
    this.body.info.single = document.createElement('span')
    this.body.info.single.classList.add('jsr_info', 'jsr_info--single')

    let elements = [
      this.body.rail,
      this.body.sliders.from,
      this.body.sliders.to,
      this.body.info.min,
      this.body.info.max,
      this.body.info.from,
      this.body.info.to,
      this.body.info.single
    ]

    elements.forEach((element) => {
      this.body.parent.appendChild(element)
    })
  }

  _validateAndSave (type, value) {
    if (type === 'from') {
      if (value < this.options.min) {
        value = this.options.min
      }

      if (value > this.selected.to) {
        value = this.selected.to
      }
    }

    if (type === 'to') {
      if (value > this.options.max) {
        value = this.options.max
      }

      if (value < this.selected.from) {
        value = this.selected.from
      }
    }

    this.selected[type] = value
  }

  _bindEvents () {
    this.body.sliders.from.addEventListener('mousedown', this._events.sliderMouseDown)
    this.body.sliders.to.addEventListener('mousedown', this._events.sliderMouseDown)
    document.addEventListener('mousemove', this._events.sliderMouseMove)
    document.addEventListener('mouseup', this._events.sliderMouseUp)

    this.body.rail.addEventListener('click', this._events.railClick)
  }

  _getValueOfPosition (mouseX) {
    let railLeft = this.body.rail.getBoundingClientRect().left
    let diff = mouseX - railLeft
    return parseInt(diff / this.body.rail.offsetWidth * this.options.max)
  }

  // _update returns all events available to use
  // it tries to use the buffering-variable (_eventsObject) to not recreate this big object every time
  get _events () {
    var _this = this;
    return _this._eventsObject || {
      sliderMouseDown: function (event) {
        event.preventDefault() // prevents selecting text
        window.jsrMoveObject = event.target
      },
      sliderMouseUp: function (event) {
        window.jsrMoveObject = null
      },
      sliderMouseMove: function (event) {
        if (window.jsrMoveObject) {
          let type = window.jsrMoveObject.dataset.jsrType
          let newSelected = _this._getValueOfPosition(event.clientX)
          _this._validateAndSave(type, newSelected)
          _this.update()
        }
      },
      railClick: function (event) {
        // determine closer to which slider it was closer
        let clickedValue = _this._getValueOfPosition(event.clientX)

        // compare absolute distance between clickedValue and selected.from/max
        // closer to zero, means closer to min/max
        if (Math.abs(_this.selected.from - clickedValue) < Math.abs(_this.selected.to - clickedValue)) {
          // closer to min
          _this.selected.from = clickedValue
        } else {
          // closer to max
          _this.selected.to = clickedValue
        }

        _this.update()
      }
    }
  }

  // _update returns all methods available to use to update things
  // it tries to use the buffering-variable (_updateObject) to not recreate this big object every time
  get _update () {
    var _this = this;
    return _this._updateObject || {
      // Here goes every function which should be updated via .all()
      // 'info' should be after 'sliders' because it depends on their value
      _toUpdate: ['rail', 'sliders', 'info'],
      all: function () {
        this._toUpdate.forEach((item) => {
          this[item]() // Call certain update function
        })
      },

      rail: function (min = _this.selected.from, max = _this.selected.to) {
        // Calc rail color position
        let start     = min / _this.options.max
        let end       = max / _this.options.max
        // Calc real start (because of weird percentage work)
        let realStart = start / (1 - (end - start))

        // Sets colored part of rail
        // Expects percentages without % sign
        _this.body.rail.style.backgroundPosition  = `${realStart * 100}% 0`
        _this.body.rail.style.backgroundSize      = `${(end - start) * 100}% 100%`
      },

      sliders: function (min = _this.selected.from, max = _this.selected.to) {
        let startWidthRatio = _this.body.sliders.from.offsetWidth / _this.body.rail.offsetWidth
        let endWidthRatio   = _this.body.sliders.to.offsetWidth / _this.body.rail.offsetWidth
        // widthRatio is used to place middle point of slider in the right point
        let start           = min / _this.options.max - startWidthRatio / 2
        let end             = max / _this.options.max - endWidthRatio / 2

        _this.body.sliders.from.style.left  = `${start * 100}%`
        _this.body.sliders.to.style.left    = `${end * 100}%`
      },

      info: function () {
        _this.body.info.min.innerHTML     = _this.options.min
        _this.body.info.max.innerHTML     = _this.options.max
        _this.body.info.from.innerHTML    = _this.selected.from
        _this.body.info.to.innerHTML      = _this.selected.to
        _this.body.info.single.innerHTML  = (_this.selected.from === _this.selected.to )
                                            ? _this.selected.from
                                            : `${_this.selected.from} - ${_this.selected.to}`

        // position infos
        // ! variables are CSS expressions (due to mix of % and px values)
        let fromSliderCenter  = `(${_this.body.sliders.from.style.left} + ${_this.body.sliders.from.offsetWidth}px / 2)`
        let toSliderCenter    = `(${_this.body.sliders.to.style.left} + ${_this.body.sliders.to.offsetWidth}px / 2)`

        _this.body.info.from.style.left = `calc(${fromSliderCenter} - ${_this.body.info.from.offsetWidth}px / 2)`
        _this.body.info.to.style.left = `calc(${toSliderCenter} - ${_this.body.info.to.offsetWidth}px / 2)`
        _this.body.info.single.style.left = `calc((${fromSliderCenter} + ${toSliderCenter}) / 2 - ${_this.body.info.single.offsetWidth}px / 2)`
      }
    }
  }
}<commit_msg>Add throttling for mousemove event<commit_after>class JSRange {
  constructor (el, options) {
    this._updateObject = this._update
    this._eventsObject = this._events
    this._mousemoveThrottle = false

    this.options = options
    this.selected = {
      from: this.options.min,
      to: this.options.max
    }

    this._createBody(el)
    this._bindEvents()
    this.update()
  }

  // Propably we want to update everything
  update () {
    this._update.all()
  }

  set (hash = {}) {
    if (hash.from) {
      this.selected.from = hash.from
    }

    if (hash.to) {
      this.selected.to = hash.to
    }

    this.update()
  }

  _createBody (el) {
    this.body = {}

    this.body.parent = document.querySelector(el)
    this.body.parent.classList.add('jsr')

    this.body.rail = document.createElement('div')
    this.body.rail.classList.add('jsr_rail')

    this.body.sliders = {}
    this.body.sliders.from = document.createElement('div')
    this.body.sliders.from.classList.add('jsr_slider', 'jsr_slider--from')
    this.body.sliders.from.dataset.jsrType = 'from'
    this.body.sliders.to = document.createElement('div')
    this.body.sliders.to.classList.add('jsr_slider', 'jsr_slider--to')
    this.body.sliders.to.dataset.jsrType = 'to'

    this.body.info = {}
    this.body.info.min = document.createElement('span')
    this.body.info.min.classList.add('jsr_info', 'jsr_info--min')
    this.body.info.max = document.createElement('span')
    this.body.info.max.classList.add('jsr_info', 'jsr_info--max')
    this.body.info.from = document.createElement('span')
    this.body.info.from.classList.add('jsr_info', 'jsr_info--from')
    this.body.info.to = document.createElement('span')
    this.body.info.to.classList.add('jsr_info', 'jsr_info--to')
    this.body.info.single = document.createElement('span')
    this.body.info.single.classList.add('jsr_info', 'jsr_info--single')

    let elements = [
      this.body.rail,
      this.body.sliders.from,
      this.body.sliders.to,
      this.body.info.min,
      this.body.info.max,
      this.body.info.from,
      this.body.info.to,
      this.body.info.single
    ]

    elements.forEach((element) => {
      this.body.parent.appendChild(element)
    })
  }

  _validateAndSave (type, value) {
    if (type === 'from') {
      if (value < this.options.min) {
        value = this.options.min
      }

      if (value > this.selected.to) {
        value = this.selected.to
      }
    }

    if (type === 'to') {
      if (value > this.options.max) {
        value = this.options.max
      }

      if (value < this.selected.from) {
        value = this.selected.from
      }
    }

    this.selected[type] = value
  }

  _bindEvents () {
    this.body.sliders.from.addEventListener('mousedown', this._events.sliderMouseDown)
    this.body.sliders.to.addEventListener('mousedown', this._events.sliderMouseDown)
    document.addEventListener('mousemove', this._events.sliderMouseMove)
    document.addEventListener('mouseup', this._events.sliderMouseUp)

    this.body.rail.addEventListener('click', this._events.railClick)
  }

  _getValueOfPosition (mouseX) {
    let railLeft = this.body.rail.getBoundingClientRect().left
    let diff = mouseX - railLeft
    return parseInt(diff / this.body.rail.offsetWidth * this.options.max)
  }

  // _update returns all events available to use
  // it tries to use the buffering-variable (_eventsObject) to not recreate this big object every time
  get _events () {
    var _this = this;
    return _this._eventsObject || {
      sliderMouseDown: function (event) {
        event.preventDefault() // prevents selecting text
        window.jsrMoveObject = event.target
      },
      sliderMouseUp: function (event) {
        window.jsrMoveObject = null
      },
      sliderMouseMove: function (event) {
        if (window.jsrMoveObject && !_this._mousemoveThrottle) {
          // throttling function
          _this._mousemoveThrottle = true
          setTimeout(() => { _this._mousemoveThrottle = false}, 20)

          let type = window.jsrMoveObject.dataset.jsrType
          let newSelected = _this._getValueOfPosition(event.clientX)
          _this._validateAndSave(type, newSelected)
          _this.update()
        }
      },
      railClick: function (event) {
        // determine closer to which slider it was closer
        let clickedValue = _this._getValueOfPosition(event.clientX)

        // compare absolute distance between clickedValue and selected.from/max
        // closer to zero, means closer to min/max
        if (Math.abs(_this.selected.from - clickedValue) < Math.abs(_this.selected.to - clickedValue)) {
          // closer to min
          _this.selected.from = clickedValue
        } else {
          // closer to max
          _this.selected.to = clickedValue
        }

        _this.update()
      }
    }
  }

  // _update returns all methods available to use to update things
  // it tries to use the buffering-variable (_updateObject) to not recreate this big object every time
  get _update () {
    var _this = this;
    return _this._updateObject || {
      // Here goes every function which should be updated via .all()
      // 'info' should be after 'sliders' because it depends on their value
      _toUpdate: ['rail', 'sliders', 'info'],
      all: function () {
        this._toUpdate.forEach((item) => {
          this[item]() // Call certain update function
        })
      },

      rail: function (min = _this.selected.from, max = _this.selected.to) {
        // Calc rail color position
        let start     = min / _this.options.max
        let end       = max / _this.options.max
        // Calc real start (because of weird percentage work)
        let realStart = start / (1 - (end - start))

        // Sets colored part of rail
        // Expects percentages without % sign
        _this.body.rail.style.backgroundPosition  = `${realStart * 100}% 0`
        _this.body.rail.style.backgroundSize      = `${(end - start) * 100}% 100%`
      },

      sliders: function (min = _this.selected.from, max = _this.selected.to) {
        let startWidthRatio = _this.body.sliders.from.offsetWidth / _this.body.rail.offsetWidth
        let endWidthRatio   = _this.body.sliders.to.offsetWidth / _this.body.rail.offsetWidth
        // widthRatio is used to place middle point of slider in the right point
        let start           = min / _this.options.max - startWidthRatio / 2
        let end             = max / _this.options.max - endWidthRatio / 2

        _this.body.sliders.from.style.left  = `${start * 100}%`
        _this.body.sliders.to.style.left    = `${end * 100}%`
      },

      info: function () {
        _this.body.info.min.innerHTML     = _this.options.min
        _this.body.info.max.innerHTML     = _this.options.max
        _this.body.info.from.innerHTML    = _this.selected.from
        _this.body.info.to.innerHTML      = _this.selected.to
        _this.body.info.single.innerHTML  = (_this.selected.from === _this.selected.to )
                                            ? _this.selected.from
                                            : `${_this.selected.from} - ${_this.selected.to}`

        // position infos
        // ! variables are CSS expressions (due to mix of % and px values)
        let fromSliderCenter  = `(${_this.body.sliders.from.style.left} + ${_this.body.sliders.from.offsetWidth}px / 2)`
        let toSliderCenter    = `(${_this.body.sliders.to.style.left} + ${_this.body.sliders.to.offsetWidth}px / 2)`

        _this.body.info.from.style.left = `calc(${fromSliderCenter} - ${_this.body.info.from.offsetWidth}px / 2)`
        _this.body.info.to.style.left = `calc(${toSliderCenter} - ${_this.body.info.to.offsetWidth}px / 2)`
        _this.body.info.single.style.left = `calc((${fromSliderCenter} + ${toSliderCenter}) / 2 - ${_this.body.info.single.offsetWidth}px / 2)`
      }
    }
  }
}<|endoftext|>


<commit_before>/**
  This file is part of the "FnordMetric" project
    Copyright (c) 2014 Laura Schlimmer
    Copyright (c) 2014 Paul Asmuth, Google Inc.

  FnordMetric is free software: you can redistribute it and/or modify it under
  the terms of the GNU General Public License v3.0. You should have received a
  copy of the GNU General Public License along with this program. If not, see
  <http://www.gnu.org/licenses/>.
**/
var ModalComponent = function() {
  this.createdCallback = function() {
    var base = this;

    //customisable
    this.closeElems = [
      this.querySelector("fn-modal-close-icon"), this.parentNode
    ];

    this.closeElems.forEach(function(elem) {
      if (elem) {
        elem.onclick = function() {
          base.close();
        }
      }
    });

    this.onclick = function(e) {
      e.stopPropagation();
    };
  };

  this.keyListener;

  this.listener = function(e) {
    //ESC
    if (e.keyCode == 27) {
      this.close();
    }
  };

  this.show = function() {
    console.log("show modal");
    var dimmer = this.parentNode;
    if (dimmer && dimmer.tagName == 'FN-MODAL-DIMMER') {
      dimmer.setAttribute('data-active', 'active');
    } else {
      this.setAttribute('data-active', 'active');
    }

    //place modal
    var height = this.getBoundingClientRect().height;
    var mtop = ((window.innerHeight - height) / 4);
    this.style.marginTop = mtop + "px";

    var _this = this;
    this.keyListener = this.listener.bind(this);
    document.addEventListener('keyup', _this.keyListener, false);
  };

  this.close = function() {
    var dimmer = this.parentNode;
    if (dimmer) {
      dimmer.removeAttribute('data-active');
    } else {
      this.removeAttribute('data-active');
    }

    var _this = this;
    document.removeEventListener('keyup', _this.keyListener, false);
  };
};

var proto = Object.create(HTMLElement.prototype);
ModalComponent.apply(proto);
document.registerElement("fn-modal", { prototype: proto });
<commit_msg>remove debug print<commit_after>/**
  This file is part of the "FnordMetric" project
    Copyright (c) 2014 Laura Schlimmer
    Copyright (c) 2014 Paul Asmuth, Google Inc.

  FnordMetric is free software: you can redistribute it and/or modify it under
  the terms of the GNU General Public License v3.0. You should have received a
  copy of the GNU General Public License along with this program. If not, see
  <http://www.gnu.org/licenses/>.
**/
var ModalComponent = function() {
  this.createdCallback = function() {
    var base = this;

    //customisable
    this.closeElems = [
      this.querySelector("fn-modal-close-icon"), this.parentNode
    ];

    this.closeElems.forEach(function(elem) {
      if (elem) {
        elem.onclick = function() {
          base.close();
        }
      }
    });

    this.onclick = function(e) {
      e.stopPropagation();
    };
  };

  this.keyListener;

  this.listener = function(e) {
    //ESC
    if (e.keyCode == 27) {
      this.close();
    }
  };

  this.show = function() {
    var dimmer = this.parentNode;
    if (dimmer && dimmer.tagName == 'FN-MODAL-DIMMER') {
      dimmer.setAttribute('data-active', 'active');
    } else {
      this.setAttribute('data-active', 'active');
    }

    //place modal
    var height = this.getBoundingClientRect().height;
    var mtop = ((window.innerHeight - height) / 4);
    this.style.marginTop = mtop + "px";

    var _this = this;
    this.keyListener = this.listener.bind(this);
    document.addEventListener('keyup', _this.keyListener, false);
  };

  this.close = function() {
    var dimmer = this.parentNode;
    if (dimmer) {
      dimmer.removeAttribute('data-active');
    } else {
      this.removeAttribute('data-active');
    }

    var _this = this;
    document.removeEventListener('keyup', _this.keyListener, false);
  };
};

var proto = Object.create(HTMLElement.prototype);
ModalComponent.apply(proto);
document.registerElement("fn-modal", { prototype: proto });
<|endoftext|>