<commit_before>'use strict';
/**
 * @file
 * WabPageTest diff API
 */

var _ = require('lodash');
var ask = require('vow-asker');
var Q = require('q');
var WebPageTest = require('webpagetest');

var httpResources = require('./http-resources');
var logger = require('./log');

/**
 * Run WebPageTest diff
 *
 * @param {WPTDiff.Params} params
 *
 * @returns {Promise<Object>}
 */
module.exports = function runWptDiff(params) {
    logger.info('[wtp-diff] Start diff with params:', params);

    var differ = new WPTDiff(params.apiKey, params.host);
    return differ.run(params.urls)
        .then(function (data) {
            logger.info('[wtp-diff] Diff complete');
            return data;
        });
};

module.exports.WPTDiff = WPTDiff;

/**
 * Compare object constructor
 *
 * @param {String} [apiKey]
 * @param {String} [host] service host
 *
 * @constructor
 */
function WPTDiff(apiKey, host) {
    host = host || this.DEFAULT_SERVICE_HOST;

    this._apiKey = apiKey;
    this._host = host;
    this._wpt = new WebPageTest(host, apiKey);
}

_.assign(WPTDiff.prototype, /** @lends WPTDiff.prototype */ {
    DEFAULT_SERVICE_HOST: 'www.webpagetest.org',

    COMPLETE_POLLING_INTERVAL: 1000,

    // TODO: add params: label, location, connectivity, mobile
    TEST_OPTIONS: {
        bodies: true,
        timeline: true,
        video: true
    },

    /**
     * Get current WebPageTest host
     * @returns {String}
     */
    getHost: function () {
        return this._host;
    },

    /**
     * Get current WebPageTest API key
     * @returns {String}
     */
    getApiKey: function () {
        return this._apiKey;
    },

    /**
     * Run compare
     *
     * @param {String[]} urls
     *
     * @returns {Promise<Object>}
     */
    run: function (urls) {
        if (this._lock) {
            throw new Error('Already run');
        }
        this._lock = true;

        // Results that be returned to user
        this._results = {};

        return this._executePipeline(urls);
    },

    _executePipeline: function (urls) {
        return this.runTests(urls)
            .then(_.bind(this._requestTestsDetails, this))
            .then(_.bind(this._finalizePipeline, this));
    },

    _requestTestsDetails: function (testsData) {
        return Q.all([
            this._requestTestResults(testsData),
            this._requestVideo(testsData)
        ]);
    },

    _requestTestResults: function (testsData) {
        var that = this;

        this._results.results = {};

        var resultsPromises = testsData.map(function (testData) {
            return this.getTestDetails(testData.data.testId);
        }, this);

        return Q.all(resultsPromises)
            .then(function (results) {
                results = prepareWptResultList(results);

                results.forEach(function (testData) {
                    that._results.results[testData.data.id] = testData.data;
                });

                return results;
            });
    },

    _requestVideo: function (testsData) {
        return this.createVideo(testsData)
            .then(_.bind(this.getVideoPlayer, this));
    },

    _finalizePipeline: function () {
        this._lock = false;
        return this._results;
    },

    /**
     * Run pages tests
     *
     * @param {String[]} urls
     *
     * @returns {Promise<Object>} Test results, see https://clck.ru/9fX69
     */
    runTests: function (urls) {
        logger.info('[wtp-diff] Run tests for %s', urls.join(', '));

        return this._launchTests(urls)
            .then(_.bind(this._waitTestsComplete, this))
            .then(_.bind(this._rememberTestsData, this));
    },

    _launchTests: function (urls) {
        var testPromises = urls.map(function (url) {
            return Q.ninvoke(this._wpt, 'runTest', url, this.TEST_OPTIONS);
        }, this);

        return Q.all(testPromises)
            .then(prepareWptResultList)
            .then(function (data) {
                logger.info('[wtp-diff] Tests have launched');

                data.forEach(function (testData) {
                    var data = testData.data;
                    logger.info('[wtp-diff] Report for %s: %s ', data.testId, data.userUrl);
                });

                return data;
            });
    },

    _waitTestsComplete: function (testsDataList) {
        logger.info('[wtp-diff] Waiting for tests complete');

        var allReaders = testsDataList.map(function (testData) {
            var reader = _.bind(function () {
                return this.getTestStatus.apply(this, arguments);
            }, this, testData.data.testId);

            reader.id = 'GET ' + testData.data.testId;

            return reader;
        }, this);

        return httpResources.readResourceWhenReady(allReaders)
            .then(function (data) {
                logger.info('[wtp-diff] All tests complete');
                return data;
            });
    },

    _rememberTestsData: function (results) {
        var ids = this._results.ids = {};
        var testsInfo = this._results.tests = {};

        results.forEach(function (testData) {
            var data = testData.data;
            var id = data.id;
            var url = data.testInfo.url;

            ids[url] = id;

            testsInfo[id] = data;

            logger.info('[wtp-diff] Report URL for %s: %s', url, data.userUrl);
        }, this);

        return results;
    },

    /**
     * Get test status by id
     * @param {String} testId
     *
     * @returns {Promise<Object>} Status, see: https://clck.ru/9fXDC
     */
    getTestStatus: function (testId) {
        return Q.ninvoke(this._wpt, 'getTestStatus', testId)
            .then(prepareWptResult);
    },

    /**
     * Get test details
     *
     * @param {String} testId
     *
     * @returns {Promise<Object>}
     */
    getTestDetails: function (testId) {
        logger.info('[wtp-diff] Request results for %s', testId);
        return Q.ninvoke(this._wpt, 'getTestResults', testId)
            .then(function (data) {
                logger.info('[wtp-diff] Results for %s have received', testId);
                return data;
            });
    },

    /**
     * Create compare video
     *
     * @param {Object[]} testsDataList
     *
     * @returns {Promise<Object>} Video data
     */
    createVideo: function (testsDataList) {
        var that = this;

        var testIds = testsDataList.map(function (testData) {
            return testData.data.testId;
        });

        var idsStr = testIds.join(', ');
        logger.info('[wtp-diff] Create video for %s', idsStr);

        return Q.ninvoke(this._wpt, 'createVideo', idsStr, {})
            .then(function (videoData) {
                videoData = prepareWptResult(videoData);
                var data = videoData.data;

                logger.info('[wtp-diff] Video for %s complete, its id: %s', idsStr, data.videoId);

                that._results.video = data;
                return videoData;
            });
    },

    /**
     * Get video player data
     *
     * @param {Object} videoData
     *
     * @returns {Promise.<Object>} Player data
     */
    getVideoPlayer: function (videoData) {
        var statusUrl = videoData.data.jsonUrl;

        logger.info('[wtp-diff] Create video player for video %s', videoData.data.videoId);

        function readData() {
            return ask({url: statusUrl})
                .then(function (results) {
                    return JSON.parse(results.data);
                });
        }

        readData.id = 'CREATE_PLAYER';

        var that = this;
        return httpResources.readResourceWhenReady(readData)
            .then(function (playerData) {
                playerData = prepareWptResult(playerData);
                that._results.player = playerData.data;

                logger.info('[wtp-diff] Player created, ids URL: %s', playerData.data.embedUrl);
                return playerData;
            });
    }
});

function prepareWptResult(videoData) {
    return _.get(videoData, 0);
}

function prepareWptResultList(results) {
    return _.compact(_.flatten(results));
}
<commit_msg>Add API limit check<commit_after>'use strict';
/**
 * @file
 * WabPageTest diff API
 */

var _ = require('lodash');
var ask = require('vow-asker');
var Q = require('q');
var WebPageTest = require('webpagetest');

var httpResources = require('./http-resources');
var logger = require('./log');

/**
 * Run WebPageTest diff
 *
 * @param {WPTDiff.Params} params
 *
 * @returns {Promise<Object>}
 */
module.exports = function runWptDiff(params) {
    logger.info('[wtp-diff] Start diff with params:', params);

    var differ = new WPTDiff(params.apiKey, params.host);
    return differ.run(params.urls)
        .then(function (data) {
            logger.info('[wtp-diff] Diff complete');
            return data;
        });
};

module.exports.WPTDiff = WPTDiff;

/**
 * Compare object constructor
 *
 * @param {String} [apiKey]
 * @param {String} [host] service host
 *
 * @constructor
 */
function WPTDiff(apiKey, host) {
    host = host || this.DEFAULT_SERVICE_HOST;

    this._apiKey = apiKey;
    this._host = host;
    this._wpt = new WebPageTest(host, apiKey);
}

