<commit_before>/*
 * grunt-ghost
 * https://github.com/colinwren/grunt-ghost
 *
 * Copyright (c) 2013 Colin Wren
 * Licensed under the MIT license.
 */

module.exports = function (grunt) {
  'use strict';
  // Create MultiTask 'ghost'
  grunt.registerMultiTask('ghost', 'Runs CasperJS Tests.', function () {
    // Get options object
    var options = this.data.options,
        // Tells Grunt that this asynchronous and that it is finished when
        // "done()" is called
        done = this.async(),
        // Get spawn function for the CasperJS process creation
        spawn = require('child_process').spawn,
        // Create array that will contain all the parameters for CasperJS
        command = [],
        len;

    // Get CasperJS test options and add them to command array
    if (options.xunit) {
      command.push('--xunit=' + options.xunit);
    }
    if (options.direct) {
      command.push('--direct');
    }
    if (options.includes) {
      command.push('--includes=' + options.includes.join());
    }
    if (options.logLevel) {
      command.push('--log-level=' + options.logLevel);
    }
    if (options.pre) {
      command.push('--pre=' + options.pre.join());
    }
    if (options.post) {
      command.push('--post=' + options.post.join());
    }
    if (options.failFast) {
      command.push('--fail-fast');
    }
    if (options.args) {
      command = command.concat(formatArgs(options.args));
    }

    // Get filepaths from 'src' and sorts alphabetically
    var filepaths = grunt.file.expandFiles(this.file.src).sort();

    // add CasperJS parameter array to filepath array
    command = filepaths.concat(command);

    // Function to wrap grunt log output at 80 characters
    var lastSpace;
    function wrap(str) {
      // Will run until there are no spaces in the string (All arguments have
      // spaces after them)
      if (str.indexOf(' ') === -1) {
        return;
      }
      // Finds last space in the first 80 characters of the string
      lastSpace = str.substr(0, 80).lastIndexOf(' ');
      // Writes string until the last space into grunt log
      grunt.log.write(str.substr(0, lastSpace) + '\n');
      // Calls itself with the rest of the string that was no logged
      wrap(str.substr(lastSpace + 1));
    }

    // Checks if something is an array
    function isArr (arr) {
      return Object.prototype.toString.call(arr) === '[object Array]';
    }

    // Formats named or anonymous arguments
    function formatArgs(params){
      var len,
          rtn = [];

      if (isArr(options.args)) {
        // Array of anonymous arguments
        len = params.length;
        for (var i = 0; i < len; i++) {
          rtn.push(params[i]);
        }
      } else {
        // Object containing named arguments
        for (var p in params) {
          rtn.push('--' + p + '=' + params[p]);
        }
      }

      return rtn;
    }

    // Additional Options
    // Prints command sent to CasperJS
    if (options.printCommand) {
      wrap('\u001b[1m\u001b[4mCommand:\u001b[0m casperjs ' +
          command.join(' ') + ' \n');
    }
    // Prints filepaths sent to CasperJS in alternating colors
    if (options.printFilePaths) {
      var files = '',
          colors = [
            '\u001b[34m', // Blue
            '\u001b[33m', // Yellow
            '\u001b[36m', // Cyan
            '\u001b[35m', // Magenta
            '\u001b[32m'  // Green
          ];

      // Give file paths alternating colors and add them to 'files' string
      for (var i = 0; i < filepaths.length; i++) {
        files += colors[i % colors.length] + filepaths[i] + ' ';
      }
      // Send to wrap function to be printed
      wrap('\u001b[1m\u001b[4mTesting:\u001b[0m\u001b[1m ' + files + '\n');
    }

    // Create CasperJS process
    var cspr = spawn('casperjs', command);
    cspr.stdout.setEncoding('utf8');
    // On receiving output from CasperJS, print it line by line
    cspr.stdout.on('data', function (data) {
      var lines = data.toString().split(/(\e?\n)/g);
      for (var j = 0; j < lines.length; j++) {
        grunt.log.write(lines[j]);
      }
    });

    // Captures errors from CasperJS and prints them
    cspr.stderr.on('data', function (data) {
      grunt.log.error(data);
      done();
    });

    // On completion print message
    cspr.on('exit', function () {
      done();
    });
  });
};
<commit_msg>Remove leftover var.<commit_after>/*
 * grunt-ghost
 * https://github.com/colinwren/grunt-ghost
 *
 * Copyright (c) 2013 Colin Wren
 * Licensed under the MIT license.
 */

module.exports = function (grunt) {
  'use strict';
  // Create MultiTask 'ghost'
  grunt.registerMultiTask('ghost', 'Runs CasperJS Tests.', function () {
    // Get options object
    var options = this.data.options,
        // Tells Grunt that this asynchronous and that it is finished when
        // "done()" is called
        done = this.async(),
        // Get spawn function for the CasperJS process creation
        spawn = require('child_process').spawn,
        // Create array that will contain all the parameters for CasperJS
        command = [];

    // Get CasperJS test options and add them to command array
    if (options.xunit) {
      command.push('--xunit=' + options.xunit);
    }
    if (options.direct) {
      command.push('--direct');
    }
    if (options.includes) {
      command.push('--includes=' + options.includes.join());
    }
    if (options.logLevel) {
      command.push('--log-level=' + options.logLevel);
    }
    if (options.pre) {
      command.push('--pre=' + options.pre.join());
    }
    if (options.post) {
      command.push('--post=' + options.post.join());
    }
    if (options.failFast) {
      command.push('--fail-fast');
    }
    if (options.args) {
      command = command.concat(formatArgs(options.args));
    }

    // Get filepaths from 'src' and sorts alphabetically
    var filepaths = grunt.file.expandFiles(this.file.src).sort();

    // add CasperJS parameter array to filepath array
    command = filepaths.concat(command);

    // Function to wrap grunt log output at 80 characters
    var lastSpace;
    function wrap(str) {
      // Will run until there are no spaces in the string (All arguments have
      // spaces after them)
      if (str.indexOf(' ') === -1) {
        return;
      }
      // Finds last space in the first 80 characters of the string
      lastSpace = str.substr(0, 80).lastIndexOf(' ');
      // Writes string until the last space into grunt log
      grunt.log.write(str.substr(0, lastSpace) + '\n');
      // Calls itself with the rest of the string that was no logged
      wrap(str.substr(lastSpace + 1));
    }

    // Checks if something is an array
    function isArr (arr) {
      return Object.prototype.toString.call(arr) === '[object Array]';
    }

    // Formats named or anonymous arguments
    function formatArgs(params){
      var len,
          rtn = [];

      if (isArr(options.args)) {
        // Array of anonymous arguments
        len = params.length;
        for (var i = 0; i < len; i++) {
          rtn.push(params[i]);
        }
      } else {
        // Object containing named arguments
        for (var p in params) {
          rtn.push('--' + p + '=' + params[p]);
        }
      }

      return rtn;
    }

    // Additional Options
    // Prints command sent to CasperJS
    if (options.printCommand) {
      wrap('\u001b[1m\u001b[4mCommand:\u001b[0m casperjs ' +
          command.join(' ') + ' \n');
    }
    // Prints filepaths sent to CasperJS in alternating colors
    if (options.printFilePaths) {
      var files = '',
          colors = [
            '\u001b[34m', // Blue
            '\u001b[33m', // Yellow
            '\u001b[36m', // Cyan
            '\u001b[35m', // Magenta
            '\u001b[32m'  // Green
          ];

      // Give file paths alternating colors and add them to 'files' string
      for (var i = 0; i < filepaths.length; i++) {
        files += colors[i % colors.length] + filepaths[i] + ' ';
      }
      // Send to wrap function to be printed
      wrap('\u001b[1m\u001b[4mTesting:\u001b[0m\u001b[1m ' + files + '\n');
    }

    // Create CasperJS process
    var cspr = spawn('casperjs', command);
    cspr.stdout.setEncoding('utf8');
    // On receiving output from CasperJS, print it line by line
    cspr.stdout.on('data', function (data) {
      var lines = data.toString().split(/(\e?\n)/g);
      for (var j = 0; j < lines.length; j++) {
        grunt.log.write(lines[j]);
      }
    });

    // Captures errors from CasperJS and prints them
    cspr.stderr.on('data', function (data) {
      grunt.log.error(data);
      done();
    });

    // On completion print message
    cspr.on('exit', function () {
      done();
    });
  });
};
<|endoftext|>