_.assign(WPTDiff.prototype, /** @lends WPTDiff.prototype */ {
    DEFAULT_SERVICE_HOST: 'www.webpagetest.org',

    COMPLETE_POLLING_INTERVAL: 1000,

    // TODO: add params: label, location, connectivity, mobile
    TEST_OPTIONS: {
        bodies: true,
        timeline: true,
        video: true
    },

    /**
     * Get current WebPageTest host
     * @returns {String}
     */
    getHost: function () {
        return this._host;
    },

    /**
     * Get current WebPageTest API key
     * @returns {String}
     */
    getApiKey: function () {
        return this._apiKey;
    },

    /**
     * Run compare
     *
     * @param {String[]} urls
     *
     * @returns {Promise<Object>}
     */
    run: function (urls) {
        if (this._lock) {
            throw new Error('Already run');
        }
        this._lock = true;

        // Results that be returned to user
        this._results = {};

        return this._executePipeline(urls);
    },

    _executePipeline: function (urls) {
        return this.runTests(urls)
            .then(_.bind(this._requestTestsDetails, this))
            .then(_.bind(this._finalizePipeline, this));
    },

    _requestTestsDetails: function (testsData) {
        return Q.all([
            this._requestTestResults(testsData),
            this._requestVideo(testsData)
        ]);
    },

    _requestTestResults: function (testsData) {
        var that = this;

        this._results.results = {};

        var resultsPromises = testsData.map(function (testData) {
            return this.getTestDetails(testData.data.testId);
        }, this);

        return Q.all(resultsPromises)
            .then(function (results) {
                results = prepareWptResultList(results);

                results.forEach(function (testData) {
                    that._results.results[testData.data.id] = testData.data;
                });

                return results;
            });
    },

    _requestVideo: function (testsData) {
        return this.createVideo(testsData)
            .then(_.bind(this.getVideoPlayer, this));
    },

    _finalizePipeline: function () {
        this._lock = false;
        return this._results;
    },

    /**
     * Run pages tests
     *
     * @param {String[]} urls
     *
     * @returns {Promise<Object>} Test results, see https://clck.ru/9fX69
     */
    runTests: function (urls) {
        logger.info('[wtp-diff] Run tests for %s', urls.join(', '));

        return this._launchTests(urls)
            .then(_.bind(this._waitTestsComplete, this))
            .then(_.bind(this._rememberTestsData, this));
    },

    _launchTests: function (urls) {
        var testPromises = urls.map(function (url) {
            return Q.ninvoke(this._wpt, 'runTest', url, this.TEST_OPTIONS);
        }, this);

        function checkStatus(data) {
            logger.debug('[wtp-diff] Launch tests data: %j', data);
            data.forEach(function (testData) {
                if (testData.statusCode >= 300) {
                    throw new Error('Launch error. Status: ' + testData.statusCode + ': ' + testData.statusText);
                }
            });
            return data;
        }

        function logResults(data) {
            logger.info('[wtp-diff] Tests have launched');

            data.forEach(function (testData) {
                var data = testData.data;
                logger.info('[wtp-diff] Report for %s: %s ', data.testId, data.userUrl);
            });

            return data;
        }

        return Q.all(testPromises)
            .then(prepareWptResultList)
            .then(checkStatus)
            .then(logResults);
    },

    _waitTestsComplete: function (testsDataList) {
        logger.info('[wtp-diff] Waiting for tests complete');

        var allReaders = testsDataList.map(function (testData) {
            var reader = _.bind(function () {
                return this.getTestStatus.apply(this, arguments);
            }, this, testData.data.testId);

            reader.id = 'GET ' + testData.data.testId;

            return reader;
        }, this);

        return httpResources.readResourceWhenReady(allReaders)
            .then(function (data) {
                logger.info('[wtp-diff] All tests complete');
                return data;
            });
    },

    _rememberTestsData: function (results) {
        var ids = this._results.ids = {};
        var testsInfo = this._results.tests = {};

        results.forEach(function (testData) {
            var data = testData.data;
            var id = data.id;
            var url = data.testInfo.url;

            ids[url] = id;

            testsInfo[id] = data;

            logger.info('[wtp-diff] Report URL for %s: %s', url, data.userUrl);
        }, this);

        return results;
    },

    /**
     * Get test status by id
     * @param {String} testId
     *
     * @returns {Promise<Object>} Status, see: https://clck.ru/9fXDC
     */
    getTestStatus: function (testId) {
        return Q.ninvoke(this._wpt, 'getTestStatus', testId)
            .then(prepareWptResult);
    },

    /**
     * Get test details
     *
     * @param {String} testId
     *
     * @returns {Promise<Object>}
     */
    getTestDetails: function (testId) {
        logger.info('[wtp-diff] Request results for %s', testId);
        return Q.ninvoke(this._wpt, 'getTestResults', testId)
            .then(function (data) {
                logger.info('[wtp-diff] Results for %s have received', testId);
                return data;
            });
    },

    /**
     * Create compare video
     *
     * @param {Object[]} testsDataList
     *
     * @returns {Promise<Object>} Video data
     */
    createVideo: function (testsDataList) {
        var that = this;

        var testIds = testsDataList.map(function (testData) {
            return testData.data.testId;
        });

        var idsStr = testIds.join(', ');
        logger.info('[wtp-diff] Create video for %s', idsStr);

        return Q.ninvoke(this._wpt, 'createVideo', idsStr, {})
            .then(function (videoData) {
                videoData = prepareWptResult(videoData);
                var data = videoData.data;

                logger.info('[wtp-diff] Video for %s complete, its id: %s', idsStr, data.videoId);

                that._results.video = data;
                return videoData;
            });
    },

    /**
     * Get video player data
     *
     * @param {Object} videoData
     *
     * @returns {Promise.<Object>} Player data
     */
    getVideoPlayer: function (videoData) {
        var statusUrl = videoData.data.jsonUrl;

        logger.info('[wtp-diff] Create video player for video %s', videoData.data.videoId);

        function readData() {
            return ask({url: statusUrl})
                .then(function (results) {
                    return JSON.parse(results.data);
                });
        }

        readData.id = 'CREATE_PLAYER';

        var that = this;
        return httpResources.readResourceWhenReady(readData)
            .then(function (playerData) {
                playerData = prepareWptResult(playerData);
                that._results.player = playerData.data;

                logger.info('[wtp-diff] Player created, ids URL: %s', playerData.data.embedUrl);
                return playerData;
            });
    }
});

function prepareWptResult(videoData) {
    return _.get(videoData, 0);
}

function prepareWptResultList(results) {
    return _.compact(_.flatten(results));
}
<|endoftext|>


<commit_before>var utile = require('../lib');

var myFN = function(/* a, b, c, callback */) {
  var args = utile.args(arguments);
  console.log(args);
};

myFN("x", "y", "z", function(){
  return 'ok';
})

/*
  OUTPUTS:

{ array: [ 'x', 'y', 'z' ],
  a: 'x',
  b: 'y',
  c: 'z',
  callback: [Function],
  cb: [Function],
  last: 'z' }

*/

myFN(function(){
  return 'ok';
})

/*

  OUTPUTS:

  { array: [],
    a: [Function],
    b: undefined,
    c: undefined,
    callback: [Function],
    cb: [Function],
    last: undefined }

*/

myFN("x", "y", function(){
  return 'ok';
})

/*

  OUTPUTS:

  { array: [ 'x', 'y' ],
    a: 'x',
    b: 'y',
    c: [Function],
    callback: [Function],
    cb: [Function],
    last: 'y' }

*/

myFN(["foo", "bar", "tar"], "car", function(){
  return 'ok';
})

/*

  OUTPUTS:

  { array: [ [ 'foo', 'bar', 'tar' ], 'car' ],
    a: [ 'foo', 'bar', 'tar' ],
    b: 'car',
    c: [Function],
    callback: [Function],
    cb: [Function],
    last: 'car' }

*/

return;
<commit_msg>[examples] Updated argument parsing example<commit_after>var utile = require('../lib');

//
// with contract comments
//
var myFN = function(/* a, b, c, callback */) {
  var args = utile.args(arguments);
  console.log(args);
};

myFN("x", "y", "z", function(){
  return 'ok';
})

/*
  OUTPUTS:

{ array: [ 'x', 'y', 'z' ],
  a: 'x',
  b: 'y',
  c: 'z',
  callback: [Function],
  cb: [Function],
  last: 'z' }

*/

//
// wihout any special comment contracts
//
var noCommentFN = function() {
  var args = utile.args(arguments);
  console.log(args);
};

noCommentFN("x", "y", "z", function() {
  return 'ok';
})

/*

  OUTPUTS

  { array: [ 'x', 'y', 'z' ],
    callback: [Function],
    cb: [Function],
    last: 'z' }
*/

/* additional variations of contract comment parsing */

myFN(function(){
  return 'ok';
})

/*

  OUTPUTS:

  { array: [],
    a: [Function],
    b: undefined,
    c: undefined,
    callback: [Function],
    cb: [Function],
    last: undefined }

*/

myFN("x", "y", function(){
  return 'ok';
})

/*

  OUTPUTS:

  { array: [ 'x', 'y' ],
    a: 'x',
    b: 'y',
    c: [Function],
    callback: [Function],
    cb: [Function],
    last: 'y' }

*/

myFN(["foo", "bar", "tar"], "car", function(){
  return 'ok';
})

/*

  OUTPUTS:

  { array: [ [ 'foo', 'bar', 'tar' ], 'car' ],
    a: [ 'foo', 'bar', 'tar' ],
    b: 'car',
    c: [Function],
    callback: [Function],
    cb: [Function],
    last: 'car' }

*/

return;
<|endoftext|>


<commit_before>/**
 * Created by AlexanderC on 11/5/15.
 */

'use strict';

import Kernel from 'deep-kernel';
import DeepCore from 'deep-core';

export class Framework {
  /**
   * @param {Object} servicesMap
   * @param {String} context
   */
  constructor(servicesMap, context) {
    this._context = context;
    this._services = this._resolveServicesMap(servicesMap);
    this._version = require('../package.json').version;
    this._kernelsMap = {};
  }

  /**
   * @returns {string}
   */
  static get ANONYMOUS_IDENTITY_KEY() {
    return 'anonymous';
  }

  /**
   * @returns {String}
   */
  get context() {
    return this._context;
  }

  /**
   * @returns {String}
   */
  get version() {
    return this._version;
  }

  /**
   *
   * @todo: improve it
   *
   * @param {Object} lambdaContext
   * @returns {Kernel}
   *
   * @sample:
   * ```
   * exports.handler = function (event, context) {
   *   DeepFramework.KernelFromLambdaContext(context).loadFromFile("_config.json", function (deepKernel) {
   *     new Handler(deepKernel).run(event, context);
   *   });
   * };
   * KernelFromLambdaContext
   * ```
   */
  KernelFromLambdaContext(lambdaContext) {
    let identityId = Framework.ANONYMOUS_IDENTITY_KEY;

    if (lambdaContext.hasOwnProperty('identity')
      && lambdaContext.identity.hasOwnProperty('cognitoIdentityPoolId')
      && lambdaContext.identity.hasOwnProperty('cognitoIdentityId')) {

      identityId = lambdaContext.identity.cognitoIdentityId;
    }

    return this._kernelCached(identityId);
  }

  /**
   * @param {String} id
   * @returns {Kernel}
   * @constructor
   */
  _kernelCached(id) {
    if (this._kernelsMap.hasOwnProperty(id)) {
      return this._kernelsMap[id];
    }

    this._kernelsMap[id] = this._createKernel();

    return this._kernelsMap[id];
  }

  /**
   * @todo: remove method in next release (back compatibility)
   *
   * @returns {Kernel}
   * @constructor
   */
  get Kernel() {
    return this._kernelCached(Framework.ANONYMOUS_IDENTITY_KEY);
  }

  /**
   * @returns {Function}
   * @constructor
   */
  get Core() {
    return DeepCore;
  }

  /**
   * @param {Object} servicesMap
   * @returns {Object}
   * @private
   */
  _resolveServicesMap(servicesMap) {
    let services = {};

    for (let serviceName in servicesMap) {
      if (!servicesMap.hasOwnProperty(serviceName)) {
        continue;
      }

      services[serviceName] = require(servicesMap[serviceName]);
    }

    return services;
  }

  /**
   * @returns {Kernel}
   * @private
   */
  _createKernel() {
    return new Kernel(this._services, this._context);
  }

  /**
   * @returns {String}
   */
  static get BACKEND_CONTEXT() {
    return Kernel.BACKEND_CONTEXT;
  }

  /**
   * @returns {String}
   */
  static get FRONTEND_CONTEXT() {
    return Kernel.FRONTEND_CONTEXT;
  }
}
<commit_msg>Fix hound error "Bad line breaking before<commit_after>/**
 * Created by AlexanderC on 11/5/15.
 */

'use strict';

import Kernel from 'deep-kernel';
import DeepCore from 'deep-core';

export class Framework {
  /**
   * @param {Object} servicesMap
   * @param {String} context
   */
  constructor(servicesMap, context) {
    this._context = context;
    this._services = this._resolveServicesMap(servicesMap);
    this._version = require('../package.json').version;
    this._kernelsMap = {};
  }

  /**
   * @returns {string}
   */
  static get ANONYMOUS_IDENTITY_KEY() {
    return 'anonymous';
  }

  /**
   * @returns {String}
   */
  get context() {
    return this._context;
  }

  /**
   * @returns {String}
   */
  get version() {
    return this._version;
  }

  /**
   *
   * @todo: improve it
   *
   * @param {Object} lambdaContext
   * @returns {Kernel}
   *
   * @sample:
   * ```
   * exports.handler = function (event, context) {
   *   DeepFramework.KernelFromLambdaContext(context).loadFromFile("_config.json", function (deepKernel) {
   *     new Handler(deepKernel).run(event, context);
   *   });
   * };
   * KernelFromLambdaContext
   * ```
   */
  KernelFromLambdaContext(lambdaContext) {
    let identityId = Framework.ANONYMOUS_IDENTITY_KEY;

    if (lambdaContext.hasOwnProperty('identity') &&
      lambdaContext.identity.hasOwnProperty('cognitoIdentityPoolId') &&
      lambdaContext.identity.hasOwnProperty('cognitoIdentityId')) {

      identityId = lambdaContext.identity.cognitoIdentityId;
    }

    return this._kernelCached(identityId);
  }

  /**
   * @param {String} id
   * @returns {Kernel}
   * @constructor
   */
  _kernelCached(id) {
    if (this._kernelsMap.hasOwnProperty(id)) {
      return this._kernelsMap[id];
    }

    this._kernelsMap[id] = this._createKernel();

    return this._kernelsMap[id];
  }

  /**
   * @todo: remove method in next release (back compatibility)
   *
   * @returns {Kernel}
   * @constructor
   */
  get Kernel() {
    return this._kernelCached(Framework.ANONYMOUS_IDENTITY_KEY);
  }

  /**
   * @returns {Function}
   * @constructor
   */
  get Core() {
    return DeepCore;
  }

  /**
   * @param {Object} servicesMap
   * @returns {Object}
   * @private
   */
  _resolveServicesMap(servicesMap) {
    let services = {};

    for (let serviceName in servicesMap) {
      if (!servicesMap.hasOwnProperty(serviceName)) {
        continue;
      }

      services[serviceName] = require(servicesMap[serviceName]);
    }

    return services;
  }

  /**
   * @returns {Kernel}
   * @private
   */
  _createKernel() {
    return new Kernel(this._services, this._context);
  }

  /**
   * @returns {String}
   */
  static get BACKEND_CONTEXT() {
    return Kernel.BACKEND_CONTEXT;
  }

  /**
   * @returns {String}
   */
  static get FRONTEND_CONTEXT() {
    return Kernel.FRONTEND_CONTEXT;
  }
}
<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

var React = require('react');
var Link = require('react-router').Link;
var DocsArticle = require('../../DocsArticle');
var Footer = require('grommet/components/Footer');
var Menu = require('grommet/components/Menu');
var Button = require('grommet/components/Button');

var FooterDoc = React.createClass({

  contextTypes: {
    routePrefix: React.PropTypes.string.isRequired
  },

  _onClick: function () {
    // no-op
  },

  render: function() {
    var inline =
    "\n  ...\n";
    return (
      <DocsArticle title="Footer" colorIndex="neutral-3">

Put things at the bottom.

{inline}

Options

large       true|false

Larger sized version.

small       true|false

Smaller sized version.

Options for <Link to={this.context.routePrefix + "box"}>Box</Link> are
          also available.

Examples

Form footer

              <Menu direction="row">
                <Button label="OK" primary={true} onClick={this._onClick} />
                <Button label="Cancel" onClick={this._onClick} />
              </Menu>

{" ..."}

Form footer right

              <Menu direction="row" justify="end">
                <Button label="Cancel" onClick={this._onClick} />
                <Button label="OK" primary={true} onClick={this._onClick} />
              </Menu>

{" ..."}

      </DocsArticle>
    );
  }
});

module.exports = FooterDoc;
<commit_msg>Added basic footer code.<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

var React = require('react');
var jsxToString = require('jsx-to-string').default;
var Link = require('react-router').Link;
var DocsArticle = require('../../DocsArticle');
var Footer = require('grommet/components/Footer');
var Menu = require('grommet/components/Menu');
var Button = require('grommet/components/Button');

var FooterDoc = React.createClass({

  contextTypes: {
    routePrefix: React.PropTypes.string.isRequired
  },

  _onClick: function () {
    // no-op
  },

  render: function() {
    var inline =
    "\n  ...\n";

    var basicFooter = (

        <Menu direction="row">
          <Button label="OK" primary={true} onClick={this._onClick} />
          <Button label="Cancel" onClick={this._onClick} />
        </Menu>

    );
    return (
      <DocsArticle title="Footer" colorIndex="neutral-3">

Put things at the bottom.

{inline}

Options

large       true|false

Larger sized version.

small       true|false

Smaller sized version.

Options for <Link to={this.context.routePrefix + "box"}>Box</Link> are
          also available.

Examples

Form footer

            {basicFooter}

{jsxToString(basicFooter)}

Form footer right

              <Menu direction="row" justify="end">
                <Button label="Cancel" onClick={this._onClick} />
                <Button label="OK" primary={true} onClick={this._onClick} />
              </Menu>

{" ..."}

      </DocsArticle>
    );
  }
});

module.exports = FooterDoc;
<|endoftext|>


<commit_before>import {EventEmitter} from 'events';

import is_function from 'lodash.isfunction';
import is_nil from 'lodash.isnil';
import is_string from 'lodash.isstring';
import cond from 'lodash.cond';
import constant from 'lodash.constant';
import noop from 'lodash.noop';
import uniq from 'lodash.uniq';

function overlay(parent) {
	let overlay = parent.querySelector('body > #modal-overlay');
	if (is_nil(overlay)) {
		overlay = document.createElement('div');
		overlay.id = 'modal-overlay';
		parent.appendChild(overlay);
	}
	return overlay;
}

function dialog_button(parent, role, label = '') {
	const item = document.createElement('li');
	const button = document.createElement('button');

	button.dataset.role = role;
	button.innerHTML = label;

	item.appendChild(button);
	parent.appendChild(item);

	return button;
}

function dialog_init_buttons(parent, buttons_descriptors) {
	const buttons_wrapper = document.createElement('ul');
	const emitter = new EventEmitter();

	parent.appendChild(buttons_wrapper);
	buttons_wrapper.className = 'buttons-wrapper';
	buttons_descriptors.forEach(({role, label}) => {
		const button = dialog_button(buttons_wrapper, role, label);
		const on_click = () => {
			emitter.emit('click', role);
			button.removeEventListener('click', on_click);
		}
		button.addEventListener('click', on_click);
	});

	return emitter;
}

function dialog_init_content(parent, content) {
	const content_wrapper = document.createElement('div');
	content_wrapper.className = 'content-wrapper';
	if (is_string(content)) {
		parent.innerHTML = content;
	} else {
		content_wrapper.appendChild(content);
	}
	parent.appendChild(content_wrapper);
	return content_wrapper;
}

export function Dialog({
	aboutToClose = noop,
	className = [],
	content,
	id = ''
} = {}) {
	const parent = document.querySelector('body');
	const dialog = document.createElement('div');

	dialog_init_content(dialog, content);
	const buttons_ = dialog_init_buttons(dialog, [{role: 'cancel', label: 'Cancel'}, {role: 'ok', label: 'Ok'}]);

	dialog.className = uniq([].concat(className, 'dialog')).join(' ');
	dialog.id = id;

	return {
		set aboutToClose(fn) {
			if (is_function(fn)) {
				aboutToClose = fn;
				return ;
			}
			throw new TypeError('argument must be a function');
		},
		run() {
			const terminate = () => {
				parent.removeChild(overlay(parent));
				parent.removeChild(dialog);
			};
			overlay(parent);
			parent.appendChild(dialog);
			dialog.style.left = `${(window.innerWidth - dialog.clientWidth)/2}px`;
			dialog.style.top = `${(window.innerHeight - dialog.clientHeight)/2}px`;
			return new Promise((resolve, reject) => {
				try {
					buttons_.once('click', action => {
						terminate();
						resolve(aboutToClose(action));
					});
				} catch (err) {
					terminate();
					reject(err);
				}
			});
		}
	};
}

export function Prompt(placeholder = '') {
	const input = document.createElement('input');

	input.type = 'text';
	input.placeholder = placeholder;

	return Dialog({
		aboutToClose: (role) => {
			if (role === 'ok') {
				return input.value;
			}
		},
		className: 'prompt',
		content: input
	});
}

export function Confirm(message) {
	return Dialog({
		aboutToClose: (role) => {
			return role === 'ok';
		},
		className: 'confirm',
		content: `<p>${message}</p>`
	});
}

const NOTICE_MESSAGE = 0;
const NOTICE_WARNING = 1;
const NOTICE_ERROR = 2;

const notice_icon = cond([
	[status => status === NOTICE_WARNING, constant('')],
	[status => status === NOTICE_ERROR,   constant('')],
	[constant(true), constant('')]
]);

export function Notice(message, status = NOTICE_MESSAGE) {
	return Dialog({
		className: 'notice',
		content: `<p>${notice_icon(status)}${message}</p>`
	});
}

Notice.Error = NOTICE_ERROR;
Notice.Warning = NOTICE_WARNING;
Notice.Message = NOTICE_MESSAGE;
<commit_msg>fix dialog content<commit_after>import {EventEmitter} from 'events';

import is_function from 'lodash.isfunction';
import is_nil from 'lodash.isnil';
import is_string from 'lodash.isstring';
import cond from 'lodash.cond';
import constant from 'lodash.constant';
import noop from 'lodash.noop';
import uniq from 'lodash.uniq';

function overlay(parent) {
	let overlay = parent.querySelector('body > #modal-overlay');
	if (is_nil(overlay)) {
		overlay = document.createElement('div');
		overlay.id = 'modal-overlay';
		parent.appendChild(overlay);
	}
	return overlay;
}

function dialog_button(parent, role, label = '') {
	const item = document.createElement('li');
	const button = document.createElement('button');

	button.dataset.role = role;
	button.innerHTML = label;

	item.appendChild(button);
	parent.appendChild(item);

	return button;
}

function dialog_init_buttons(parent, buttons_descriptors) {
	const buttons_wrapper = document.createElement('ul');
	const emitter = new EventEmitter();

	parent.appendChild(buttons_wrapper);
	buttons_wrapper.className = 'buttons-wrapper';
	buttons_descriptors.forEach(({role, label}) => {
		const button = dialog_button(buttons_wrapper, role, label);
		const on_click = () => {
			emitter.emit('click', role);
			button.removeEventListener('click', on_click);
		}
		button.addEventListener('click', on_click);
	});

	return emitter;
}

function dialog_init_content(parent, content) {
	const content_wrapper = document.createElement('div');
	content_wrapper.className = 'content-wrapper';
	if (is_string(content)) {
		content_wrapper.innerHTML = content;
	} else {
		content_wrapper.appendChild(content);
	}
	parent.appendChild(content_wrapper);
	return content_wrapper;
}

export function Dialog({
	aboutToClose = noop,
	className = [],
	content,
	id = ''
} = {}) {
	const parent = document.querySelector('body');
	const dialog = document.createElement('div');

	dialog_init_content(dialog, content);
	const buttons_ = dialog_init_buttons(dialog, [{role: 'cancel', label: 'Cancel'}, {role: 'ok', label: 'Ok'}]);

	dialog.className = uniq([].concat(className, 'dialog')).join(' ');
	dialog.id = id;

	return {
		set aboutToClose(fn) {
			if (is_function(fn)) {
				aboutToClose = fn;
				return ;
			}
			throw new TypeError('argument must be a function');
		},
		run() {
			const terminate = () => {
				parent.removeChild(overlay(parent));
				parent.removeChild(dialog);
			};
			overlay(parent);
			parent.appendChild(dialog);
			dialog.style.left = `${(window.innerWidth - dialog.clientWidth)/2}px`;
			dialog.style.top = `${(window.innerHeight - dialog.clientHeight)/2}px`;
			return new Promise((resolve, reject) => {
				try {
					buttons_.once('click', action => {
						terminate();
						resolve(aboutToClose(action));
					});
				} catch (err) {
					terminate();
					reject(err);
				}
			});
		}
	};
}