<commit_before>var util = require('util'),
    _ = require('underscore'),
    uglifyJs = require('uglify-js-papandreou'),
    uglifyAst = require('uglifyast'),
    i18nTools = require('../i18nTools'),
    htmlLangCssSelectorRegExp = /^(html\[\s*lang\s*(?:=|\|=|~=)\s*(|'|").*?\1\s*\])(.*)$/i;

function assetNeedsLocalization(asset, assetGraph) {
    var needsLocalization = false;
    if (asset.type === 'JavaScript') {
        if (asset.incomingRelations.every(function (incomingRelation) {
            return incomingRelation.type !== 'HtmlScript' || incomingRelation.node.id !== 'bootstrapper';
        })) {
            var q = [asset.parseTree];
            while (!needsLocalization && q.length > 0) {
                var node = q.pop();

                if ((node[0] === 'name' && (node[1] === 'LOCALEID' || node[1] === 'SUPPORTEDLOCALEIDS' || node[1] === 'DEFAULTLOCALEID')) ||
                    (node[0] === 'call' && node[1][0] === 'name' && (node[1][1] === 'TR' || node[1][1] === 'TRPAT'))) {

                    needsLocalization = true;
                } else {
                    // Don't dive into the LVALUE in assignments:
                    for (var i = (node[0] === 'assign' ? 3 : 0) ; i < node.length ; i += 1) {
                        if (Array.isArray(node[i])) {
                            q.push(node[i]);
                        }
                    }
                }
            }
        }
    } else if (asset.isHtml) {
        i18nTools.eachI18nTagInHtmlDocument(asset.parseTree, function () {
            needsLocalization = true;
            return false;
        });
    } else if (asset.type === 'Css') {
        asset.eachRuleInParseTree(function (cssRule, parentRuleOrStylesheet) {
            if (cssRule.type === 1) { // cssom.CSSRule.STYLE_RULE
                if (htmlLangCssSelectorRegExp.test(cssRule.selectorText)) {
                    needsLocalization = true;
                    return false;
                }
            }
        });
    }
    return needsLocalization;
}

function isBootstrapperRelation(relation) {
    return relation.type === 'HtmlScript' && relation.node && relation.node.getAttribute('id') === 'bootstrapper';
}

function followRelationFn(relation) {
    return relation.type !== 'HtmlAnchor' && !isBootstrapperRelation(relation);
}

module.exports = function (queryObj, options) {
    var localeIds = options.localeIds.map(i18nTools.normalizeLocaleId),
        defaultLocaleId = i18nTools.normalizeLocaleId(options.defaultLocaleId || 'en'),
        infoObject = options.infoObject || {};

    return function cloneForEachLocale(assetGraph) {
        var assetNeedsLocalizationById = {};
        assetGraph.findAssets(_.extend({type: 'Html'}, queryObj)).forEach(function (originalHtmlAsset) {
            var assetToLocalizeById = {},
                assetsToLocalize = [];
            assetGraph.eachAssetPostOrder(originalHtmlAsset, followRelationFn, function (asset) {
                if (asset.isLoaded && (assetNeedsLocalization(asset) || assetGraph.findRelations({from: asset}).some(function (outgoingRelation) {return outgoingRelation.to.id in assetToLocalizeById;}))) {
                    assetToLocalizeById[asset.id] = asset;
                    assetsToLocalize.push(asset);
                }
            });

            var nonInlineAssetsToLocalizePreOrder = [];
            assetGraph.eachAssetPreOrder(originalHtmlAsset, followRelationFn, function (asset) {
                if (!asset.isInline && asset.id in assetToLocalizeById) {
                    nonInlineAssetsToLocalizePreOrder.push(asset);
                }
            });

            localeIds.forEach(function (localeId) {
                var allKeysForLocale = i18nTools.extractAllKeysForLocale(assetGraph, localeId),
                    trReplacer = i18nTools.createTrReplacer({
                        allKeysForLocale: allKeysForLocale,
                        localeId: localeId,
                        defaultLocaleId: defaultLocaleId,
                        infoObject: infoObject
                    }),
                    i18nTagReplacer = i18nTools.createI18nTagReplacer({
                        allKeysForLocale: allKeysForLocale,
                        localeId: localeId,
                        defaultLocaleId: defaultLocaleId,
                        infoObject: infoObject
                    }),
                    globalValueByName = {LOCALEID: localeId, SUPPORTEDLOCALEIDS: localeIds, DEFAULTLOCALEID: defaultLocaleId};

                ['localeCookieName'].forEach(function (optionName) {
                    if (options[optionName]) {
                        globalValueByName[optionName.toUpperCase()] = options[optionName];
                    }
                });

                var localizedAssets = [];

                function localizeAsset(asset) {
                    if (asset.type === 'JavaScript') {
                        if (asset.incomingRelations.every(isBootstrapperRelation)) {
                            return;
                        }
                        i18nTools.eachTrInAst(asset.parseTree, trReplacer);

                        var ifAndParentNodesToOptimize = [],
                            walker = uglifyJs.uglify.ast_walker();
                        walker.with_walkers({
                            name: function (name) {
                                if (Object.prototype.hasOwnProperty.call(globalValueByName, name)) {
                                    var stack = walker.stack(),
                                        node = stack[stack.length - 1];
                                    if (stack[stack.length - 2][0] !== 'assign') {
                                        Array.prototype.splice.apply(node, [0, node.length].concat(uglifyAst.objToAst(globalValueByName[node[1]])));
                                        for (var i = stack.length - 2 ; i >= 0 ; i -= 1) {
                                            var parentNode = stack[i];
                                            if (parentNode[0] === 'if') {
                                                ifAndParentNodesToOptimize.push([parentNode, stack[i - 1]]);
                                            } else if (parentNode[0] !== 'binary' && parentNode[0] !== 'unary-prefix' && parentNode[0] !== 'unary-postfix') {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }, function () {
                            walker.walk(asset.parseTree);
                        });
                        // Poor man's optimization: Replace if(false) with the else part and if(true) with the then part.
                        ifAndParentNodesToOptimize.forEach(function (ifAndParentNode) {
                            var ifNode = ifAndParentNode[0],
                                parentNode = ifAndParentNode[1],
                                statementArray = parentNode[0] === 'toplevel' && parentNode[1];
                            if (statementArray) {
                                var indexInStatementArray = statementArray.indexOf(ifNode);
                                if (indexInStatementArray !== -1) {
                                    var foldedAst = uglifyAst.foldConstant(ifNode[1]);
                                    if (foldedAst[0] === 'unary-prefix' && foldedAst[1] === '!' && foldedAst[2][0] === 'num') {
                                        var statementAsts = foldedAst[2][1] ? (ifNode[3] ? [ifNode[3]] : []) : (ifNode[2] ? [ifNode[2]] : []);
                                        if (statementAsts.length === 1 && statementAsts[0][0] === 'block') {
                                            statementAsts = statementAsts[0][1];
                                        }
                                        Array.prototype.splice.apply(statementArray, [indexInStatementArray, 1].concat(statementAsts));
                                    }
                                }
                            }
                        });
                        asset.markDirty();
                    } else if (asset.isHtml) {
                        var document = asset.parseTree;
                        i18nTools.eachI18nTagInHtmlDocument(document, i18nTagReplacer);
                        if (document.documentElement) {
                            document.documentElement.setAttribute('lang', localeId);
                        }
                        asset.markDirty();
                    } else if (asset.type === 'Css') {
                        var cssRules = [];
                        asset.eachRuleInParseTree(function (cssRule) {
                            if (cssRule.type === 1) { // cssom.CSSRule.STYLE_RULE
                                cssRules.push(cssRule);
                            }
                        });
                        // Traverse the rules in reverse so the indices aren't screwed up by deleting rules underway:
                        cssRules.reverse().forEach(function (cssRule) {
                            var matchSelectorText = cssRule.selectorText.match(htmlLangCssSelectorRegExp);
                            if (matchSelectorText) {
                                if (localizedAssets[0].parseTree.querySelectorAll(matchSelectorText[1]).length > 0) {
                                    cssRule.selectorText = 'html' + matchSelectorText[3];
                                } else {
                                    assetGraph.findRelations({from: asset}).forEach(function (outgoingRelation) {
                                        if (outgoingRelation.cssRule !== cssRule) {
                                            return;
                                        }
                                        if (outgoingRelation.to.isInline) {
                                            assetGraph.removeAsset(outgoingRelation.to);
                                        }
                                        // FIXME: Find out why outgoingRelation isn't in the graph when outgoingRelation.to is an inline image!
                                        if (outgoingRelation.assetGraph) {
                                            assetGraph.removeRelation(outgoingRelation);
                                        }
                                    });
                                    var containingCssRules = (cssRule.parentRule || cssRule.parentStyleSheet).cssRules;
                                    containingCssRules.splice(containingCssRules.indexOf(cssRule), 1);
                                }
                            }
                        });
                        asset.markDirty();
                    }
                }

                // asset.clone adds the asset to the graph and populates the relations. Since the localization
                // could introduce or remove relations, it needs to happen before the population.
                // The 'addAsset' event is emitted right before the population takes place, so that does the job.
                // (Would of course be cleaner if asset.clone was split up or supported a hook at this point).
                assetGraph.on('addAsset', localizeAsset);

                nonInlineAssetsToLocalizePreOrder.forEach(function (asset) {
                    var incomingRelationsFromLocalizedAssets = assetGraph.findRelations({to: asset, from: {nonInlineAncestor: localizedAssets}}),
                        targetUrl = asset.url.replace(/(\.\w+)?$/, '.' + localeId + '$1'),
                        existingLocalizedAsset = assetGraph.findAssets({url: targetUrl})[0];

                    if (existingLocalizedAsset) {
                        incomingRelationsFromLocalizedAssets.forEach(function (incomingRelation) {
                            incomingRelation.to = existingLocalizedAsset;
                            incomingRelation.refreshHref();
                        });
                    } else {
                        var localizedAsset = asset.clone(incomingRelationsFromLocalizedAssets);
                        localizedAsset.url = targetUrl;
                        localizedAssets.push(localizedAsset);
                    }
                });

                assetGraph.removeListener('addAsset', localizeAsset);
            });

            // Remove orphaned JavaScript and templates:

            nonInlineAssetsToLocalizePreOrder.forEach(function (asset) {
                if (asset.assetGraph && (asset === originalHtmlAsset || (!asset.isInline && assetGraph.findRelations({to: asset}).length === 0))) {
                    assetGraph.removeAsset(asset);
                }
            });
        });
    };
};
<commit_msg>cloneForEachLocale: Do dive into the RHS of assign nodes when replacing LOCALEID etc. Fixes bug introduced in a554609 (1.5.1+).<commit_after>var util = require('util'),
    _ = require('underscore'),
    uglifyJs = require('uglify-js-papandreou'),
    uglifyAst = require('uglifyast'),
    i18nTools = require('../i18nTools'),
    htmlLangCssSelectorRegExp = /^(html\[\s*lang\s*(?:=|\|=|~=)\s*(|'|").*?\1\s*\])(.*)$/i;

function assetNeedsLocalization(asset, assetGraph) {
    var needsLocalization = false;
    if (asset.type === 'JavaScript') {
        if (asset.incomingRelations.every(function (incomingRelation) {
            return incomingRelation.type !== 'HtmlScript' || incomingRelation.node.id !== 'bootstrapper';
        })) {
            var q = [asset.parseTree];
            while (!needsLocalization && q.length > 0) {
                var node = q.pop();

                if ((node[0] === 'name' && (node[1] === 'LOCALEID' || node[1] === 'SUPPORTEDLOCALEIDS' || node[1] === 'DEFAULTLOCALEID')) ||
                    (node[0] === 'call' && node[1][0] === 'name' && (node[1][1] === 'TR' || node[1][1] === 'TRPAT'))) {

                    needsLocalization = true;
                } else {
                    // Don't dive into the LVALUE in assignments:
                    for (var i = (node[0] === 'assign' ? 3 : 0) ; i < node.length ; i += 1) {
                        if (Array.isArray(node[i])) {
                            q.push(node[i]);
                        }
                    }
                }
            }
        }
    } else if (asset.isHtml) {
        i18nTools.eachI18nTagInHtmlDocument(asset.parseTree, function () {
            needsLocalization = true;
            return false;
        });
    } else if (asset.type === 'Css') {
        asset.eachRuleInParseTree(function (cssRule, parentRuleOrStylesheet) {
            if (cssRule.type === 1) { // cssom.CSSRule.STYLE_RULE
                if (htmlLangCssSelectorRegExp.test(cssRule.selectorText)) {
                    needsLocalization = true;
                    return false;
                }
            }
        });
    }
    return needsLocalization;
}

function isBootstrapperRelation(relation) {
    return relation.type === 'HtmlScript' && relation.node && relation.node.getAttribute('id') === 'bootstrapper';
}

function followRelationFn(relation) {
    return relation.type !== 'HtmlAnchor' && !isBootstrapperRelation(relation);
}

module.exports = function (queryObj, options) {
    var localeIds = options.localeIds.map(i18nTools.normalizeLocaleId),
        defaultLocaleId = i18nTools.normalizeLocaleId(options.defaultLocaleId || 'en'),
        infoObject = options.infoObject || {};

    return function cloneForEachLocale(assetGraph) {
        var assetNeedsLocalizationById = {};
        assetGraph.findAssets(_.extend({type: 'Html'}, queryObj)).forEach(function (originalHtmlAsset) {
            var assetToLocalizeById = {},
                assetsToLocalize = [];
            assetGraph.eachAssetPostOrder(originalHtmlAsset, followRelationFn, function (asset) {
                if (asset.isLoaded && (assetNeedsLocalization(asset) || assetGraph.findRelations({from: asset}).some(function (outgoingRelation) {return outgoingRelation.to.id in assetToLocalizeById;}))) {
                    assetToLocalizeById[asset.id] = asset;
                    assetsToLocalize.push(asset);
                }
            });

            var nonInlineAssetsToLocalizePreOrder = [];
            assetGraph.eachAssetPreOrder(originalHtmlAsset, followRelationFn, function (asset) {
                if (!asset.isInline && asset.id in assetToLocalizeById) {
                    nonInlineAssetsToLocalizePreOrder.push(asset);
                }
            });

            localeIds.forEach(function (localeId) {
                var allKeysForLocale = i18nTools.extractAllKeysForLocale(assetGraph, localeId),
                    trReplacer = i18nTools.createTrReplacer({
                        allKeysForLocale: allKeysForLocale,
                        localeId: localeId,
                        defaultLocaleId: defaultLocaleId,
                        infoObject: infoObject
                    }),
                    i18nTagReplacer = i18nTools.createI18nTagReplacer({
                        allKeysForLocale: allKeysForLocale,
                        localeId: localeId,
                        defaultLocaleId: defaultLocaleId,
                        infoObject: infoObject
                    }),
                    globalValueByName = {LOCALEID: localeId, SUPPORTEDLOCALEIDS: localeIds, DEFAULTLOCALEID: defaultLocaleId};

                ['localeCookieName'].forEach(function (optionName) {
                    if (options[optionName]) {
                        globalValueByName[optionName.toUpperCase()] = options[optionName];
                    }
                });

                var localizedAssets = [];

                function localizeAsset(asset) {
                    if (asset.type === 'JavaScript') {
                        if (asset.incomingRelations.every(isBootstrapperRelation)) {
                            return;
                        }
                        i18nTools.eachTrInAst(asset.parseTree, trReplacer);

                        var ifAndParentNodesToOptimize = [],
                            walker = uglifyJs.uglify.ast_walker();
                        walker.with_walkers({
                            name: function (name) {
                                if (Object.prototype.hasOwnProperty.call(globalValueByName, name)) {
                                    var stack = walker.stack(),
                                        node = stack[stack.length - 1],
                                        stackIndex = stack.length - 2;

                                    // Make sure that we're not in the LHS of an ['assign', ...] node:

                                    while (stackIndex >= 0 && stack[stackIndex][0] === 'dot') {
                                        stackIndex -= 1;
                                    }

                                    if (stack[stackIndex][0] !== 'assign' || stack[stackIndex][2] !== stack[stackIndex + 1]) {
                                        Array.prototype.splice.apply(node, [0, node.length].concat(uglifyAst.objToAst(globalValueByName[node[1]])));
                                        for (var i = stack.length - 2 ; i >= 0 ; i -= 1) {
                                            var parentNode = stack[i];
                                            if (parentNode[0] === 'if') {
                                                ifAndParentNodesToOptimize.push([parentNode, stack[i - 1]]);
                                            } else if (parentNode[0] !== 'binary' && parentNode[0] !== 'unary-prefix' && parentNode[0] !== 'unary-postfix') {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }, function () {
                            walker.walk(asset.parseTree);
                        });
                        // Poor man's optimization: Replace if(false) with the else part and if(true) with the then part.
                        ifAndParentNodesToOptimize.forEach(function (ifAndParentNode) {
                            var ifNode = ifAndParentNode[0],
                                parentNode = ifAndParentNode[1],
                                statementArray = parentNode[0] === 'toplevel' && parentNode[1];
                            if (statementArray) {
                                var indexInStatementArray = statementArray.indexOf(ifNode);
                                if (indexInStatementArray !== -1) {
                                    var foldedAst = uglifyAst.foldConstant(ifNode[1]);
                                    if (foldedAst[0] === 'unary-prefix' && foldedAst[1] === '!' && foldedAst[2][0] === 'num') {
                                        var statementAsts = foldedAst[2][1] ? (ifNode[3] ? [ifNode[3]] : []) : (ifNode[2] ? [ifNode[2]] : []);
                                        if (statementAsts.length === 1 && statementAsts[0][0] === 'block') {
                                            statementAsts = statementAsts[0][1];
                                        }
                                        Array.prototype.splice.apply(statementArray, [indexInStatementArray, 1].concat(statementAsts));
                                    }
                                }
                            }
                        });
                        asset.markDirty();
                    } else if (asset.isHtml) {
                        var document = asset.parseTree;
                        i18nTools.eachI18nTagInHtmlDocument(document, i18nTagReplacer);
                        if (document.documentElement) {
                            document.documentElement.setAttribute('lang', localeId);
                        }
                        asset.markDirty();
                    } else if (asset.type === 'Css') {
                        var cssRules = [];
                        asset.eachRuleInParseTree(function (cssRule) {
                            if (cssRule.type === 1) { // cssom.CSSRule.STYLE_RULE
                                cssRules.push(cssRule);
                            }
                        });
                        // Traverse the rules in reverse so the indices aren't screwed up by deleting rules underway:
                        cssRules.reverse().forEach(function (cssRule) {
                            var matchSelectorText = cssRule.selectorText.match(htmlLangCssSelectorRegExp);
                            if (matchSelectorText) {
                                if (localizedAssets[0].parseTree.querySelectorAll(matchSelectorText[1]).length > 0) {
                                    cssRule.selectorText = 'html' + matchSelectorText[3];
                                } else {
                                    assetGraph.findRelations({from: asset}).forEach(function (outgoingRelation) {
                                        if (outgoingRelation.cssRule !== cssRule) {
                                            return;
                                        }
                                        if (outgoingRelation.to.isInline) {
                                            assetGraph.removeAsset(outgoingRelation.to);
                                        }
                                        // FIXME: Find out why outgoingRelation isn't in the graph when outgoingRelation.to is an inline image!
                                        if (outgoingRelation.assetGraph) {
                                            assetGraph.removeRelation(outgoingRelation);
                                        }
                                    });
                                    var containingCssRules = (cssRule.parentRule || cssRule.parentStyleSheet).cssRules;
                                    containingCssRules.splice(containingCssRules.indexOf(cssRule), 1);
                                }
                            }
                        });
                        asset.markDirty();
                    }
                }

                // asset.clone adds the asset to the graph and populates the relations. Since the localization
                // could introduce or remove relations, it needs to happen before the population.
                // The 'addAsset' event is emitted right before the population takes place, so that does the job.
                // (Would of course be cleaner if asset.clone was split up or supported a hook at this point).
                assetGraph.on('addAsset', localizeAsset);

                nonInlineAssetsToLocalizePreOrder.forEach(function (asset) {
                    var incomingRelationsFromLocalizedAssets = assetGraph.findRelations({to: asset, from: {nonInlineAncestor: localizedAssets}}),
                        targetUrl = asset.url.replace(/(\.\w+)?$/, '.' + localeId + '$1'),
                        existingLocalizedAsset = assetGraph.findAssets({url: targetUrl})[0];

                    if (existingLocalizedAsset) {
                        incomingRelationsFromLocalizedAssets.forEach(function (incomingRelation) {
                            incomingRelation.to = existingLocalizedAsset;
                            incomingRelation.refreshHref();
                        });
                    } else {
                        var localizedAsset = asset.clone(incomingRelationsFromLocalizedAssets);
                        localizedAsset.url = targetUrl;
                        localizedAssets.push(localizedAsset);
                    }
                });

                assetGraph.removeListener('addAsset', localizeAsset);
            });

            // Remove orphaned JavaScript and templates:

            nonInlineAssetsToLocalizePreOrder.forEach(function (asset) {
                if (asset.assetGraph && (asset === originalHtmlAsset || (!asset.isInline && assetGraph.findRelations({to: asset}).length === 0))) {
                    assetGraph.removeAsset(asset);
                }
            });
        });
    };
};
<|endoftext|>


<commit_before>
<commit_msg>Delete script.js<commit_after><|endoftext|>


<commit_before>(function() {

var App = window.App;

App.wgs84 = new OpenLayers.Projection("EPSG:4326");
App.webmerc = new OpenLayers.Projection("EPSG:900913");

App.map_point = function(lon, lat) {
    return new OpenLayers.LonLat(lon, lat).transform(App.wgs84, App.webmerc);
};

App.show_feature_info = function(e) {
    var map_lonlat = App.map.getLonLatFromPixel(e.xy)
    App.hide_popup();
    if(! e.text) return;
    var popup_content = e.text;
    App.show_popup({
        'content': popup_content,
        'x': map_lonlat.lon,
        'y': map_lonlat.lat
    });
};

App.hide_popup = function() {
    if(App.popup) {
        App.popup.destroy();
        App.popup = null;
    }
};

App.show_popup = function(options) {
    App.hide_popup();
    App.popup = new OpenLayers.Popup.FramedCloud(
        "the_popup",
        new OpenLayers.LonLat(options['x'], options['y']),
        null,
        options['content'],
        null,
        true
    );
    App.popup.closeOnMove = true;
    App.map.addPopup(App.popup);
};

App.init = function() {
    var map = App.map = new OpenLayers.Map('map');
    map.addLayer(new OpenLayers.Layer.OSM());
    map.setCenter(App.map_point(25, 46), 7);
    map.addControl(new OpenLayers.Control.LayerSwitcher());

    var judete_layer = new OpenLayers.Layer.MapServer(
        "judete", App.MAPSERV_URL, {layers: 'judete'},
        {gutter: 15,
         projection: App.webmerc,
         isBaseLayer: false});
    //map.addLayer(judete_layer);

    //var money_layer = new OpenLayers.Layer.MapServer(
    //    "money", App.MAPSERV_URL, {layers: 'money'},
    //    {gutter: 200,
    //     projection: App.webmerc,
    //     isBaseLayer: false});
    var money_layer = new OpenLayers.Layer.WMS(
        "money", App.MAPSERV_URL, {layers: 'money', transparent: true},
        {gutter: 200,
         projection: App.webmerc,
         isBaseLayer: false});
    money_layer.srs = App.webmerc;
    map.addLayer(money_layer);

    var info_control = new OpenLayers.Control.WMSGetFeatureInfo({
        url: App.MAPSERV_URL,
        title: 'Identify features by clicking',
        layers: [money_layer],
        queryVisible: true
    });
    info_control.events.register("getfeatureinfo", App, App.show_feature_info);
    map.addControl(info_control);
    info_control.activate();
};

$(document).ready(function() {
    App.init();
});

})();
<commit_msg>linkify query results<commit_after>(function() {

var App = window.App;

App.wgs84 = new OpenLayers.Projection("EPSG:4326");
App.webmerc = new OpenLayers.Projection("EPSG:900913");

App.map_point = function(lon, lat) {
    return new OpenLayers.LonLat(lon, lat).transform(App.wgs84, App.webmerc);
};

App.show_feature_info = function(e) {
    var map_lonlat = App.map.getLonLatFromPixel(e.xy)
    App.hide_popup();
    if(! e.text) return;
    var popup_content = $(e.text);
    popup_content.find('li').each(function() {
        var li = $(this);
        var name = li.text();
        var href = '/table?localitate=' + encodeURIComponent(name);
        var link = $('<a>').text(name).attr({'href': href, 'target': '_blank'});
        li.empty().append(link);
    });
    App.show_popup({
        'content': $('<div>').append(popup_content).html(),
        'x': map_lonlat.lon,
        'y': map_lonlat.lat
    });
};

App.hide_popup = function() {
    if(App.popup) {
        App.popup.destroy();
        App.popup = null;
    }
};

App.show_popup = function(options) {
    App.hide_popup();
    App.popup = new OpenLayers.Popup.FramedCloud(
        "the_popup",
        new OpenLayers.LonLat(options['x'], options['y']),
        null,
        options['content'],
        null,
        true
    );
    App.popup.closeOnMove = true;
    App.map.addPopup(App.popup);
};

App.init = function() {
    var map = App.map = new OpenLayers.Map('map');
    map.addLayer(new OpenLayers.Layer.OSM());
    map.setCenter(App.map_point(25, 46), 7);
    map.addControl(new OpenLayers.Control.LayerSwitcher());

    var judete_layer = new OpenLayers.Layer.MapServer(
        "judete", App.MAPSERV_URL, {layers: 'judete'},
        {gutter: 15,
         projection: App.webmerc,
         isBaseLayer: false});
    //map.addLayer(judete_layer);

    //var money_layer = new OpenLayers.Layer.MapServer(
    //    "money", App.MAPSERV_URL, {layers: 'money'},
    //    {gutter: 200,
    //     projection: App.webmerc,
    //     isBaseLayer: false});
    var money_layer = new OpenLayers.Layer.WMS(
        "money", App.MAPSERV_URL, {layers: 'money', transparent: true},
        {gutter: 200,
         projection: App.webmerc,
         isBaseLayer: false});
    money_layer.srs = App.webmerc;
    map.addLayer(money_layer);

    var info_control = new OpenLayers.Control.WMSGetFeatureInfo({
        url: App.MAPSERV_URL,
        title: 'Identify features by clicking',
        layers: [money_layer],
        queryVisible: true
    });
    info_control.events.register("getfeatureinfo", App, App.show_feature_info);
    map.addControl(info_control);
    info_control.activate();
};

$(document).ready(function() {
    App.init();
});

})();
<|endoftext|>


<commit_before>module.exports = function (grunt){
  'use strict';

  var
    cmd = 'node',
    path = require('path'),
    mochaPath,
    istanbulPath;

  try {
    mochaPath = require.resolve('mocha/bin/_mocha');
  } catch (e) {
    grunt.log.error('Missing mocha peer dependency');
    return;
  }

  try {
    istanbulPath = require.resolve('istanbul/lib/cli');
  } catch (e) {
    grunt.log.error('Missing istanbul peer dependency');
    return;
  }

  function executeCheck(callback, coverageFolder, options) {
    var args = [], check = options.check;

    if (
      check.statements !== false ||
      check.lines !== false ||
      check.functions !== false ||
      check.branches !== false
      ) {
      args.push(istanbulPath);
      args.push('check-coverage');
      if (check.lines) {
        args.push('--lines');
        args.push(check.lines);
      }
      if (check.statements) {
        args.push('--statements');
        args.push(check.statements);
      }
      if (check.functions) {
        args.push('--functions');
        args.push(check.functions);
      }
      if (check.branches) {
        args.push('--branches');
        args.push(check.branches);
      }

      args.push('--dir=' + coverageFolder);

      grunt.verbose.ok('Will execute: ', 'node ' + args.join(' '));

      if (!options.dryRun) {
        grunt.util.spawn({
          cmd : cmd,
          args: args,
          opts: {
            env  : process.env,
            cwd  : process.cwd(),
            stdio: options.quiet ? 'ignore' : 'inherit'
          }
        }, function (err){
          if (err) {
            callback && callback(err);
            return;
          }
          callback && callback(null, 'Done. Minimum coverage threshold succeeded.');
        });

        return;
      } else {
        callback && callback(null, 'Would also execute post cover: node ' + args.join(' '));
        return;
      }
    }

    callback && callback();
  }

  grunt.registerMultiTask('istanbul_check_coverage', 'Solo task for checking coverage over different or many files.', function () {
    var
      done = this.async(),
      options = this.options({
        coverageFolder: 'coverage',
        check: {
          statements: false,
          lines: false,
          functions: false,
          branches: false
        }
      });

    executeCheck(function (err, result) {
      if (err) { return done(err); }
      if (options.coverage) {
        var coverage = grunt.file.read(path.join(coverageFolder, 'lcov.info'));
        return grunt.event.emit('coverage', coverage, function (d) {
          grunt.log.ok(result || 'Done. Check coverage folder.');
          done(d);
        });
      }
      grunt.log.ok(result || 'Done. Check coverage folder.');
      done();
    }, options.coverageFolder, options)
  });

  grunt.registerMultiTask('mocha_istanbul', 'Generate coverage report with Istanbul from mocha test', function (){
    if (!this.filesSrc.length || !grunt.file.isDir(this.filesSrc[0])) {
      grunt.fail.fatal('Missing src attribute with the folder with tests');
      return;
    }

    var
      options = this.options({
        require        : [],
        ui             : false,
        globals        : [],
        reporter       : false,
        timeout        : false,
        coverage       : false,
        slow           : false,
        grep           : false,
        dryRun         : false,
        quiet          : false,
        recursive      : false,
        mask           : false,
        root           : false,
        print          : false,
        noColors       : false,
        harmony        : false,
        coverageFolder : 'coverage',
        reportFormats  : ['lcov'],
        check          : {
          statements: false,
          lines     : false,
          functions : false,
          branches  : false
        },
        excludes       : false,
        mochaOptions   : false,
        istanbulOptions: false
      }),
      coverageFolder = path.join(process.cwd(), options.coverageFolder),
      rootFolderForCoverage = options.root ? path.join(process.cwd(), options.root) : '.',
      done = this.async(),
      args = [];

    if (options.harmony) {
      args.push('--harmony');
    }

    args.push(istanbulPath);              // node ./node_modules/istanbul/lib/cli.js
    args.push('cover');                   // node ./node_modules/istanbul/lib/cli.js cover

    if (typeof options.require === 'string') {
      options.require = [options.require];
    }

    if (options.excludes && options.excludes.length) {
      options.excludes.forEach(function(excluded){
        args.push('-x');
        args.push(excluded);
      });
    }

    args.push('--dir=' + coverageFolder); // node ./node_modules/istanbul/cli.js --dir=coverage
    if (options.root) {
      args.push('--root=' + rootFolderForCoverage);
    }
    if (options.print) {
      args.push('--print=' + options.print);
    }

    options.reportFormats.forEach(function (format){
      args.push('--report=' + format);
    });

    if (options.istanbulOptions && options.istanbulOptions.length) {
      options.istanbulOptions.forEach(function (opt){
        args.push(opt);
      });
    }

    args.push(mochaPath);                 // node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha
    args.push('--');                      // node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha --

    if (grunt.file.exists(path.join(process.cwd(), this.filesSrc[0], 'mocha.opts'))) {
      if (
        options.require.length ||
        options.globals.length ||
        options.ui ||
        options.reporter ||
        options.timeout ||
        options.slow ||
        options.grep ||
        options.mask ||
        options.noColors
      ) {
        grunt.log.error('Warning: mocha.opts exists, but overwriting with options');
      }
    }

    if (options.timeout) {
      args.push('--timeout');
      args.push(options.timeout);
    }

    if (options.require) {
      options.require.forEach(function (require){
        args.push('--require');
        args.push(require);
      });
    }
    if (options.ui) {
      args.push('--ui');
      args.push(options.ui);
    }
    if (options.noColors) {
      args.push('--no-colors');
    }
    if (options.reporter) {
      args.push('--reporter');
      args.push(options.reporter);
    }

    if (options.globals.length) {
      args.push('--globals');
      args.push(options.globals.join(','));
    }
    if (options.slow) {
      args.push('--slow');
      args.push(options.slow);
    }
    if (options.grep) {
      args.push('--grep');
      args.push(options.grep);
    }

    if (options.recursive) {
      args.push('--recursive');
    }

    var masked = this.filesSrc[0];

    if (options.mask) {
      masked = path.join(this.filesSrc[0], options.mask);
    }

    if (options.mochaOptions && options.mochaOptions.length) {
      options.mochaOptions.forEach(function (opt){
        args.push(opt);
      });
    }

    args.push(masked);

    grunt.verbose.ok('Will execute:', 'node ' + args.join(' '));

    if (!options.dryRun) {
      grunt.util.spawn({
        cmd : cmd,
        args: args,
        opts: {
          env  : process.env,
          cwd  : process.cwd(),
          stdio: options.quiet ? 'ignore' : 'inherit'
        }
      }, function (err, result){
        if (err) {
          grunt.log.error(result);
          done(false);
          return;
        }

        executeCheck(function (err, result) {
          if (!err) {
            if (options.coverage) {
              var coverage = grunt.file.read(path.join(coverageFolder, 'lcov.info'));
              grunt.event.emit('coverage', coverage, function (d) {
                grunt.log.ok(result || 'Done. Check coverage folder.');
                done(d);
              });
            } else {
              grunt.log.ok(result || 'Done. Check coverage folder.');
              done();
            }
          } else {
            done(err);
          }
        }, coverageFolder, options);
      });
    } else {
      executeCheck(function (err, would) {
        grunt.log.ok('Would execute:', 'node ' + args.join(' '));
        would && grunt.log.ok(would);
      }, coverageFolder, options);

      done();
    }

  });
};
<commit_msg>misunderstood the way istanbul determines the coverage files to check<commit_after>module.exports = function (grunt){
  'use strict';

  var
    cmd = 'node',
    path = require('path'),
    mochaPath,
    istanbulPath;

  try {
    mochaPath = require.resolve('mocha/bin/_mocha');
  } catch (e) {
    grunt.log.error('Missing mocha peer dependency');
    return;
  }

  try {
    istanbulPath = require.resolve('istanbul/lib/cli');
  } catch (e) {
    grunt.log.error('Missing istanbul peer dependency');
    return;
  }

  function executeCheck(callback, coverageFolder, options) {
    var args = [], check = options.check;

    if (
      check.statements !== false ||
      check.lines !== false ||
      check.functions !== false ||
      check.branches !== false
      ) {
      args.push(istanbulPath);
      args.push('check-coverage');
      if (check.lines) {
        args.push('--lines');
        args.push(check.lines);
      }
      if (check.statements) {
        args.push('--statements');
        args.push(check.statements);
      }
      if (check.functions) {
        args.push('--functions');
        args.push(check.functions);
      }
      if (check.branches) {
        args.push('--branches');
        args.push(check.branches);
      }

      args.push(coverageFolder + '/coverage*.json');

      grunt.verbose.ok('Will execute: ', 'node ' + args.join(' '));

      if (!options.dryRun) {
        grunt.util.spawn({
          cmd : cmd,
          args: args,
          opts: {
            env  : process.env,
            cwd  : process.cwd(),
            stdio: options.quiet ? 'ignore' : 'inherit'
          }
        }, function (err){
          if (err) {
            callback && callback(err);
            return;
          }
          callback && callback(null, 'Done. Minimum coverage threshold succeeded.');
        });

        return;
      } else {
        callback && callback(null, 'Would also execute post cover: node ' + args.join(' '));
        return;
      }
    }

    callback && callback();
  }

  grunt.registerMultiTask('istanbul_check_coverage', 'Solo task for checking coverage over different or many files.', function () {
    var
      done = this.async(),
      options = this.options({
        coverageFolder: 'coverage',
        check: {
          statements: false,
          lines: false,
          functions: false,
          branches: false
        }
      });

    executeCheck(function (err, result) {
      if (err) { return done(err); }
      if (options.coverage) {
        var coverage = grunt.file.read(path.join(coverageFolder, 'lcov.info'));
        return grunt.event.emit('coverage', coverage, function (d) {
          grunt.log.ok(result || 'Done. Check coverage folder.');
          done(d);
        });
      }
      grunt.log.ok(result || 'Done. Check coverage folder.');
      done();
    }, options.coverageFolder, options)
  });

  grunt.registerMultiTask('mocha_istanbul', 'Generate coverage report with Istanbul from mocha test', function (){
    if (!this.filesSrc.length || !grunt.file.isDir(this.filesSrc[0])) {
      grunt.fail.fatal('Missing src attribute with the folder with tests');
      return;
    }

    var
      options = this.options({
        require        : [],
        ui             : false,
        globals        : [],
        reporter       : false,
        timeout        : false,
        coverage       : false,
        slow           : false,
        grep           : false,
        dryRun         : false,
        quiet          : false,
        recursive      : false,
        mask           : false,
        root           : false,
        print          : false,
        noColors       : false,
        harmony        : false,
        coverageFolder : 'coverage',
        reportFormats  : ['lcov'],
        check          : {
          statements: false,
          lines     : false,
          functions : false,
          branches  : false
        },
        excludes       : false,
        mochaOptions   : false,
        istanbulOptions: false
      }),
      coverageFolder = path.join(process.cwd(), options.coverageFolder),
      rootFolderForCoverage = options.root ? path.join(process.cwd(), options.root) : '.',
      done = this.async(),
      args = [];

    if (options.harmony) {
      args.push('--harmony');
    }

    args.push(istanbulPath);              // node ./node_modules/istanbul/lib/cli.js
    args.push('cover');                   // node ./node_modules/istanbul/lib/cli.js cover

    if (typeof options.require === 'string') {
      options.require = [options.require];
    }

    if (options.excludes && options.excludes.length) {
      options.excludes.forEach(function(excluded){
        args.push('-x');
        args.push(excluded);
      });
    }

    args.push('--dir=' + coverageFolder); // node ./node_modules/istanbul/cli.js --dir=coverage
    if (options.root) {
      args.push('--root=' + rootFolderForCoverage);
    }
    if (options.print) {
      args.push('--print=' + options.print);
    }

    options.reportFormats.forEach(function (format){
      args.push('--report=' + format);
    });

    if (options.istanbulOptions && options.istanbulOptions.length) {
      options.istanbulOptions.forEach(function (opt){
        args.push(opt);
      });
    }

    args.push(mochaPath);                 // node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha
    args.push('--');                      // node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha --

    if (grunt.file.exists(path.join(process.cwd(), this.filesSrc[0], 'mocha.opts'))) {
      if (
        options.require.length ||
        options.globals.length ||
        options.ui ||
        options.reporter ||
        options.timeout ||
        options.slow ||
        options.grep ||
        options.mask ||
        options.noColors
      ) {
        grunt.log.error('Warning: mocha.opts exists, but overwriting with options');
      }
    }

    if (options.timeout) {
      args.push('--timeout');
      args.push(options.timeout);
    }

    if (options.require) {
      options.require.forEach(function (require){
        args.push('--require');
        args.push(require);
      });
    }
    if (options.ui) {
      args.push('--ui');
      args.push(options.ui);
    }
    if (options.noColors) {
      args.push('--no-colors');
    }
    if (options.reporter) {
      args.push('--reporter');
      args.push(options.reporter);
    }

    if (options.globals.length) {
      args.push('--globals');
      args.push(options.globals.join(','));
    }
    if (options.slow) {
      args.push('--slow');
      args.push(options.slow);
    }
    if (options.grep) {
      args.push('--grep');
      args.push(options.grep);
    }

    if (options.recursive) {
      args.push('--recursive');
    }

    var masked = this.filesSrc[0];

    if (options.mask) {
      masked = path.join(this.filesSrc[0], options.mask);
    }

    if (options.mochaOptions && options.mochaOptions.length) {
      options.mochaOptions.forEach(function (opt){
        args.push(opt);
      });
    }

    args.push(masked);

    grunt.verbose.ok('Will execute:', 'node ' + args.join(' '));

    if (!options.dryRun) {
      grunt.util.spawn({
        cmd : cmd,
        args: args,
        opts: {
          env  : process.env,
          cwd  : process.cwd(),
          stdio: options.quiet ? 'ignore' : 'inherit'
        }
      }, function (err, result){
        if (err) {
          grunt.log.error(result);
          done(false);
          return;
        }

        executeCheck(function (err, result) {
          if (!err) {
            if (options.coverage) {
              var coverage = grunt.file.read(path.join(coverageFolder, 'lcov.info'));
              grunt.event.emit('coverage', coverage, function (d) {
                grunt.log.ok(result || 'Done. Check coverage folder.');
                done(d);
              });
            } else {
              grunt.log.ok(result || 'Done. Check coverage folder.');
              done();
            }
          } else {
            done(err);
          }
        }, coverageFolder, options);
      });
    } else {
      executeCheck(function (err, would) {
        grunt.log.ok('Would execute:', 'node ' + args.join(' '));
        would && grunt.log.ok(would);
      }, coverageFolder, options);

      done();
    }

  });
};
<|endoftext|>


<commit_before>$(document).ready(function() {

    $('.search-results .map').each(function() {
        var map = new L.Map(this, {
            center: new L.LatLng(46, 25.0),
            zoom: 6,
            fadeAnimation: false
        });

        var zoom_box = $('.leaflet-control-zoom').parent();
        zoom_box.removeClass('leaflet-left').addClass('leaflet-right');

        if(R.debug) {
            var circle = new L.CircleMarker(new L.LatLng(46, 25));
            map.addLayer(circle);
        }

        var legend = $('
');
        legend.appendTo($('.leaflet-control-container', this));

        var osm_url = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
        var osm = new L.TileLayer(osm_url, {maxZoom: 18});
        map.addLayer(osm);

        function new_layer(options) {
            var layer = new L.GeoJSON();
            layer.features = [];
            $.extend(layer, options);

            layer.on('featureparse', function(e) {
                var name = e.properties['name'];
                var feature_layer = e.layer;
                feature_layer.name = name;
                layer.features.push(e.properties['_feature']);
                feature_layer.setStyle({
                    color: layer['color'],
                    weight: 2,
                    clickable: false
                });
            });

            map.addLayer(layer);
            return layer;
        }

        var layers = {
            judete: new_layer({color: '#888'}),
            sci: new_layer({color: '#b92'}),
            spa: new_layer({color: '#9b2'})
        };
        R.layers = layers;

        function features_at(latlng) {
            if(R.debug) { console.time(1); }
            var hit_list = [];
            $.each(layers, function(layer_name, layer) {
                $.each(layer.features, function(i, feature) {
                    if(hit_test(feature['geometry'], latlng)) {
                        hit_list.push({
                            name: feature['properties']['name'],
                            layer: layer
                        });
                    }
                });
            });
            if(R.debug) { console.timeEnd(1); }
            return hit_list;
        }

        function hit_list_html(hit_list) {
            var ul = $('
');
            $.each(hit_list, function(i, hit) {
                var item = $('
').appendTo(ul);
                var sample = $('
');
                sample.css({background: hit['layer']['color']});
                item.append(sample, hit['name'])[0];
            });
            return ul;
        }

        map.on('mousemove', function(e) {
            legend.empty().append($('').text(
                float_repr(e.latlng.lat, 4) + ', ' +
                float_repr(e.latlng.lng, 4)
            ));

            var hit_list = features_at(e.latlng);
            if(hit_list.length > 0) {
                legend.append(hit_list_html(hit_list));
            }

            if(R.debug) { circle.setLatLng(e.latlng); }
        });

        map.on('click', function(e) {
            var hit_list = features_at(e.latlng);
            if(hit_list.length > 0) {
                var popup = new L.Popup();
                popup.setLatLng(e.latlng);
                popup.setContent(hit_list_html(hit_list)[0]);
                map.openPopup(popup);
            }
        });

        function process_geometry(feature) {
            feature['properties']['_feature'] = feature;
            feature['geometry']['bbox'] = bounding_box(feature['geometry']);
        }

        var sitecode_hash = {};
        var sitename = {};
        $('.search-results .sitecode').each(function() {
            var code = $(this).text();
            sitecode_hash[code] = true;
            sitename[code] = $(this).parent('li').children('a.sitename').text();
        });
        var keep = function(code) { return sitecode_hash[code]; };

        function add_site_features(features, layer) {
            $.each(features, function(i, feature) {
                var sitecode = feature['properties']['SITECODE'];
                feature['properties']['name'] = sitename[sitecode];
                if(! keep(sitecode)) { return; }
                process_geometry(feature);
                layer.addGeoJSON(feature);
            });
        }

        $.getJSON(R.assets + 'sci-wgs84.geojson', function(data) {
            add_site_features(data['features'], layers['sci']);
        });

        $.getJSON(R.assets + 'spa-wgs84.geojson', function(data) {
            add_site_features(data['features'], layers['spa']);
        });

        $.getJSON(R.assets + 'judete-wgs84.geojson', function(data) {
            var layer = layers['judete'];
            $.each(data['features'], function(i, feature) {
                var name = feature['properties']['denjud'];
                name = name[0] + name.slice(1).toLowerCase();
                process_geometry(feature);
                feature['properties']['name'] = name;
                layer.addGeoJSON(feature);
            });
            layer.setStyle({
                color: layer['color'],
                weight: 2
            });
        });

    });

    function bounding_box(geometry) {
        if(geometry['type'] == 'Polygon') {
            return bounding_box_polygon(geometry['coordinates'][0]);
        }

        if(geometry['type'] == 'MultiPolygon') {
            return bounding_box_multipolygon(geometry['coordinates']);
        }
    }

    function bounding_box_polygon(ring) {
        var lng_list = $.map(ring, function(lnglat) { return lnglat[0]; });
        var lat_list = $.map(ring, function(lnglat) { return lnglat[1]; });
        return [
            Math.min.apply(null, lng_list),
            Math.min.apply(null, lat_list),
            Math.max.apply(null, lng_list),
            Math.max.apply(null, lat_list)
        ];
    }

    function bounding_box_multipolygon(coordinates) {
        var boxes = $.map(coordinates, function(poly_coords) {
            return [bounding_box_polygon(poly_coords[0])];
        });
        function extract(list, name) {
            return $.map(list, function(dic) { return dic[name]; });
        }
        return [
            Math.min.apply(null, extract(boxes, 0)),
            Math.min.apply(null, extract(boxes, 1)),
            Math.max.apply(null, extract(boxes, 2)),
            Math.max.apply(null, extract(boxes, 3))
        ];
    }

    function point_in_box(latlng, bbox) {
        if(! bbox)
            return true;
        if(latlng.lng < bbox[0] || latlng.lng > bbox[2])
            return false;
        if(latlng.lat < bbox[1] || latlng.lat > bbox[3])
            return false;
        return true;
    }

    function hit_test(geometry, latlng) {
        if(! point_in_box(latlng, geometry['bbox'])) {
            return false;
        }
        if(geometry['type'] == 'Polygon') {
            return hit_test_polygon(geometry['coordinates'], latlng);
        }
        if(geometry['type'] == 'MultiPolygon') {
            return hit_test_multipolygon(geometry['coordinates'], latlng);
        }
        return false;
    }

    function float_repr(value, digits) {
        var str = '';
        if(value < 0) {
            str += '-';
            value = -value;
        }

        consume();
        str += '.';
        while(digits) {
            consume();
            digits -= 1;
        }
        return str;

        function consume() {
            var f = Math.floor(value)
            str += f;
            value -= f;
            value *= 10;
        }
    }

    function hit_test_multipolygon(coordinates, latlng) {
        for(var c = 0; c < coordinates.length; c ++) {
            if(hit_test_polygon(coordinates[c], latlng)) {
                return true;
            }
        }
        return false;
    }

/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the Clear BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

    function hit_test_polygon(coordinates, latlng) {
        var numRings = coordinates.length;
        var contained = false;
        if(numRings > 0) {
            // check exterior ring - 1 means on edge, boolean otherwise
            contained = hit_test_ring(coordinates[0], latlng);
            if(contained !== 1) {
                if(contained && numRings > 1) {
                    // check interior rings
                    var hole;
                    for(var i=1; i<numRings; ++i) {
                        hole = hit_test_ring(coordinates[i], latlng);
                        if(hole) {
                            if(hole === 1) {
                                // on edge
                                contained = 1;
                            } else {
                                // in hole
                                contained = false;
                            }
                            break;
                        }
                    }
                }
            }
        }
        return contained;
    }

    function hit_test_ring(ring, latlng) {
        var digs = 14;
        var px = approx(latlng.lng, digs);
        var py = approx(latlng.lat, digs);
        function getX(y, x1, y1, x2, y2) {
            return (((x1 - x2) * y) + ((x2 * y1) - (x1 * y2))) / (y1 - y2);
        }
        var numSeg = ring.length - 1;
        var start, end, x1, y1, x2, y2, cx, cy;
        var crosses = 0;
        for(var i=0; i<numSeg; ++i) {
            start = ring[i];
            x1 = approx(start[0], digs);
            y1 = approx(start[1], digs);
            end = ring[i + 1];
            x2 = approx(end[0], digs);
            y2 = approx(end[1], digs);

            /**
             * The following conditions enforce five edge-crossing rules:
             *    1. points coincident with edges are considered contained;
             *    2. an upward edge includes its starting endpoint, and
             *    excludes its final endpoint;
             *    3. a downward edge excludes its starting endpoint, and
             *    includes its final endpoint;
             *    4. horizontal edges are excluded; and
             *    5. the edge-ray intersection point must be strictly right
             *    of the point P.
             */
            if(y1 == y2) {
                // horizontal edge
                if(py == y1) {
                    // point on horizontal line
                    if(x1 <= x2 && (px >= x1 && px <= x2) || // right or vert
                       x1 >= x2 && (px <= x1 && px >= x2)) { // left or vert
                        // point on edge
                        crosses = -1;
                        break;
                    }
                }
                // ignore other horizontal edges
                continue;
            }
            cx = approx(getX(py, x1, y1, x2, y2), digs);
            if(cx == px) {
                // point on line
                if(y1 < y2 && (py >= y1 && py <= y2) || // upward
                   y1 > y2 && (py <= y1 && py >= y2)) { // downward
                    // point on edge
                    crosses = -1;
                    break;
                }
            }
            if(cx <= px) {
                // no crossing to the right
                continue;
            }
            if(x1 != x2 && (cx < Math.min(x1, x2) || cx > Math.max(x1, x2))) {
                // no crossing
                continue;
            }
            if(y1 < y2 && (py >= y1 && py < y2) || // upward
               y1 > y2 && (py < y1 && py >= y2)) { // downward
                ++crosses;
            }
        }
        var contained = (crosses == -1) ?
            // on edge
            1 :
            // even (out) or odd (in)
            !!(crosses & 1);

        return contained;
    }

    function approx(num, sig) {
        var fig = 0;
        if (sig > 0) {
            fig = parseFloat(num.toPrecision(sig));
        }
        return fig;
    }

});
<commit_msg>link to view of sci/spa document<commit_after>$(document).ready(function() {

    $('.search-results .map').each(function() {
        var map = new L.Map(this, {
            center: new L.LatLng(46, 25.0),
            zoom: 6,
            fadeAnimation: false
        });

        var zoom_box = $('.leaflet-control-zoom').parent();
        zoom_box.removeClass('leaflet-left').addClass('leaflet-right');

        if(R.debug) {
            var circle = new L.CircleMarker(new L.LatLng(46, 25));
            map.addLayer(circle);
        }

        var legend = $('
');
        legend.appendTo($('.leaflet-control-container', this));

        var osm_url = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
        var osm = new L.TileLayer(osm_url, {maxZoom: 18});
        map.addLayer(osm);

        function new_layer(options) {
            var layer = new L.GeoJSON();
            layer.features = [];
            $.extend(layer, options);

            layer.on('featureparse', function(e) {
                var name = e.properties['name'];
                var feature_layer = e.layer;
                feature_layer.name = name;
                layer.features.push(e.properties['_feature']);
                feature_layer.setStyle({
                    color: layer['color'],
                    weight: 2,
                    clickable: false
                });
            });

            map.addLayer(layer);
            return layer;
        }

        var layers = {
            judete: new_layer({color: '#888'}),
            sci: new_layer({color: '#b92'}),
            spa: new_layer({color: '#9b2'})
        };
        R.layers = layers;

        function features_at(latlng) {
            if(R.debug) { console.time(1); }
            var hit_list = [];
            $.each(layers, function(layer_name, layer) {
                $.each(layer.features, function(i, feature) {
                    if(hit_test(feature['geometry'], latlng)) {
                        hit_list.push({
                            feature: feature,
                            layer: layer
                        });
                    }
                });
            });
            if(R.debug) { console.timeEnd(1); }
            return hit_list;
        }

        function hit_list_html(hit_list, item_content) {
            if(! item_content) {
                item_content = function(feature) {
                    return feature['properties']['name'];
                }
            }
            var ul = $('
');
            $.each(hit_list, function(i, hit) {
                var item = $('
').appendTo(ul);
                var sample = $('
');
                sample.css({background: hit['layer']['color']});
                item.append(sample, item_content(hit['feature']))[0];
            });
            return ul;
        }

        map.on('mousemove', function(e) {
            legend.empty().append($('').text(
                float_repr(e.latlng.lat, 4) + ', ' +
                float_repr(e.latlng.lng, 4)
            ));

            var hit_list = features_at(e.latlng);
            if(hit_list.length > 0) {
                legend.append(hit_list_html(hit_list));
            }

            if(R.debug) { circle.setLatLng(e.latlng); }
        });

        map.on('click', function(e) {
            var hit_list = features_at(e.latlng);
            if(hit_list.length > 0) {
                var popup = new L.Popup();
                popup.setLatLng(e.latlng);
                popup.setContent(hit_list_html(hit_list, linkify)[0]);
                map.openPopup(popup);
            }
        });

        function linkify(feature) {
            var url = feature['properties']['url'];
            var label = feature['properties']['name'];
            if(url) {
                return $('').attr('href', url).text(label);
            }
            else {
                return label;
            }
        }

        function process_geometry(feature) {
            feature['properties']['_feature'] = feature;
            feature['geometry']['bbox'] = bounding_box(feature['geometry']);
        }

        var sitecode_hash = {};
        var sitename = {};
        var site_url = {};
        $('.search-results .sitecode').each(function() {
            var code = $(this).text();
            sitecode_hash[code] = true;
            var a = $(this).parent('li').children('a.sitename')
            sitename[code] = a.text();
            site_url[code] = a.attr('href');
        });
        var keep = function(code) { return sitecode_hash[code]; };

        function add_site_features(features, layer) {
            $.each(features, function(i, feature) {
                var sitecode = feature['properties']['SITECODE'];
                feature['properties']['name'] = sitename[sitecode];
                feature['properties']['url'] = site_url[sitecode];
                if(! keep(sitecode)) { return; }
                process_geometry(feature);
                layer.addGeoJSON(feature);
            });
        }

        $.getJSON(R.assets + 'sci-wgs84.geojson', function(data) {
            add_site_features(data['features'], layers['sci']);
        });

        $.getJSON(R.assets + 'spa-wgs84.geojson', function(data) {
            add_site_features(data['features'], layers['spa']);
        });

        $.getJSON(R.assets + 'judete-wgs84.geojson', function(data) {
            var layer = layers['judete'];
            $.each(data['features'], function(i, feature) {
                var name = feature['properties']['denjud'];
                name = name[0] + name.slice(1).toLowerCase();
                process_geometry(feature);
                feature['properties']['name'] = name;
                layer.addGeoJSON(feature);
            });
            layer.setStyle({
                color: layer['color'],
                weight: 2
            });
        });

    });

    function bounding_box(geometry) {
        if(geometry['type'] == 'Polygon') {
            return bounding_box_polygon(geometry['coordinates'][0]);
        }

        if(geometry['type'] == 'MultiPolygon') {
            return bounding_box_multipolygon(geometry['coordinates']);
        }
    }

    function bounding_box_polygon(ring) {
        var lng_list = $.map(ring, function(lnglat) { return lnglat[0]; });
        var lat_list = $.map(ring, function(lnglat) { return lnglat[1]; });
        return [
            Math.min.apply(null, lng_list),
            Math.min.apply(null, lat_list),
            Math.max.apply(null, lng_list),
            Math.max.apply(null, lat_list)
        ];
    }

    function bounding_box_multipolygon(coordinates) {
        var boxes = $.map(coordinates, function(poly_coords) {
            return [bounding_box_polygon(poly_coords[0])];
        });
        function extract(list, name) {
            return $.map(list, function(dic) { return dic[name]; });
        }
        return [
            Math.min.apply(null, extract(boxes, 0)),
            Math.min.apply(null, extract(boxes, 1)),
            Math.max.apply(null, extract(boxes, 2)),
            Math.max.apply(null, extract(boxes, 3))
        ];
    }

    function point_in_box(latlng, bbox) {
        if(! bbox)
            return true;
        if(latlng.lng < bbox[0] || latlng.lng > bbox[2])
            return false;
        if(latlng.lat < bbox[1] || latlng.lat > bbox[3])
            return false;
        return true;
    }

    function hit_test(geometry, latlng) {
        if(! point_in_box(latlng, geometry['bbox'])) {
            return false;
        }
        if(geometry['type'] == 'Polygon') {
            return hit_test_polygon(geometry['coordinates'], latlng);
        }
        if(geometry['type'] == 'MultiPolygon') {
            return hit_test_multipolygon(geometry['coordinates'], latlng);
        }
        return false;
    }

    function float_repr(value, digits) {
        var str = '';
        if(value < 0) {
            str += '-';
            value = -value;
        }

        consume();
        str += '.';
        while(digits) {
            consume();
            digits -= 1;
        }
        return str;

        function consume() {
            var f = Math.floor(value)
            str += f;
            value -= f;
            value *= 10;
        }
    }

    function hit_test_multipolygon(coordinates, latlng) {
        for(var c = 0; c < coordinates.length; c ++) {
            if(hit_test_polygon(coordinates[c], latlng)) {
                return true;
            }
        }
        return false;
    }

/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the Clear BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

    function hit_test_polygon(coordinates, latlng) {
        var numRings = coordinates.length;
        var contained = false;
        if(numRings > 0) {
            // check exterior ring - 1 means on edge, boolean otherwise
            contained = hit_test_ring(coordinates[0], latlng);
            if(contained !== 1) {
                if(contained && numRings > 1) {
                    // check interior rings
                    var hole;
                    for(var i=1; i<numRings; ++i) {
                        hole = hit_test_ring(coordinates[i], latlng);
                        if(hole) {
                            if(hole === 1) {
                                // on edge
                                contained = 1;
                            } else {
                                // in hole
                                contained = false;
                            }
                            break;
                        }
                    }
                }
            }
        }
        return contained;
    }

    function hit_test_ring(ring, latlng) {
        var digs = 14;
        var px = approx(latlng.lng, digs);
        var py = approx(latlng.lat, digs);
        function getX(y, x1, y1, x2, y2) {
            return (((x1 - x2) * y) + ((x2 * y1) - (x1 * y2))) / (y1 - y2);
        }
        var numSeg = ring.length - 1;
        var start, end, x1, y1, x2, y2, cx, cy;
        var crosses = 0;
        for(var i=0; i<numSeg; ++i) {
            start = ring[i];
            x1 = approx(start[0], digs);
            y1 = approx(start[1], digs);
            end = ring[i + 1];
            x2 = approx(end[0], digs);
            y2 = approx(end[1], digs);

            /**
             * The following conditions enforce five edge-crossing rules:
             *    1. points coincident with edges are considered contained;
             *    2. an upward edge includes its starting endpoint, and
             *    excludes its final endpoint;
             *    3. a downward edge excludes its starting endpoint, and
             *    includes its final endpoint;
             *    4. horizontal edges are excluded; and
             *    5. the edge-ray intersection point must be strictly right
             *    of the point P.
             */
            if(y1 == y2) {
                // horizontal edge
                if(py == y1) {
                    // point on horizontal line
                    if(x1 <= x2 && (px >= x1 && px <= x2) || // right or vert
                       x1 >= x2 && (px <= x1 && px >= x2)) { // left or vert
                        // point on edge
                        crosses = -1;
                        break;
                    }
                }
                // ignore other horizontal edges
                continue;
            }
            cx = approx(getX(py, x1, y1, x2, y2), digs);
            if(cx == px) {
                // point on line
                if(y1 < y2 && (py >= y1 && py <= y2) || // upward
                   y1 > y2 && (py <= y1 && py >= y2)) { // downward
                    // point on edge
                    crosses = -1;
                    break;
                }
            }
            if(cx <= px) {
                // no crossing to the right
                continue;
            }
            if(x1 != x2 && (cx < Math.min(x1, x2) || cx > Math.max(x1, x2))) {
                // no crossing
                continue;
            }
            if(y1 < y2 && (py >= y1 && py < y2) || // upward
               y1 > y2 && (py < y1 && py >= y2)) { // downward
                ++crosses;
            }
        }
        var contained = (crosses == -1) ?
            // on edge
            1 :
            // even (out) or odd (in)
            !!(crosses & 1);

        return contained;
    }

    function approx(num, sig) {
        var fig = 0;
        if (sig > 0) {
            fig = parseFloat(num.toPrecision(sig));
        }
        return fig;
    }

});
<|endoftext|>


<commit_before>'use strict';
const async = require('async');
const fs = require('fs');
const path = require('path');
const AWS = require('aws-sdk');

/**
 * Configure the plugin-tasks.
 *
 * @param {Object} config
 * @returns {Object} {{prepare: {Function} prepare, deploy: {Function} deploy}}
 */
exports.configure = function(config) {
  return {

    prepare: function(context, done) {
      async.waterfall([

        async.apply(validateConfig, config, context),
        async.apply(initializeAWS, config, context),
        async.apply(deleteArtifact, config, context)

      ], done);
    },

    deploy: function(context, done) {
      context.comment('Start deployment ...');

      async.waterfall([

        // create the aws artifact
        async.apply(createArtifact, config, context),
        async.apply(deployToAWS, config, context)

      ], function(err) {
        if(!err) context.comment('Deployment successful');
        done(err);
      });
    }

  };

};

/**
 * Evaluate the config object and fill in additional config data
 *
 * @param {Object} config
 * @param {Object} context
 * @param {Function} callback
 */
function validateConfig(config, context, callback) {
  if(!config) return callback('config undefined');

  if(!config.applicationName) return callback('application-name is undefined');
  if(!config.deploymentGroup) return callback('deployment-group is undefined');
  if(!config.s3Bucket) return callback('s3-bucket is undefined');
  if(!config.region) return callback('region is undefined');
  if(!config.sourcePath) return callback('the source-path is undefined');

  // fill config with computed properties
  config.buildDirectory = 'aws_build';
  config.artifactName = `${config.applicationName}_strider_artifact.zip`;
  config.artifactPath = path.join(config.buildDirectory, config.artifactName);
  config.absArtifactPath = path.join(context.dataDir, config.artifactPath);

  callback();
}

/**
 * Initialize the AWS-SDK
 *
 * @param {Object} config
 * @param {Object} context
 * @param {Function} callback
 */
function initializeAWS(config, context, callback) {
  AWS.config.region = config.region;

  // configure the credential provider chain
  const awsCredentials = config.awsCredentials;
  const providers = [];

  if(awsCredentials) {
    const mode = awsCredentials.mode;

    // set explicit credentials, if there are any
    if(( mode === 'explicit' || mode === 'standard' ) && awsCredentials.credentials) {
      providers.push(function () {
        return new AWS.Credentials(config.awsCredentials.credentials);
      });
    }

    // set shared credentials profile or zero
    if(mode === 'shared' || mode === 'standard') {
      providers.push(function () {
        return new AWS.SharedIniFileCredentials(config.awsCredentials.profile);
      });
    }

    // set environment credentials profile or zero
    if(mode === 'environment' || mode === 'standard') {
      providers.push(function () {
        return new AWS.EnvironmentCredentials(config.awsCredentials.environment);
      });
    }

    AWS.CredentialProviderChain.defaultProviders = providers;
  }

  // search for credentials
  const providerChain = new AWS.CredentialProviderChain();
  providerChain.resolve(function(err, credentials) {
    if(err) return callback(err);

    AWS.config.credentials = credentials;
    callback();
  });
}

/**
 * Deploy the revision to AWS
 *
 * @param config
 * @param context
 * @param callback
 */
function deployToAWS(config, context, callback) {
  context.comment('Deploy to AWS ...');

  // aws service interfaces
  const s3 = new AWS.S3({apiVersion: '2006-03-01'});
  const codedeploy = new AWS.CodeDeploy({apiVersion: '2014-10-06'});

  async.waterfall([

    // load artifact to s3
    function(callback) {

      const stream = fs.createReadStream(config.absArtifactPath);

      if(!stream) return callback('artifact not found');

      var params = {Bucket: config.s3Bucket, Key: config.artifactName, Body: stream};
      s3.upload(params, callback);

    },

    // create new deployment from revision
    function(s3Object, callback) {
      const deployParams = {
        applicationName: config.applicationName,
        deploymentGroupName: config.deploymentGroup,
        revision: {
          revisionType: 'S3',
          s3Location: {
            bucket: config.s3Bucket,
            bundleType: 'zip',
            eTag: s3Object.ETag,
            key: config.artifactName
            //version: 'STRING_VALUE'
          }
        },
        description: 'Deployment via strider'
      };

      // deploy revision
      codedeploy.createDeployment(deployParams, callback);
    },

    // monitor deployment
    function(deployment, callback) {
      context.log(deployment);
      monitorDeployment(context, codedeploy, deployment, callback);
    },

    // evaluate deployment result
    function(deployment, callback) {
      context.log(deployment);
      if(deployment.status === 'Succeeded') callback();
      else callback(deployment.errorInformation);
    }

  ], callback);
}

/**
 * Periodically request the deployment status and print it to the strider console.
 * Return, as soon as the jon is finished.
 *
 * @param {Object} context
 * @param {Object} codedeploy
 * @param {Object} params
 * @param {Function} callback
 */
function monitorDeployment(context, codedeploy, params, callback) {

  const delay = 2000;

  const refresh = function() {
    codedeploy.getDeployment(params, function(err, result) {
      if(err) return callback(err);

      const deploymentInfo = result.deploymentInfo || {};

      printDeploymentUpdate(context, deploymentInfo);

      // check the status
      switch(deploymentInfo.status) {

        // restart timeout
      case 'Created':
      case 'Queued':
      case 'InProgress':
        setTimeout(refresh, delay);
        break;

        // return result
      default:
        return callback(null, deploymentInfo);
      }
    });
  };

  refresh();
}

/**
 * Print the deployment-status
 *
 * @param {Object} context
 * @param {Object} deployment
 */
function printDeploymentUpdate(context, deployment) {
  context.comment(`Status: ${deployment.status}`);
  if(deployment.errorInformation) {
    context.comment(`Error: ${errorInformation}`);
  }
}

/**
 * Bundle the build artifact.
 *
 * @param {Object} config
 * @param {Object} context
 * @param {Function} callback
 */
function createArtifact(config, context, callback) {
  context.comment('Bundle aws artifact ...');

  async.waterfall([

    // create build directory
    function (callback) {
      context.cmd(`mkdir ${config.buildDirectory}`, function () {
        callback();
      });
    },

    // create the aws artifact
    function (callback) {
      var command = `zip ${config.artifactPath} ${config.sourcePath}` +
        ' --recurse-paths' +
        ` --exclude ${config.buildDirectory}/*`;

      if(config.excludeString) command = command + ` ${config.excludeString}`;
      if(config.quietBuild) command = command + ' --quiet';

      context.cmd(command, function () {
        callback();
      });
    }

  ], callback);
}

/**
 * Delete an old build-directory.
 *
 * @param {Object} config
 * @param {Object} context
 * @param {Function} callback
 */
function deleteArtifact(config, context, callback) {
  context.comment('Delete old artifact ...');
  context.cmd(`rm -r ${config.buildDirectory}`, function() {callback();});
}
<commit_msg>delete some comment<commit_after>'use strict';
const async = require('async');
const fs = require('fs');
const path = require('path');
const AWS = require('aws-sdk');

/**
 * Configure the plugin-tasks.
 *
 * @param {Object} config
 * @returns {Object} {{prepare: {Function} prepare, deploy: {Function} deploy}}
 */
exports.configure = function(config) {
  return {

    prepare: function(context, done) {
      async.waterfall([

        async.apply(validateConfig, config, context),
        async.apply(initializeAWS, config, context),
        async.apply(deleteArtifact, config, context)

      ], done);
    },

    deploy: function(context, done) {
      context.comment('Start deployment ...');

      async.waterfall([

        async.apply(createArtifact, config, context),
        async.apply(deployToAWS, config, context)

      ], function(err) {
        if(!err) context.comment('Deployment successful');
        done(err);
      });
    }

  };

};

/**
 * Evaluate the config object and fill in additional config data
 *
 * @param {Object} config
 * @param {Object} context
 * @param {Function} callback
 */
function validateConfig(config, context, callback) {
  if(!config) return callback('config undefined');

  if(!config.applicationName) return callback('application-name is undefined');
  if(!config.deploymentGroup) return callback('deployment-group is undefined');
  if(!config.s3Bucket) return callback('s3-bucket is undefined');
  if(!config.region) return callback('region is undefined');
  if(!config.sourcePath) return callback('the source-path is undefined');

  // fill config with computed properties
  config.buildDirectory = 'aws_build';
  config.artifactName = `${config.applicationName}_strider_artifact.zip`;
  config.artifactPath = path.join(config.buildDirectory, config.artifactName);
  config.absArtifactPath = path.join(context.dataDir, config.artifactPath);

  callback();
}

/**
 * Initialize the AWS-SDK
 *
 * @param {Object} config
 * @param {Object} context
 * @param {Function} callback
 */
function initializeAWS(config, context, callback) {
  AWS.config.region = config.region;

  // configure the credential provider chain
  const awsCredentials = config.awsCredentials;
  const providers = [];

  if(awsCredentials) {
    const mode = awsCredentials.mode;

    // set explicit credentials, if there are any
    if(( mode === 'explicit' || mode === 'standard' ) && awsCredentials.credentials) {
      providers.push(function () {
        return new AWS.Credentials(config.awsCredentials.credentials);
      });
    }

    // set shared credentials profile or zero
    if(mode === 'shared' || mode === 'standard') {
      providers.push(function () {
        return new AWS.SharedIniFileCredentials(config.awsCredentials.profile);
      });
    }

    // set environment credentials profile or zero
    if(mode === 'environment' || mode === 'standard') {
      providers.push(function () {
        return new AWS.EnvironmentCredentials(config.awsCredentials.environment);
      });
    }

    AWS.CredentialProviderChain.defaultProviders = providers;
  }

  // search for credentials
  const providerChain = new AWS.CredentialProviderChain();
  providerChain.resolve(function(err, credentials) {
    if(err) return callback(err);

    AWS.config.credentials = credentials;
    callback();
  });
}

/**
 * Deploy the revision to AWS
 *
 * @param config
 * @param context
 * @param callback
 */
function deployToAWS(config, context, callback) {
  context.comment('Deploy to AWS ...');

  // aws service interfaces
  const s3 = new AWS.S3({apiVersion: '2006-03-01'});
  const codedeploy = new AWS.CodeDeploy({apiVersion: '2014-10-06'});

  async.waterfall([

    // load artifact to s3
    function(callback) {

      const stream = fs.createReadStream(config.absArtifactPath);

      if(!stream) return callback('artifact not found');

      var params = {Bucket: config.s3Bucket, Key: config.artifactName, Body: stream};
      s3.upload(params, callback);

    },

    // create new deployment from revision
    function(s3Object, callback) {
      const deployParams = {
        applicationName: config.applicationName,
        deploymentGroupName: config.deploymentGroup,
        revision: {
          revisionType: 'S3',
          s3Location: {
            bucket: config.s3Bucket,
            bundleType: 'zip',
            eTag: s3Object.ETag,
            key: config.artifactName
            //version: 'STRING_VALUE'
          }
        },
        description: 'Deployment via strider'
      };

      // deploy revision
      codedeploy.createDeployment(deployParams, callback);
    },

    // monitor deployment
    function(deployment, callback) {
      context.log(deployment);
      monitorDeployment(context, codedeploy, deployment, callback);
    },

    // evaluate deployment result
    function(deployment, callback) {
      context.log(deployment);
      if(deployment.status === 'Succeeded') callback();
      else callback(deployment.errorInformation);
    }

  ], callback);
}

/**
 * Periodically request the deployment status and print it to the strider console.
 * Return as soon as the jon is finished.
 *
 * @param {Object} context
 * @param {Object} codedeploy
 * @param {Object} params
 * @param {Function} callback
 */
function monitorDeployment(context, codedeploy, params, callback) {
  const refresh = function() {
    codedeploy.getDeployment(params, function(err, result) {
      if(err) return callback(err);

      const deploymentInfo = result.deploymentInfo || {};

      printDeploymentUpdate(context, deploymentInfo);

      switch(deploymentInfo.status) {
        // restart timeout
      case 'Created':
      case 'Queued':
      case 'InProgress':
        setTimeout(refresh, 2000);
        break;

      default:
        return callback(null, deploymentInfo);
      }
    });
  };

  refresh();
}

/**
 * Print the deployment-status
 *
 * @param {Object} context
 * @param {Object} deployment
 */
function printDeploymentUpdate(context, deployment) {
  context.comment(`Status: ${deployment.status}`);
  if(deployment.errorInformation) {
    context.comment(`Error: ${deployment.errorInformation.message}`);
  }
}

/**
 * Bundle the build artifact.
 *
 * @param {Object} config
 * @param {Object} context
 * @param {Function} callback
 */
function createArtifact(config, context, callback) {
  context.comment('Bundle aws artifact ...');

  async.waterfall([

    // create build directory
    function (callback) {
      context.cmd(`mkdir ${config.buildDirectory}`, () => callback());
    },

    // create the aws artifact
    function (callback) {
      var command = `zip ${config.artifactPath} ${config.sourcePath}` +
        ' --recurse-paths' +
        ` --exclude ${config.buildDirectory}/*`;

      if(config.excludeString) command = command + ` ${config.excludeString}`;
      if(config.quietBuild) command = command + ' --quiet';

      context.cmd(command, () => callback());
    }

  ], callback);
}

/**
 * Delete an old build-directory.
 *
 * @param {Object} config
 * @param {Object} context
 * @param {Function} callback
 */
function deleteArtifact(config, context, callback) {
  context.comment('Delete old artifact ...');
  context.cmd(`rm -r ${config.buildDirectory}`, function() {callback();});
}
<|endoftext|>