export function Prompt(placeholder = '') {
	const input = document.createElement('input');

	input.type = 'text';
	input.placeholder = placeholder;

	return Dialog({
		aboutToClose: (role) => {
			if (role === 'ok') {
				return input.value;
			}
		},
		className: 'prompt',
		content: input
	});
}

export function Confirm(message) {
	return Dialog({
		aboutToClose: (role) => {
			return role === 'ok';
		},
		className: 'confirm',
		content: `<p>${message}</p>`
	});
}

const NOTICE_MESSAGE = 0;
const NOTICE_WARNING = 1;
const NOTICE_ERROR = 2;

const notice_icon = cond([
	[status => status === NOTICE_WARNING, constant('')],
	[status => status === NOTICE_ERROR,   constant('')],
	[constant(true), constant('')]
]);

export function Notice(message, status = NOTICE_MESSAGE) {
	return Dialog({
		className: 'notice',
		content: `<p>${notice_icon(status)}${message}</p>`
	});
}

Notice.Error = NOTICE_ERROR;
Notice.Warning = NOTICE_WARNING;
Notice.Message = NOTICE_MESSAGE;
<|endoftext|>


<commit_before>'use strict';

// This file contains needed polyfills mainly for IE11

// IE11 does not support Set with constructing arguments. May 2017.
var checkSetSupport = function() {
    var setTest = new window.Set(['test']);
    var hasConstructorParameterSupport = setTest.has('test');

    if (!hasConstructorParameterSupport) {
        var nativeSetConstructor = window.Set;
        window.Set = function(init) {
            var set = new nativeSetConstructor();
            if (init) {
                for (var i = 0; i < init.length; ++i) {
                    set.add(init[i]);
                }
            }
            return set;
        };
    }
};

checkSetSupport();

var checkTypedArraySlice = function() {
    if (!Float32Array.prototype.slice) {
        var slicePolyfill = function(start, end) {
            return new this.constructor(this.subarray(start, end));
        };

        Int8Array.prototype.slice = slicePolyfill;
        Uint8Array.prototype.slice = slicePolyfill;
        Uint8ClampedArray.prototype.slice = slicePolyfill;
        Int16Array.prototype.slice = slicePolyfill;
        Uint16Array.prototype.slice = slicePolyfill;
        Int32Array.prototype.slice = slicePolyfill;
        Uint32Array.prototype.slice = slicePolyfill;
        Float32Array.prototype.slice = slicePolyfill;
        Float64Array.prototype.slice = slicePolyfill;
    }
};

checkTypedArraySlice();
<commit_msg>Adds polyfill for old browsers<commit_after>'use strict';

// This file contains needed polyfills mainly for IE11
if (!Math.sign) {
    Math.sign = function(a) {
        return a > 0.0 ? 1.0 : a < 0.0 ? -1.0 : 0.0;
    };
}

if (!Math.log2) {
    Math.log2 = function(x) {
        return Math.log(x) * Math.LOG2E;
    };
}

if (!Math.log10) {
    Math.log10 = function(x) {
        return Math.log(x) * Math.LOG10E;
    };
}

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(str) {
        return this.slice(-str.length) === str;
    };
}

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(str) {
        return this.slice(0, str.length) === str;
    };
}

if (!Float32Array.prototype.slice) {
    var _slicePolyfill = function(start, end) {
        return new this.constructor(this.subarray(start, end));
    };

    Int8Array.prototype.slice = _slicePolyfill;
    Uint8Array.prototype.slice = _slicePolyfill;
    Uint8ClampedArray.prototype.slice = _slicePolyfill;
    Int16Array.prototype.slice = _slicePolyfill;
    Uint16Array.prototype.slice = _slicePolyfill;
    Int32Array.prototype.slice = _slicePolyfill;
    Uint32Array.prototype.slice = _slicePolyfill;
    Float32Array.prototype.slice = _slicePolyfill;
    Float64Array.prototype.slice = _slicePolyfill;
}

// IE11 does not support Set with constructing arguments. May 2017.
(function() {
    var setTest = new window.Set(['test']);
    var hasConstructorParameterSupport = setTest.has('test');
    if (hasConstructorParameterSupport) return;

    var nativeSetConstructor = window.Set;
    window.Set = function(init) {
        var set = new nativeSetConstructor();
        if (init) {
            for (var i = 0; i < init.length; ++i) {
                set.add(init[i]);
            }
        }
        return set;
    };
})();
<|endoftext|>


<commit_before>/*
 * grunt-componentize
 * https://github.com/fortyau/grunt-componentize
 *
 * Copyright (c) 2015 duane
 * Licensed under the MIT license.
 */

'use strict';

// This is dumb
var DEV_MODE = true;

// DEPENDENCIES ========================================================================================================
var colors = require('colors');
var path = require('path');
var _ = require('lodash');
var jju = require('jju');
var toSource = require('tosource');
var execSync = require('child_process').execSync;

// CONSTANTS/DEFAULTS ==================================================================================================
var MODULE_NAME = 'componentize';
var TEMPLATE_PATH = path.join(__dirname, 'component.tpl.ejs');
var BOWER_PATH = !DEV_MODE ? path.resolve('bower.json') : path.join(__dirname, '../test/fixtures/bower.json');
var BOWER_INFO_CMD = 'bower info {name}#{ver}';
var HOST_URL = 'http://localhost:9000';
var JS_PATH = '/scripts/vendor';
var CSS_PATH = '/styles/vendor';
var ASSET_TYPES = ['js', 'css'];
var DICTIONARY = '';
var SERIALIZERS = {
    'jju': function jjuSerializer(obj, serializerOptions) {
        return _.isUndefined(obj) ? 'undefined' : jju.stringify(obj, serializerOptions);
    },
    'json': function jsonSerializer(obj, serializerOptions) {
        return _.isUndefined(obj) ? 'undefined' : JSON.stringify(obj, serializerOptions.replacer, serializerOptions.space);
    },
    'source': function sourceSerializer(obj, serializerOptions) {
        return toSource(obj, serializerOptions.filter, serializerOptions.indent, serializerOptions.startingIndent);
    }
};

// PRIVATE FUNCTIONS ===================================================================================================
/**
 * Lookup the info for a package in the bower repository!
 * @param pkg_name
 * @returns {*}
 */
var getBowerInfo = function(pkg_name, pkg_ver){

    var pkg_info = null;
    var dep_type = null;
    var cmd = BOWER_INFO_CMD.replace("{name}", pkg_name).replace("{ver}", pkg_ver) + ' --json';

    try {
        var response = execSync(cmd, {stdio: [null]});

        pkg_info = JSON.parse(response.toString());

        if(pkg_info && _.size(pkg_info) > 0){
            console.info('      - Fetched info for '.green + pkg_name.bold.green + ' from Bower'.grey);
        }else{
            console.warn('      ^ Could not fetch info for '.grey + pkg_name.red.bold);
        }
    }
    catch (err) {
        console.warn('      ^ Could not fetch info for '.grey + pkg_name.red.bold);
    }

    return pkg_info;
};

/**
 * Capitalize a string
 * @param str
 * @returns {string}
 */
var cap = function(str){
    return str.charAt(0).toUpperCase() + str.slice(1);
};

// THE TASK ============================================================================================================

module.exports = function(grunt) {

  var defaultTemplate = grunt.file.read(TEMPLATE_PATH);
  grunt.template.addDelimiters(MODULE_NAME, '{%', '%}');  // Add delimiters that do not conflict with grunt

  function resolveSerializer(key) {
    var serializer = SERIALIZERS[key] || key;
    if (!_.isFunction(serializer)) {
        grunt.fail.warn('Invalid serializer. Serializer needs to be a function.');
    }
    return serializer;
  }

  grunt.registerMultiTask(MODULE_NAME, 'The best Grunt plugin ever.', function() {

    console.log('**Beginning the componentize task!**'.black.bold.bgBlue);

    // LOCALS FOR THE TASK ---------------------------------------------------------------------------------------------
    // Get any options for this Grunt task
    console.info('Gathering configuration > '.bold.blue);
    console.info('  > Getting options from Grunt config'.cyan);

    /** The component object that we are creating **/
    var comp = this.options({
        name: 'fg_component',
        template: defaultTemplate,
        host_url: HOST_URL,
        js_path: JS_PATH,
        delimiters: MODULE_NAME,
        css_path: CSS_PATH,
        bower_path: BOWER_PATH,
        serializer: 'jju',
        serializerOptions: {
            indent: '',
            no_trailing_comma: true
        },
        deps: {
            js: [],
            css: [],
            unknown: []
        }
    });

    var transformData = function dataTransformer(data) {
      return _.map(data, function (value, name) {
          return {
              name: name,
              value: serializer.call(this, value, comp.serializerOptions, comp)
          };
      }, this);
    }.bind(this);

    var serializer = resolveSerializer(comp.serializer);
    //------------------------------------------------------------------------------------------------------------------

    // MODELS  ---------------------------------------------------------------------------------------------------------
    var dep_model = {
        name: undefined,
        version: undefined,
        src: undefined,
        type: undefined,
        bower_info: undefined,
        filename: undefined,
        verify_version: undefined,
        verify_presence: undefined,
        getFileName: function(){
            if(!this.filename) {
                if (typeof(this.bower_info.main) === Object && this.bower_info.main.length) {
                    if (this.bower_info.main.length === 1) {
                        this.filename = this.bower_info.main.length[0];
                    }
                } else {
                    this.filename = this.bower_info.main;
                }
            }

            var filename_arr = this.filename.split('/');
            this.filename = filename_arr[filename_arr.length-1].trim();

            return this.filename;
        },
        getSrc: function(){
            return comp.host_url + comp[this.type + '_path'] + '/' + this.getFileName();
        },
        getVersion: function(){
            if(!this.version){
                if(this.bower_info.version){
                    this.version = this.bower_info.version;
                }else{
                    console.warn('  ! Could not determine version for '.red + this.name.red.bold);
                }
            }
            return this.version;
        },
        isValid: function(){
            return !_.isEmpty(this.src) && !_.isEmpty(this.version) && !_.isEmpty(this.name);
        },
        getInfoFromBower: function(){
            this.bower_info = getBowerInfo(this.name, this.version);
            if(this.version === '*' && this.bower_info.hasOwnProperty('latest')){
                this.bower_info = this.bower_info.latest;
            }
            return this.bower_info;
        },
        fulfillRequirements: function(){
            console.log('  ! Fulfilling requirements for '.yellow + this.name.yellow.bold);
            if(!this.src){
                this.src = this.getSrc();
                console.info('     * ' + 'Determined src' + ' of '.grey + this.src.toString().bold.grey);
            }
            if(!this.version){
                this.version = this.bower_info.version;
                console.info('     * ' + 'Determined version' + ' of '.grey + this.src.toString().bold.grey);
            }
        }
    }; //---------------------------------------------------------------------------------------------------------------

    // Check if bower actually has any dependencies --------------------------------------------------------------------
    console.info('  > Reading the configured dependencies and bower.json file'.cyan);
    var bower = require(comp.bower_path);
    var bower_deps = {};

    console.info('  > Setting the name of the component object'.cyan);
    comp.name = bower.name;

    if(bower.hasOwnProperty('dependencies')){
        bower_deps = bower.dependencies;
        console.info('  > Found '.green + _.size(bower_deps).toString().green + ' dependency(ies) from bower.json'.green);
    }else{
        console.info('  ! Found 0 dependencies in bower.json'.red);
    } //----------------------------------------------------------------------------------------------------------------

    // Determine where those bower dependencies should go...------------------------------------------------------------
    if(_.size(bower_deps) > 0){
        console.info('  > Determining dependency types of each bower component'.yellow);

        // The dependency type could be specifically declared in the configuration
        _.forEach(bower_deps, function(ver, name){
            console.info('    * Resolving dependency'.grey.bold + ' type for: '.grey + name.bold + '#'.grey + ver +'');

            var dep_is_placed = false;  // Ugly switch

            // Loop through the asset types and see if we have one that belongs to both
            // If we do have one like that...then it will get added in both places, if
            // we can't find it anywhere then we will check against the bower repo
            _.forEach(ASSET_TYPES, function(type){
                var d_idx = _.findIndex(comp.deps[type], {name:name});

                if(d_idx >= 0){
                    dep_is_placed = true;   // Trigger the ugly switch
                    comp.deps[type][d_idx] = _.merge(comp.deps[type][d_idx], dep_model);
                    comp.deps[type][d_idx].type = type;
                }
                return;
            });

            if(dep_is_placed){
                return;
            }

            // Not placed - look up in bower
            console.warn('      ! Attempting to lookup type from the Bower repository...'.yellow);

            // "Instantiate" a dependency model object
            var dep = _.merge({
                name: name,
                version: ver
            }, dep_model);

            // Success!
            if(dep.getInfoFromBower()){
                if(!dep.bower_info.hasOwnProperty('main')){
                    console.warn('      ^ Could not determine the dependency type for '.grey + name.red.bold + ' (no main attribute)!'.grey);
                    return;
                }

                // If the string is empty, arr is empty, etc
                if(_.size(dep.bower_info.main) === 0){
                    console.warn('      ^ Could not determine the dependency type for '.grey + name.red.bold + ' (multiple main values)!'.grey);
                    return;
                }

                dep.filename = null;

                // If its an array with a single entry then extract
                if(typeof(dep.bower_info.main)===Object && dep.bower_info.main.length){
                    if(dep.bower_info.main.length === 1){
                        dep.filename = dep.bower_info.main.length[0];
                    }
                }else{
                    dep.filename = dep.bower_info.main;
                }

                if(dep.filename && dep.filename.indexOf('.') >= 0){
                    var dep_type = dep.filename.split('.').pop().toLowerCase().trim();
                    dep.type = dep_type;
                    comp.deps[dep_type].push(dep);
                    console.info('      - Resolved '.green + name.bold.green + ' as '.grey + dep_type.toUpperCase().bold.green + ' from Bower'.grey);

                }else{
                    comp.deps['unknown'].push(dep);
                    console.warn('      ^ Could not determine the dependency type for '.grey + name.red.bold);
                }
            }

          return;
        });
    }//-----------------------------------------------------------------------------------------------------------------

    console.info('  > Checking dependency validity'.cyan);
    _.forEach(comp.deps, function(dep, dep_type){
        if(dep_type==='unknown'){
            return;
        }

        _.forEach(dep, function(d, i){

            if(d.isValid()){
            }else{
                comp.deps[dep_type][i].fulfillRequirements();
            }

        });

        console.info('All '.green + dep_type.toUpperCase().green.bold + ' dependencies are done!'.green);
    });

    // Write the file to where we need to! -----------------------------------------------------------------------------
    console.dir(comp);
    var result = grunt.template.process(comp.template, {
      data: _.extend({}, comp, {
          moduleName: comp.name,
          deps: comp.deps
      }),
      delimiters: comp.delimiters
    });

    grunt.file.write(path.join(__dirname, '../test/tmp/component.js'), result);

    console.info('Woot!'.green);
    if(comp.deps.unknown && comp.deps.unknown.length > 0){
        console.warn('We could not resolve '.red.bold + comp.deps.unknown.length.toString().red.bold + ' dependencies!'.red.bold);
    }
  });

};
<commit_msg>Add support for path<commit_after>/*
 * grunt-componentize
 * https://github.com/fortyau/grunt-componentize
 *
 * Copyright (c) 2015 duane
 * Licensed under the MIT license.
 */

'use strict';

// This is dumb
var DEV_MODE = true;

// DEPENDENCIES ========================================================================================================
var colors = require('colors');
var path = require('path');
var _ = require('lodash');
var jju = require('jju');
var toSource = require('tosource');
var execSync = require('child_process').execSync;

// CONSTANTS/DEFAULTS ==================================================================================================
var MODULE_NAME = 'componentize';
var TEMPLATE_PATH = path.join(__dirname, 'component.tpl.ejs');
var BOWER_PATH = !DEV_MODE ? path.resolve('bower.json') : path.join(__dirname, '../test/fixtures/bower.json');
var BOWER_INFO_CMD = 'bower info {name}#{ver}';
var HOST_URL = 'http://localhost:9000';
var JS_PATH = '/scripts/vendor';
var CSS_PATH = '/styles/vendor';
var ASSET_TYPES = ['js', 'css'];
var DEFAULT_DEST_PATH = 'dist/componentize.js'
var DICTIONARY = '';
var SERIALIZERS = {
    'jju': function jjuSerializer(obj, serializerOptions) {
        return _.isUndefined(obj) ? 'undefined' : jju.stringify(obj, serializerOptions);
    },
    'json': function jsonSerializer(obj, serializerOptions) {
        return _.isUndefined(obj) ? 'undefined' : JSON.stringify(obj, serializerOptions.replacer, serializerOptions.space);
    },
    'source': function sourceSerializer(obj, serializerOptions) {
        return toSource(obj, serializerOptions.filter, serializerOptions.indent, serializerOptions.startingIndent);
    }
};

// PRIVATE FUNCTIONS ===================================================================================================
/**
 * Lookup the info for a package in the bower repository!
 * @param pkg_name
 * @returns {*}
 */
var getBowerInfo = function(pkg_name, pkg_ver){

    var pkg_info = null;
    var dep_type = null;
    var cmd = BOWER_INFO_CMD.replace("{name}", pkg_name).replace("{ver}", pkg_ver) + ' --json';

    try {
        var response = execSync(cmd, {stdio: [null]});

        pkg_info = JSON.parse(response.toString());

        if(pkg_info && _.size(pkg_info) > 0){
            console.info('      - Fetched info for '.green + pkg_name.bold.green + ' from Bower'.grey);
        }else{
            console.warn('      ^ Could not fetch info for '.grey + pkg_name.red.bold);
        }
    }
    catch (err) {
        console.warn('      ^ Could not fetch info for '.grey + pkg_name.red.bold);
    }

    return pkg_info;
};

/**
 * Capitalize a string
 * @param str
 * @returns {string}
 */
var cap = function(str){
    return str.charAt(0).toUpperCase() + str.slice(1);
};

// THE TASK ============================================================================================================

module.exports = function(grunt) {

  var defaultTemplate = grunt.file.read(TEMPLATE_PATH);
  grunt.template.addDelimiters(MODULE_NAME, '{%', '%}');  // Add delimiters that do not conflict with grunt

  function resolveSerializer(key) {
    var serializer = SERIALIZERS[key] || key;
    if (!_.isFunction(serializer)) {
        grunt.fail.warn('Invalid serializer. Serializer needs to be a function.');
    }
    return serializer;
  }

  grunt.registerMultiTask(MODULE_NAME, 'The best Grunt plugin ever.', function() {

    console.log('**Beginning the componentize task!**'.black.bold.bgBlue);

    // LOCALS FOR THE TASK ---------------------------------------------------------------------------------------------
    // Get any options for this Grunt task
    console.info('Gathering configuration > '.bold.blue);
    console.info('  > Getting options from Grunt config'.cyan);

    /** The component object that we are creating **/
    var comp = this.options({
        name: 'fg_component',
        dest_path: DEFAULT_DEST_PATH,
        template: defaultTemplate,
        host_url: HOST_URL,
        js_path: JS_PATH,
        delimiters: MODULE_NAME,
        css_path: CSS_PATH,
        bower_path: BOWER_PATH,
        serializer: 'jju',
        serializerOptions: {
            indent: '',
            no_trailing_comma: true
        },
        deps: {
            js: [],
            css: [],
            unknown: []
        }
    });

    var transformData = function dataTransformer(data) {
      return _.map(data, function (value, name) {
          return {
              name: name,
              value: serializer.call(this, value, comp.serializerOptions, comp)
          };
      }, this);
    }.bind(this);

    var serializer = resolveSerializer(comp.serializer);
    //------------------------------------------------------------------------------------------------------------------

    // MODELS  ---------------------------------------------------------------------------------------------------------
    var dep_model = {
        name: undefined,
        version: undefined,
        src: undefined,
        type: undefined,
        bower_info: undefined,
        filename: undefined,
        verify_version: undefined,
        verify_presence: undefined,
        getFileName: function(){
            if(!this.filename) {
                if (typeof(this.bower_info.main) === Object && this.bower_info.main.length) {
                    if (this.bower_info.main.length === 1) {
                        this.filename = this.bower_info.main.length[0];
                    }
                } else {
                    this.filename = this.bower_info.main;
                }
            }

            var filename_arr = this.filename.split('/');
            this.filename = filename_arr[filename_arr.length-1].trim();

            return this.filename;
        },
        getSrc: function(){
            return comp.host_url + comp[this.type + '_path'] + '/' + this.getFileName();
        },
        getVersion: function(){
            if(!this.version){
                if(this.bower_info.version){
                    this.version = this.bower_info.version;
                }else{
                    console.warn('  ! Could not determine version for '.red + this.name.red.bold);
                }
            }
            return this.version;
        },
        isValid: function(){
            return !_.isEmpty(this.src) && !_.isEmpty(this.version) && !_.isEmpty(this.name);
        },
        getInfoFromBower: function(){
            this.bower_info = getBowerInfo(this.name, this.version);
            if(this.version === '*' && this.bower_info.hasOwnProperty('latest')){
                this.bower_info = this.bower_info.latest;
            }
            return this.bower_info;
        },
        fulfillRequirements: function(){
            console.log('  ! Fulfilling requirements for '.yellow + this.name.yellow.bold);
            if(!this.src){
                this.src = this.getSrc();
                console.info('     * ' + 'Determined src' + ' of '.grey + this.src.toString().bold.grey);
            }
            if(!this.version){
                this.version = this.bower_info.version;
                console.info('     * ' + 'Determined version' + ' of '.grey + this.src.toString().bold.grey);
            }
        }
    }; //---------------------------------------------------------------------------------------------------------------

    // Check if bower actually has any dependencies --------------------------------------------------------------------
    console.info('  > Reading the configured dependencies and bower.json file'.cyan);
    var bower = require(comp.bower_path);
    var bower_deps = {};

    console.info('  > Setting the name of the component object'.cyan);
    comp.name = bower.name;

    if(bower.hasOwnProperty('dependencies')){
        bower_deps = bower.dependencies;
        console.info('  > Found '.green + _.size(bower_deps).toString().green + ' dependency(ies) from bower.json'.green);
    }else{
        console.info('  ! Found 0 dependencies in bower.json'.red);
    } //----------------------------------------------------------------------------------------------------------------

    // Determine where those bower dependencies should go...------------------------------------------------------------
    if(_.size(bower_deps) > 0){
        console.info('  > Determining dependency types of each bower component'.yellow);

        // The dependency type could be specifically declared in the configuration
        _.forEach(bower_deps, function(ver, name){
            console.info('    * Resolving dependency'.grey.bold + ' type for: '.grey + name.bold + '#'.grey + ver +'');

            var dep_is_placed = false;  // Ugly switch

            // Loop through the asset types and see if we have one that belongs to both
            // If we do have one like that...then it will get added in both places, if
            // we can't find it anywhere then we will check against the bower repo
            _.forEach(ASSET_TYPES, function(type){
                var d_idx = _.findIndex(comp.deps[type], {name:name});

                if(d_idx >= 0){
                    dep_is_placed = true;   // Trigger the ugly switch
                    comp.deps[type][d_idx] = _.merge(comp.deps[type][d_idx], dep_model);
                    comp.deps[type][d_idx].type = type;
                }
                return;
            });

            if(dep_is_placed){
                return;
            }

            // Not placed - look up in bower
            console.warn('      ! Attempting to lookup type from the Bower repository...'.yellow);

            // "Instantiate" a dependency model object
            var dep = _.merge({
                name: name,
                version: ver
            }, dep_model);

            // Success!
            if(dep.getInfoFromBower()){
                if(!dep.bower_info.hasOwnProperty('main')){
                    console.warn('      ^ Could not determine the dependency type for '.grey + name.red.bold + ' (no main attribute)!'.grey);
                    return;
                }

                // If the string is empty, arr is empty, etc
                if(_.size(dep.bower_info.main) === 0){
                    console.warn('      ^ Could not determine the dependency type for '.grey + name.red.bold + ' (multiple main values)!'.grey);
                    return;
                }

                dep.filename = null;

                // If its an array with a single entry then extract
                if(typeof(dep.bower_info.main)===Object && dep.bower_info.main.length){
                    if(dep.bower_info.main.length === 1){
                        dep.filename = dep.bower_info.main.length[0];
                    }
                }else{
                    dep.filename = dep.bower_info.main;
                }

                if(dep.filename && dep.filename.indexOf('.') >= 0){
                    var dep_type = dep.filename.split('.').pop().toLowerCase().trim();
                    dep.type = dep_type;
                    comp.deps[dep_type].push(dep);
                    console.info('      - Resolved '.green + name.bold.green + ' as '.grey + dep_type.toUpperCase().bold.green + ' from Bower'.grey);

                }else{
                    comp.deps['unknown'].push(dep);
                    console.warn('      ^ Could not determine the dependency type for '.grey + name.red.bold);
                }
            }

          return;
        });
    }//-----------------------------------------------------------------------------------------------------------------

    console.info('  > Checking dependency validity'.cyan);
    _.forEach(comp.deps, function(dep, dep_type){
        if(dep_type==='unknown'){
            return;
        }

        _.forEach(dep, function(d, i){

            if(d.isValid()){
            }else{
                comp.deps[dep_type][i].fulfillRequirements();
            }

        });

        console.info('All '.green + dep_type.toUpperCase().green.bold + ' dependencies are done!'.green);
    });

    // Write the file to where we need to! -----------------------------------------------------------------------------
    console.dir(comp);
    var result = grunt.template.process(comp.template, {
      data: _.extend({}, comp, {
          moduleName: comp.name,
          deps: comp.deps
      }),
      delimiters: comp.delimiters
    });

    grunt.file.write(path.join(__dirname, comp.dest_path), result);

    console.info('Woot!'.green);
    if(comp.deps.unknown && comp.deps.unknown.length > 0){
        console.warn('We could not resolve '.red.bold + comp.deps.unknown.length.toString().red.bold + ' dependencies!'.red.bold);
    }
  });

};
<|endoftext|>


<commit_before>/*
 * grunt-angular-templates
 * https://github.com/ericclemmons/grunt-angular-templates
 *
 * Copyright (c) 2013 Eric Clemmons
 * Licensed under the MIT license.
 */

'use strict';

var minify  = require('html-minifier').minify;
var Url     = require('url');

/**
 * Angular Template Compiler
 * @param  {Object} grunt   Grunt global variable
 * @param  {Object} options Task options
 * @param  {String} cwd     Determines if paths are relative or not
 * @return {Object}
 */
var Compiler = function(grunt, options, cwd) {

  /**
   * Wrap individual cache registration script in bootstrap function
   *
   * @param  {String} script  Multiline string of `$templateCache.put(...)`
   * @return {String}         Final template aggregate script
   */
  this.bootstrap = function(module, script) {
    return options.bootstrap(module, script, options);
  };

  /**
   * Wrap HTML template in `$templateCache.put(...)`
   * @param  {String} template  Multiline HTML template string
   * @param  {String} url       URL to act as template ID
   * @return {String}           Template wrapped in `$templateCache.put(...)`
   */
  this.cache = function(template, url, prefix) {
    var path = prefix;

    // Force trailing slash
    if (path.length) {
      path = path.replace(/\/?$/, '/');
    }

    // Append formatted URL
    path += Url.format( Url.parse( url.replace(/\\/g, '/') ) );

    return "\n  $templateCache.put('" + path + "',\n    " + template + "\n  );\n";
  };

  /**
   * Convert list of files into Javascript that caches their contents
   * @param  {String} module  Module name
   * @param  {Array} files    List of files relative to `cwd`
   * @return {String}         Final template aggregate script
   */
  this.compile = function(module, files) {
    var paths = files.map(this.path).filter(function(path) {
      if (!grunt.file.exists(path)) {
        grunt.log.warn('Template "' + path + '" not found.');
        return false;
      }

      return true;
    });

    var script = "  'use strict';" + grunt.util.linefeed;

    script += paths
      .map(this.load)
      .map(this.minify)
      .map(function(source, i) {
        return this.customize(source, paths[i]);
      }.bind(this))
      .map(this.stringify)
      .map(function(string, i) {
        return this.cache(string, this.url(files[i]), options.prefix);
      }.bind(this))
      .map(grunt.util.normalizelf)
      .join(grunt.util.linefeed)
    ;

    return this.bootstrap(module, script);
  };

  /**
   * Customize template source
   * @param  {String} source Possibly minified template source
   * @param  {String} path   Path to template file
   * @return {String}
   */
  this.customize = function(source, path) {
    if (typeof options.source === 'function') {
      return options.source(source, path, options);
    }

    return source;
  };

  /**
   * Load template path
   * @param  {String} path  Template path
   * @return {String}       Template source
   */
  this.load = function(path) {
    return grunt.file.read(path);
  };

  /**
   * Run template source through htmlmin
   * @param  {String} source  Template source
   * @return {String}         Minified template
   */
  this.minify = function(source) {
    if (options.htmlmin && Object.keys(options.htmlmin).length) {
      try {
        source = minify(source, options.htmlmin);
      } catch (err) {
        grunt.warn(err);
      }
    }

    return source;
  };

  /**
   * Get static or dynamic module name from file.
   * @param  {String} file  File name
   * @return {String}
   */
  this.module = function(file) {
    if (typeof options.module === 'function') {
      return options.module(file, options);
    }

    return options.module;
  };

  /**
   * Group files into individual modules
   * @param  {Array} files  Files
   * @return {Object}       Key/Value pair of module + files
   */
  this.modules = function(files) {
    var modules = {};

    files.forEach(function(file) {
      var module = this.module(file);

      if (!modules[module]) {
        modules[module] = [];
      }

      modules[module].push(file);
    }, this);

    return modules;
  };

  /**
   * Get path to template file on filesystem
   * @param  {String} file  Name of file relative to `cwd`
   * @return {String}       Template path
   */
  this.path = function(file) {
    if (cwd) {
      return cwd + '/' + file;
    }

    return file;
  };

  /**
   * Convert template source Javascript-friendly lines
   * @param  {String} source Template source
   * @return {String}
   */
  this.stringify = function(source) {
    return source.split(/^/gm).map(function(line) {
      return JSON.stringify(line);
    }).join(' +\n    ') || '""';
  };

  /**
   * Convert file name to URL
   * @param  {String} file  File name
   * @return {String}       URL
   */
  this.url = function(file) {
    if (typeof options.url === 'function') {
      return options.url(file, options);
    }

    return file;
  };

};

module.exports = Compiler;
<commit_msg>Output offending template at minification error<commit_after>/*
 * grunt-angular-templates
 * https://github.com/ericclemmons/grunt-angular-templates
 *
 * Copyright (c) 2013 Eric Clemmons
 * Licensed under the MIT license.
 */

'use strict';

var minify  = require('html-minifier').minify;
var Url     = require('url');

/**
 * Angular Template Compiler
 * @param  {Object} grunt   Grunt global variable
 * @param  {Object} options Task options
 * @param  {String} cwd     Determines if paths are relative or not
 * @return {Object}
 */
var Compiler = function(grunt, options, cwd) {

  /**
   * Wrap individual cache registration script in bootstrap function
   *
   * @param  {String} script  Multiline string of `$templateCache.put(...)`
   * @return {String}         Final template aggregate script
   */
  this.bootstrap = function(module, script) {
    return options.bootstrap(module, script, options);
  };

  /**
   * Wrap HTML template in `$templateCache.put(...)`
   * @param  {String} template  Multiline HTML template string
   * @param  {String} url       URL to act as template ID
   * @return {String}           Template wrapped in `$templateCache.put(...)`
   */
  this.cache = function(template, url, prefix) {
    var path = prefix;

    // Force trailing slash
    if (path.length) {
      path = path.replace(/\/?$/, '/');
    }

    // Append formatted URL
    path += Url.format( Url.parse( url.replace(/\\/g, '/') ) );

    return "\n  $templateCache.put('" + path + "',\n    " + template + "\n  );\n";
  };

  /**
   * Convert list of files into Javascript that caches their contents
   * @param  {String} module  Module name
   * @param  {Array} files    List of files relative to `cwd`
   * @return {String}         Final template aggregate script
   */
  this.compile = function(module, files) {
    var paths = files.map(this.path).filter(function(path) {
      if (!grunt.file.exists(path)) {
        grunt.log.warn('Template "' + path + '" not found.');
        return false;
      }

      return true;
    });

    var script = "  'use strict';" + grunt.util.linefeed;

    script += paths
      .map(this.load)
      .map(this.minify)
      .map(function(source, i) {
        return this.customize(source, paths[i]);
      }.bind(this))
      .map(this.stringify)
      .map(function(string, i) {
        return this.cache(string, this.url(files[i]), options.prefix);
      }.bind(this))
      .map(grunt.util.normalizelf)
      .join(grunt.util.linefeed)
    ;

    return this.bootstrap(module, script);
  };

  /**
   * Customize template source
   * @param  {String} source Possibly minified template source
   * @param  {String} path   Path to template file
   * @return {String}
   */
  this.customize = function(source, path) {
    if (typeof options.source === 'function') {
      return options.source(source, path, options);
    }

    return source;
  };

  /**
   * Load template path
   * @param  {String} path  Template path
   * @return {String}       Template source
   */
  this.load = function(path) {
    return grunt.file.read(path);
  };

  /**
   * Run template source through htmlmin
   * @param  {String} source  Template source
   * @return {String}         Minified template
   */
  this.minify = function(source) {
    if (options.htmlmin && Object.keys(options.htmlmin).length) {
      try {
        source = minify(source, options.htmlmin);
      } catch (err) {
        grunt.warn(err + '\n\n' + source + '\n\n');
      }
    }

    return source;
  };

  /**
   * Get static or dynamic module name from file.
   * @param  {String} file  File name
   * @return {String}
   */
  this.module = function(file) {
    if (typeof options.module === 'function') {
      return options.module(file, options);
    }

    return options.module;
  };

  /**
   * Group files into individual modules
   * @param  {Array} files  Files
   * @return {Object}       Key/Value pair of module + files
   */
  this.modules = function(files) {
    var modules = {};

    files.forEach(function(file) {
      var module = this.module(file);

      if (!modules[module]) {
        modules[module] = [];
      }

      modules[module].push(file);
    }, this);

    return modules;
  };

  /**
   * Get path to template file on filesystem
   * @param  {String} file  Name of file relative to `cwd`
   * @return {String}       Template path
   */
  this.path = function(file) {
    if (cwd) {
      return cwd + '/' + file;
    }

    return file;
  };

  /**
   * Convert template source Javascript-friendly lines
   * @param  {String} source Template source
   * @return {String}
   */
  this.stringify = function(source) {
    return source.split(/^/gm).map(function(line) {
      return JSON.stringify(line);
    }).join(' +\n    ') || '""';
  };

  /**
   * Convert file name to URL
   * @param  {String} file  File name
   * @return {String}       URL
   */
  this.url = function(file) {
    if (typeof options.url === 'function') {
      return options.url(file, options);
    }

    return file;
  };

};

module.exports = Compiler;
<|endoftext|>


<commit_before>/*
 * grunt-sonar-runner
 * https://github.com/skhatri/grunt-sonar-runner
 *
 * Copyright (c) 2014 Suresh Khatri
 * Licensed under the MIT license.
 */

'use strict';

var childProcess = require('child_process'), format = require('util').format, os = require('os');

module.exports = function (grunt) {
    var SONAR_RUNNER_HOME = __dirname+'/../sonar-runner-2.3';

    var JAR = '/lib/sonar-runner-dist-2.3.jar';
    var SONAR_RUNNER_COMMAND = 'java -Xms256m -Xmx1024m -jar ' + SONAR_RUNNER_HOME + JAR+' -X -Drunner.home=' + SONAR_RUNNER_HOME;
    var LIST_CMD = (/^win/).test(os.platform()) ? 'dir '+SONAR_RUNNER_HOME + JAR : 'ls '+SONAR_RUNNER_HOME + JAR;

    var mergeOptions = function (prefix, effectiveOptions, obj) {
        for (var j in obj) {
            if (obj.hasOwnProperty(j)) {

                if (typeof obj[j] === 'object') {
                    mergeOptions(prefix + j + '.', effectiveOptions, obj[j]);
                } else {
                    effectiveOptions[prefix + j] = obj[j];
                }
            }
        }
    };
    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('sonarRunner', 'Sonar Analysis Runner from grunt', function () {
        var options = this.options({
            debug: false,
            separator: os.EOL,
            dryRun: false
        });
        var data = this.data;
        var callback = (typeof data.callback === 'function') ? data.callback : function () {
        };
        var dryRun = options.dryRun;
        var done = this.async();

        options.sonar.language = options.sonar.language || 'js';
        options.sonar.sourceEncoding = options.sonar.sourceEncoding || 'UTF-8';
        options.sonar.host = options.sonar.host || {url: 'http://localhost:9000'};

        var effectiveOptions = Object.create(null);
        mergeOptions('sonar.', effectiveOptions, options.sonar);

        var props = [];
        if (options.debug) {
            grunt.log.writeln('Effective Sonar Options');
            grunt.log.writeln('-----------------------');
        }
        for (var o in effectiveOptions) {
            var line = o + '=' + effectiveOptions[o];
            props.push(line);
            if (options.debug) {
                grunt.log.writeln(line);
            }
        }

        grunt.file.write(SONAR_RUNNER_HOME + '/conf/sonar-runner.properties', props.join(options.separator));
        if (options.debug) {
            grunt.log.writeln('Sonar client configured ');
        }

        var execCmd = dryRun ? LIST_CMD : SONAR_RUNNER_COMMAND;
        var exec = childProcess.exec(execCmd, callback);
        exec.stdout.on('data', function (c) {
            grunt.log.write(c);
        });
        exec.stderr.on('data', function (c) {
            grunt.log.error(c);
        });

        exec.on('exit', function (code) {
            if (code !== 0) {
                grunt.log.error(format('Return code: %d.', code));
                return done(false);
            }
            grunt.verbose.ok(format('Return code: %d.', code));
            done(true);
        });
    });

};
<commit_msg>Lower JVM memory parameters<commit_after>/*
 * grunt-sonar-runner
 * https://github.com/skhatri/grunt-sonar-runner
 *
 * Copyright (c) 2014 Suresh Khatri
 * Licensed under the MIT license.
 */

'use strict';

var childProcess = require('child_process'), format = require('util').format, os = require('os');

module.exports = function (grunt) {
    var SONAR_RUNNER_HOME = __dirname+'/../sonar-runner-2.3';

    var JAR = '/lib/sonar-runner-dist-2.3.jar';
    var SONAR_RUNNER_COMMAND = 'java -Xms128m -Xmx512m -jar ' + SONAR_RUNNER_HOME + JAR+' -X -Drunner.home=' + SONAR_RUNNER_HOME;
    var LIST_CMD = (/^win/).test(os.platform()) ? 'dir '+SONAR_RUNNER_HOME + JAR : 'ls '+SONAR_RUNNER_HOME + JAR;

    var mergeOptions = function (prefix, effectiveOptions, obj) {
        for (var j in obj) {
            if (obj.hasOwnProperty(j)) {

                if (typeof obj[j] === 'object') {
                    mergeOptions(prefix + j + '.', effectiveOptions, obj[j]);
                } else {
                    effectiveOptions[prefix + j] = obj[j];
                }
            }
        }
    };
    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('sonarRunner', 'Sonar Analysis Runner from grunt', function () {
        var options = this.options({
            debug: false,
            separator: os.EOL,
            dryRun: false
        });
        var data = this.data;
        var callback = (typeof data.callback === 'function') ? data.callback : function () {
        };
        var dryRun = options.dryRun;
        var done = this.async();

        options.sonar.language = options.sonar.language || 'js';
        options.sonar.sourceEncoding = options.sonar.sourceEncoding || 'UTF-8';
        options.sonar.host = options.sonar.host || {url: 'http://localhost:9000'};

        var effectiveOptions = Object.create(null);
        mergeOptions('sonar.', effectiveOptions, options.sonar);

        var props = [];
        if (options.debug) {
            grunt.log.writeln('Effective Sonar Options');
            grunt.log.writeln('-----------------------');
        }
        for (var o in effectiveOptions) {
            var line = o + '=' + effectiveOptions[o];
            props.push(line);
            if (options.debug) {
                grunt.log.writeln(line);
            }
        }

        grunt.file.write(SONAR_RUNNER_HOME + '/conf/sonar-runner.properties', props.join(options.separator));
        if (options.debug) {
            grunt.log.writeln('Sonar client configured ');
        }

        var execCmd = dryRun ? LIST_CMD : SONAR_RUNNER_COMMAND;
        var exec = childProcess.exec(execCmd, callback);
        exec.stdout.on('data', function (c) {
            grunt.log.write(c);
        });
        exec.stderr.on('data', function (c) {
            grunt.log.error(c);
        });

        exec.on('exit', function (code) {
            if (code !== 0) {
                grunt.log.error(format('Return code: %d.', code));
                return done(false);
            }
            grunt.verbose.ok(format('Return code: %d.', code));
            done(true);
        });
    });

};
<|endoftext|>


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

  var fs = require( 'fs' );
  var path = require( 'path' );
  var mkdirp = require( 'mkdirp' );

  grunt.registerMultiTask( 'appIcons', 'create app icons', function () {

    var done = this.async();
    var im = require( 'imagemagick' );

    var options = this.options( {
      type: [], // all, favicon, touch, ios, android
      createDirectories: false,
      precomposed: true,
      precomposedString: '-precomposed',
      args: []
    } );

    var remaining = this.files.length;

    this.files.forEach( function ( file ) {

      if ( options.type.length > 0 ) {

        var image = file.src[0];
        var folder = path.dirname( file.dest ) + '/' + path.basename( file.dest ) + '/';
        var folders = [folder];

        // Create path folders, if needed
        mkdirp(path.dirname( file.dest ), function ( error ) {
          grunt.log.error( error );
        });

        if ( options.type.indexOf( 'all' ) >= 0 ) {
          options.type = ['favicon', 'touch', 'ios', 'android']
        }

        if ( options.createDirectories ) {
          folders = [];
          options.type.forEach( function ( type ) {
            folders.push( folder + type + '/' );
          } );
        }

        var remainingTypes = options.type.length;
        var remainingFolders = folders.length;

        folders.forEach( function ( f ) {
          fs.mkdirParent( f, null, function () {
            if ( -- remainingFolders <= 0 ) {
              options.type.forEach( function ( type ) {
                if ( icons.hasOwnProperty( type ) ) {
                  var remainingIcons = icons[type].length;
                  icons[type].forEach( function ( iconOptions ) {
                    var iconFolder = folder;
                    if ( options.createDirectories ) {
                      iconFolder += type + '/';
                    }
                    var iconName = iconOptions.name;
                    if ( options.precomposed ) {
                      iconName = iconName.replace( /%precomposed%/g, options.precomposedString );
                    }
                    var iconArgs = iconOptions.args || [];
                    var taskArgs = options.args || [];
                    if ( typeof taskArgs === 'function' ) {
                      taskArgs = taskArgs( iconOptions.resize );
                    }
                    if ( iconOptions.resize ) {
                      iconArgs = ['-resize', iconOptions.resize].concat( iconArgs );
                      taskArgs = taskArgs.map( function( arg ) {
                        return arg.replace( /%size%/g, iconOptions.resize );
                      } );
                    }
                    var args = [image].concat( iconArgs ).concat( taskArgs ).concat( [iconFolder + iconName] );
                    im.convert( args, function ( error ) {
                      if ( error ) {
                        grunt.log.errorlns( error );
                      } else {
                        grunt.log.writeln( 'Created: ' + iconName );
                      }
                      if ( -- remainingIcons <= 0 ) {
                        if ( -- remainingTypes <= 0 ) {
                          if ( -- remaining <= 0 ) {
                            done();
                          }
                        }
                      }
                    } );
                  } );
                } else {
                  if ( -- remainingTypes <= 0 ) {
                    if ( -- remaining <= 0 ) {
                      done();
                    }
                  }
                }
              } );
            }
          } );
        } );

      } else {
        grunt.log.error( 'No type option specified, allowed: all, favicon, touch, ios, android' );
        if ( -- remaining <= 0 ) {
          done();
        }
      }

    } );

  } );

  var icons = {
    ios: [
      {name: 'icon-60.png', resize: '60x60'},
      {name: 'icon-60@2x.png', resize: '120x120'},
      {name: 'icon-60@3x.png', resize: '180x180'},
      {name: 'icon-76.png', resize: '76x76'},
      {name: 'icon-76@2x.png', resize: '152x152'},
      {name: 'icon-40.png', resize: '40x40'},
      {name: 'icon-40@2x.png', resize: '80x80'},
      {name: 'icon.png', resize: '57x57'},
      {name: 'icon@2x.png', resize: '114x114'},
      {name: 'icon-72.png', resize: '72x72'},
      {name: 'icon-72@2x.png', resize: '144x144'},
      {name: 'icon-small.png', resize: '29x29'},
      {name: 'icon-small@2x.png', resize: '58x58'},
      {name: 'icon-50.png', resize: '50x50'},
      {name: 'icon-50@2x.png', resize: '100x100'}
    ],
    android: [
      {name: 'icon-ldpi.png', resize: '36x36'},
      {name: 'icon-mdpi.png', resize: '48x48'},
      {name: 'icon-hdpi.png', resize: '72x72'},
      {name: 'icon-xhdpi.png', resize: '96x96'},
      {name: 'icon-xxhdpi.png', resize: '144x144'},
      {name: 'icon-xxxhdpi.png', resize: '192x192'}
    ],
    androidDirectories: [
      {name: 'drawable-ldpi/icon.png', resize: '36x36'},
      {name: 'drawable-mdpi/icon.png', resize: '48x48'},
      {name: 'drawable-hdpi/icon.png', resize: '72x72'},
      {name: 'drawable-xhdpi/icon.png', resize: '96x96'},
      {name: 'drawable-xxhdpi/icon.png', resize: '144x144'},
      {name: 'drawable-xxxhdpi/icon.png', resize: '192x192'}
    ],
    favicon: [
      {
        name: 'favicon.ico',
        args: [
          '(', '-clone', '0', '-resize', '16x16', ')',
          '(', '-clone', '0', '-resize', '32x32', ')',
          '(', '-clone', '0', '-resize', '48x48', ')',
          '(', '-clone', '0', '-resize', '64x64', ')',
          '-delete', '0',
          '-alpha', 'off',
          '-colors', '256'
        ]
      }
    ],
    touch: [
      {name: 'apple-touch-icon%precomposed%.png', resize: '57x57'},
      {name: 'apple-touch-icon-76x76%precomposed%.png', resize: '76x76'},
      {name: 'apple-touch-icon-120x120%precomposed%.png', resize: '120x120'},
      {name: 'apple-touch-icon-152x152%precomposed%.png', resize: '152x152'},
      {name: 'apple-touch-icon-180x180%precomposed%.png', resize: '180x180'},
      {name: 'touch-icon-128x128.png', resize: '128x128'},
      {name: 'touch-icon-192x192.png', resize: '192x192'}
    ]
  };

  fs.mkdirParent = function ( dirPath, mode, callback ) {
    fs.mkdir( dirPath, mode, function ( error ) {
      if ( error && error.errno === 34 ) {
        fs.mkdirParent( path.dirname( dirPath ), mode, callback );
        fs.mkdirParent( dirPath, mode, callback );
      }
      callback && callback( error );
    } );
  };

};
<commit_msg>Added iosStore, playStore, amazonStore icon types.<commit_after>module.exports = function ( grunt ) {
  'use strict';

  var fs = require( 'fs' );
  var path = require( 'path' );
  var mkdirp = require( 'mkdirp' );

  grunt.registerMultiTask( 'appIcons', 'create app icons', function () {

    var done = this.async();
    var im = require( 'imagemagick' );

    var options = this.options( {
      type: [], // all, favicon, touch, ios, android
      createDirectories: false,
      precomposed: true,
      precomposedString: '-precomposed',
      args: []
    } );

    var remaining = this.files.length;

    this.files.forEach( function ( file ) {

      if ( options.type.length > 0 ) {

        var image = file.src[0];
        var folder = path.dirname( file.dest ) + '/' + path.basename( file.dest ) + '/';
        var folders = [folder];

        // Create path folders, if needed
        mkdirp(path.dirname( file.dest ), function ( error ) {
          grunt.log.error( error );
        });

        if ( options.type.indexOf( 'all' ) >= 0 ) {
          options.type = ['favicon', 'touch', 'ios', 'android']
        }

        if ( options.createDirectories ) {
          folders = [];
          options.type.forEach( function ( type ) {
            folders.push( folder + type + '/' );
          } );
        }

        var remainingTypes = options.type.length;
        var remainingFolders = folders.length;

        folders.forEach( function ( f ) {
          fs.mkdirParent( f, null, function () {
            if ( -- remainingFolders <= 0 ) {
              options.type.forEach( function ( type ) {
                if ( icons.hasOwnProperty( type ) ) {
                  var remainingIcons = icons[type].length;
                  icons[type].forEach( function ( iconOptions ) {
                    var iconFolder = folder;
                    if ( options.createDirectories ) {
                      iconFolder += type + '/';
                    }
                    var iconName = iconOptions.name;
                    if ( options.precomposed ) {
                      iconName = iconName.replace( /%precomposed%/g, options.precomposedString );
                    }
                    var iconArgs = iconOptions.args || [];
                    var taskArgs = options.args || [];
                    if ( typeof taskArgs === 'function' ) {
                      taskArgs = taskArgs( iconOptions.resize );
                    }
                    if ( iconOptions.resize ) {
                      iconArgs = ['-resize', iconOptions.resize].concat( iconArgs );
                      taskArgs = taskArgs.map( function( arg ) {
                        return arg.replace( /%size%/g, iconOptions.resize );
                      } );
                    }
                    var args = [image].concat( iconArgs ).concat( taskArgs ).concat( [iconFolder + iconName] );
                    im.convert( args, function ( error ) {
                      if ( error ) {
                        grunt.log.errorlns( error );
                      } else {
                        grunt.log.writeln( 'Created: ' + iconName );
                      }
                      if ( -- remainingIcons <= 0 ) {
                        if ( -- remainingTypes <= 0 ) {
                          if ( -- remaining <= 0 ) {
                            done();
                          }
                        }
                      }
                    } );
                  } );
                } else {
                  if ( -- remainingTypes <= 0 ) {
                    if ( -- remaining <= 0 ) {
                      done();
                    }
                  }
                }
              } );
            }
          } );
        } );

      } else {
        grunt.log.error( 'No type option specified, allowed: all, favicon, touch, ios, android' );
        if ( -- remaining <= 0 ) {
          done();
        }
      }

    } );

  } );

  var icons = {
    ios: [
      {name: 'icon-60.png', resize: '60x60'},
      {name: 'icon-60@2x.png', resize: '120x120'},
      {name: 'icon-60@3x.png', resize: '180x180'},
      {name: 'icon-76.png', resize: '76x76'},
      {name: 'icon-76@2x.png', resize: '152x152'},
      {name: 'icon-40.png', resize: '40x40'},
      {name: 'icon-40@2x.png', resize: '80x80'},
      {name: 'icon.png', resize: '57x57'},
      {name: 'icon@2x.png', resize: '114x114'},
      {name: 'icon-72.png', resize: '72x72'},
      {name: 'icon-72@2x.png', resize: '144x144'},
      {name: 'icon-small.png', resize: '29x29'},
      {name: 'icon-small@2x.png', resize: '58x58'},
      {name: 'icon-50.png', resize: '50x50'},
      {name: 'icon-50@2x.png', resize: '100x100'}
    ],
    android: [
      {name: 'icon-ldpi.png', resize: '36x36'},
      {name: 'icon-mdpi.png', resize: '48x48'},
      {name: 'icon-hdpi.png', resize: '72x72'},
      {name: 'icon-xhdpi.png', resize: '96x96'},
      {name: 'icon-xxhdpi.png', resize: '144x144'},
      {name: 'icon-xxxhdpi.png', resize: '192x192'}
    ],
    androidDirectories: [
      {name: 'drawable-ldpi/icon.png', resize: '36x36'},
      {name: 'drawable-mdpi/icon.png', resize: '48x48'},
      {name: 'drawable-hdpi/icon.png', resize: '72x72'},
      {name: 'drawable-xhdpi/icon.png', resize: '96x96'},
      {name: 'drawable-xxhdpi/icon.png', resize: '144x144'},
      {name: 'drawable-xxxhdpi/icon.png', resize: '192x192'}
    ],
    iosStore: [
      {name: 'iTunesArtwork.png', resize: '512x512'},
      {name: 'iTunesArtwork@2x.png', resize: '1024x1024'}
    ],
    playStore: [
      {name: 'icon-google-play.png', resize: '512x512'}
    ],
    amazonStore: [
      {name: 'icon-amazon-small.png', resize: '114x114'},
      {name: 'icon-amazon-large.png', resize: '512x512'}
    ],
    favicon: [
      {
        name: 'favicon.ico',
        args: [
          '(', '-clone', '0', '-resize', '16x16', ')',
          '(', '-clone', '0', '-resize', '32x32', ')',
          '(', '-clone', '0', '-resize', '48x48', ')',
          '(', '-clone', '0', '-resize', '64x64', ')',
          '-delete', '0',
          '-alpha', 'off',
          '-colors', '256'
        ]
      }
    ],
    touch: [
      {name: 'apple-touch-icon%precomposed%.png', resize: '57x57'},
      {name: 'apple-touch-icon-76x76%precomposed%.png', resize: '76x76'},
      {name: 'apple-touch-icon-120x120%precomposed%.png', resize: '120x120'},
      {name: 'apple-touch-icon-152x152%precomposed%.png', resize: '152x152'},
      {name: 'apple-touch-icon-180x180%precomposed%.png', resize: '180x180'},
      {name: 'touch-icon-128x128.png', resize: '128x128'},
      {name: 'touch-icon-192x192.png', resize: '192x192'}
    ]
  };

  fs.mkdirParent = function ( dirPath, mode, callback ) {
    fs.mkdir( dirPath, mode, function ( error ) {
      if ( error && error.errno === 34 ) {
        fs.mkdirParent( path.dirname( dirPath ), mode, callback );
        fs.mkdirParent( dirPath, mode, callback );
      }
      callback && callback( error );
    } );
  };

};
<|endoftext|>


<commit_before>describe('Address Book', function() {
	var addressBook,
		thisContact;

	beforeEach(function() {
		addressBook = new AddressBook();
		thisContact = new Contact();
	});

	it('should be able to add a contact', function() {
		addressBook.addContact(thisContact);

		expect(addressBook.getContact(0)).toBe(thisContact);
	});

	it('should be able to delete a contact', function() {
		addressBook.addContact(thisContact);
		addressBook.deleteContact(0);

		expect(addressBook.getContact(0)).not.toBeDefined();
	});
});

describe('Async Address Book', function() {
	it('should grab initial contacts', function() {
		var addressBook = new AddressBook();

		addressBook.getInitialContacts();
		expect(addressBook.initialComplete).toBe(true);
	});
});<commit_msg>refactor async test suite<commit_after>describe('Address Book', function() {
	var addressBook,
		thisContact;

	beforeEach(function() {
		addressBook = new AddressBook();
		thisContact = new Contact();
	});

	it('should be able to add a contact', function() {
		addressBook.addContact(thisContact);

		expect(addressBook.getContact(0)).toBe(thisContact);
	});

	it('should be able to delete a contact', function() {
		addressBook.addContact(thisContact);
		addressBook.deleteContact(0);

		expect(addressBook.getContact(0)).not.toBeDefined();
	});
});

describe('Async Address Book', function() {
	var addressBook = new AddressBook();

	beforeEach(function(done) {
		addressBook.getInitialContacts(function() {
			done();
		});
	});

	it('should grab initial contacts', function() {
		expect(addressBook.initialComplete).toBe(true);
		done();
	});
});
<|endoftext|>