<commit_before>"use strict"

const config = require('config');
const moment = require('moment');
const _ = require('underscore');

const log = require("./helpers/logger");

const requestFactory = function(requestParameters){
    log.trace("Creating new request object");
    return new createRequestObject(requestParameters);
};

/**
 * Set defaults and overwrite with task values
 *
 * @param requestParameters
 */
const createRequestObject = function(requestParameters) {

    this.localObject = {};
    this.index = (requestParameters.index) ? requestParameters.index.toString() : undefined;
    this.start = config.has('start') ? config.get('start') : moment.utc().subtract(32, 'days').unix();
    this.end = config.has('end') ? config.get('end') : moment.utc().unix();
    this.analysis_type = requestParameters.analysis_type;
    this.target = requestParameters.target;
    this.threshold = requestParameters.threshold || 200;
    this.interval = requestParameters.interval;
    this.span = requestParameters.span || undefined;
    this.user = process.env.AUTH_USER || ( config.has('index.' + this.index + '.auth.username') ? config.get('index.' + this.index + '.auth.username') : (config.has('index.default.auth.username') ? config.get('index.default.auth.username') : ""));
    this.pass = process.env.AUTH_KEY || ( config.has('index.' + this.index + '.auth.api_key') ? config.get('index.' + this.index + '.auth.api_key') : (config.has('index.default.auth.api_key') ? config.get('index.default.auth.api_key') : ""));
    this.subscription_id = process.env.AUTH_KEY || (config.has('index.' + this.index + '.subscription_id') ? config.get('index.' + this.index + '.subscription_id') : (config.has('index.default.subscription_id') ? config.get('index.default.subscription_id') : ""));
    this.filter = requestParameters.filter || undefined;
    this.name = this.localObject.name = requestParameters.name;
    this.child = requestParameters.child || undefined;
    this.childTarget = (requestParameters.child) ? requestParameters.child.target : undefined;
    this.childThreshold = (requestParameters.child && requestParameters.child.threshold) ? requestParameters.child.threshold : 200;
    this.grandChild = requestParameters.grandChild || undefined;
    this.grandChildTarget = (requestParameters.grandChild) ? requestParameters.grandChild.target : undefined;
    this.grandChildThreshold = (requestParameters.grandChild && requestParameters.grandChild.threshold) ? requestParameters.grandChild.threshold : 200;

    if(requestParameters.then) {
        this.localObject.then = requestParameters.then;
    }

    if(requestParameters.cache) {
        this.localObject.cache = requestParameters.cache;
    }
};

/**
 * Create an /analyze request object
 *
 * @returns {}
 */
createRequestObject.prototype.analyze = function(){

    let params = { 'target': this.target, 'threshold': this.threshold };

    if(this.analysis_type === "timeSeries"){
        params = { 'interval': this.interval };
        if(this.span) params.span = this.span;
    }

    let returnObj = {
        'method': 'POST',
        'auth': {
            'user': this.user,
            'pass': this.pass,
        },
        'uri': "https://api.datasift.com/v1.3/pylon/analyze",
        'json': {
            'id': this.subscription_id,
            'start': this.start,
            'end': this.end,
            'parameters': {
                'analysis_type': this.analysis_type,
                'parameters': params
            }
        }
    };

    if(this.filter) {
        returnObj.json.filter = this.filter;
    }

    if(this.child) {
        returnObj.json.parameters.child = {
            'analysis_type': 'freqDist',
            'parameters': {
                'target': this.childTarget,
                'threshold': this.childThreshold
            }
        };
    }

    if(this.grandChild) {
        returnObj.json.parameters.child.child = {
            'analysis_type': 'freqDist',
            'parameters': {
                'target': this.grandChildTarget,
                'threshold': this.grandChildThreshold
            }
        };
    }

    return _.extend(returnObj, this.localObject);

};

createRequestObject.prototype.task = function(){
    return this.localObject;
};

module.exports.requestFactory = requestFactory;
<commit_msg>Cleanup.<commit_after>"use strict"

const config = require('config');
const moment = require('moment');
const _ = require('underscore');

const log = require("./helpers/logger");

const requestFactory = function(requestParameters){
    log.trace("Creating new request object");
    return new createRequestObject(requestParameters);
};

/**
 * Set defaults and overwrite with task values
 *
 * @param requestParameters
 */
const createRequestObject = function(requestParameters) {
    this.localObject = {};
    this.index = (requestParameters.index) ? requestParameters.index.toString() : undefined;
    this.start = config.has('start') ? config.get('start') : moment.utc().subtract(32, 'days').unix();
    this.end = config.has('end') ? config.get('end') : moment.utc().unix();
    this.analysis_type = requestParameters.analysis_type;
    this.target = requestParameters.target;
    this.threshold = requestParameters.threshold || 200;
    this.interval = requestParameters.interval;
    this.span = requestParameters.span || undefined;
    this.user = process.env.AUTH_USER || ( config.has('index.' + this.index + '.auth.username') ? config.get('index.' + this.index + '.auth.username') : (config.has('index.default.auth.username') ? config.get('index.default.auth.username') : ""));
    this.pass = process.env.AUTH_KEY || ( config.has('index.' + this.index + '.auth.api_key') ? config.get('index.' + this.index + '.auth.api_key') : (config.has('index.default.auth.api_key') ? config.get('index.default.auth.api_key') : ""));
    this.subscription_id = process.env.AUTH_KEY || (config.has('index.' + this.index + '.subscription_id') ? config.get('index.' + this.index + '.subscription_id') : (config.has('index.default.subscription_id') ? config.get('index.default.subscription_id') : ""));
    this.filter = requestParameters.filter || undefined;
    this.name = this.localObject.name = requestParameters.name;
    this.child = requestParameters.child || undefined;
    this.childTarget = (requestParameters.child) ? requestParameters.child.target : undefined;
    this.childThreshold = (requestParameters.child && requestParameters.child.threshold) ? requestParameters.child.threshold : 200;
    this.grandChild = requestParameters.grandChild || undefined;
    this.grandChildTarget = (requestParameters.grandChild) ? requestParameters.grandChild.target : undefined;
    this.grandChildThreshold = (requestParameters.grandChild && requestParameters.grandChild.threshold) ? requestParameters.grandChild.threshold : 200;

    if(requestParameters.then) {
        this.localObject.then = requestParameters.then;
    }

    if(requestParameters.cache) {
        this.localObject.cache = requestParameters.cache;
    }
};

/**
 * Create an /analyze request object
 *
 * @returns {}
 */
createRequestObject.prototype.analyze = function(){

    let params = { 'target': this.target, 'threshold': this.threshold };

    if(this.analysis_type === "timeSeries"){
        params = { 'interval': this.interval };
        if(this.span) params.span = this.span;
    }

    let returnObj = {
        'method': 'POST',
        'auth': {
            'user': this.user,
            'pass': this.pass,
        },
        'uri': "https://api.datasift.com/v1.3/pylon/analyze",
        'json': {
            'id': this.subscription_id,
            'start': this.start,
            'end': this.end,
            'parameters': {
                'analysis_type': this.analysis_type,
                'parameters': params
            }
        }
    };

    if(this.filter) {
        returnObj.json.filter = this.filter;
    }

    if(this.child) {
        returnObj.json.parameters.child = {
            'analysis_type': 'freqDist',
            'parameters': {
                'target': this.childTarget,
                'threshold': this.childThreshold
            }
        };
    }

    if(this.grandChild) {
        returnObj.json.parameters.child.child = {
            'analysis_type': 'freqDist',
            'parameters': {
                'target': this.grandChildTarget,
                'threshold': this.grandChildThreshold
            }
        };
    }

    return _.extend(returnObj, this.localObject);

};

createRequestObject.prototype.task = function(){
    return this.localObject;
};

module.exports.requestFactory = requestFactory;
<|endoftext|>


<commit_before>"use strict";
var responseHelper = module.exports = { };

var _ = require("underscore");
var async = require("async");
var pagination = require("./pagination.js");
var Joi = require("joi");
var debug = require("./debugging.js");

responseHelper.setBaseUrl = function(baseUrl) {
  responseHelper._baseUrl = baseUrl;
};
responseHelper.setMetadata = function(meta) {
  responseHelper._metadata = meta;
};

responseHelper._enforceSchemaOnArray = function(items, schema, callback) {
  if (!(items instanceof Array)) {
    items = [ items ];
  }
  async.map(items, function(item, done) {
    return responseHelper._enforceSchemaOnObject(item, schema, done);
  }, function(err, results) {
    if (err) return callback(err);

    results = results.filter(function(result) {
      return !!result;
    });
    return callback(null, results);
  });
};

responseHelper._enforceSchemaOnObject = function(item, schema, callback) {
  debug.validationOutput(JSON.stringify(item));
  Joi.validate(item, schema, function (err) {
    if (err) {
      console.log("Failed to validate internal object?!", JSON.stringify(arguments));
      return callback(null, null);
    }

    var dataItem = responseHelper._generateDataItem(item, schema);
    return callback(null, dataItem);
  });
};

responseHelper._generateDataItem = function(item, schema) {

  var isSpecialProperty = function(value) {
    if (!(value instanceof Object)) return false;
    if (value._settings) return true;
    return false;
  };
  var linkProperties = Object.keys(schema).filter(function(someProperty) {
    return isSpecialProperty(schema[someProperty]);
  });
  var attributeProperties = Object.keys(schema).filter(function(someProperty) {
    if (someProperty === "id") return false;
    if (someProperty === "type") return false;
    if (someProperty === "meta") return false;
    return !isSpecialProperty(schema[someProperty]);
  });

  var result = {
    type: item.type,
    id: item.id,
    attributes: _.pick(item, attributeProperties),
    links: responseHelper._generateLinks(item, schema, linkProperties),
    relationships: responseHelper._generateRelationships(item, schema, linkProperties),
    meta: item.meta
  };

  return result;
};

responseHelper._generateLinks = function(item) {
  return {
    self: responseHelper._baseUrl + item.type + "/" + item.id
  };
};

responseHelper._generateRelationships = function(item, schema, linkProperties) {
  if (linkProperties.length === 0) return undefined;

  var links = { };

  linkProperties.forEach(function(linkProperty) {
    links[linkProperty] = responseHelper._generateLink(item, schema[linkProperty], linkProperty);
  });

  return links;
};

responseHelper._generateLink = function(item, schemaProperty, linkProperty) {
  var link = {
    meta: {
      relation: "primary",
      // type: schemaProperty._settings.__many || schemaProperty._settings.__one,
      readOnly: false
    },
    links: {
      self: responseHelper._baseUrl + item.type + "/" + item.id + "/relationships/" + linkProperty,
      related: responseHelper._baseUrl + item.type + "/" + item.id + "/" + linkProperty
    },
    data: null
  };

  if (schemaProperty._settings.__many) {
    link.data = [ ];
    var linkItems = item[linkProperty];
    if (linkItems) {
      if (!(linkItems instanceof Array)) linkItems = [ linkItems ];
      linkItems.forEach(function(linkItem) {
        link.data.push({
          type: linkItem.type,
          id: linkItem.id,
          meta: linkItem.meta
        });
      });
    }
  }

  if (schemaProperty._settings.__one) {
    var linkItem = item[linkProperty];
    if (linkItem) {
      link.data = {
        type: linkItem.type,
        id: linkItem.id,
        meta: linkItem.meta
      };
    }
  }

  if (schemaProperty._settings.__as) {
    var relatedResource = schemaProperty._settings.__one || schemaProperty._settings.__many;
    // get information about the linkage - list of ids and types
    // /rest/bookings/relationships/?customer=26aa8a92-2845-4e40-999f-1fa006ec8c63
    link.links.self = responseHelper._baseUrl + relatedResource + "/relationships/?" + schemaProperty._settings.__as + "=" + item.id;
    // get full details of all linked resources
    // /rest/bookings/?relationships[customer]=26aa8a92-2845-4e40-999f-1fa006ec8c63
    link.links.related = responseHelper._baseUrl + relatedResource + "/?relationships[" + schemaProperty._settings.__as + "]=" + item.id;
    if (!item[linkProperty]) {
      link.data = undefined;
    }
    link.meta = {
      relation: "foreign",
      belongsTo: relatedResource,
      as: schemaProperty._settings.__as,
      many: !!schemaProperty._settings.__many,
      readOnly: true
    };
  }

  return link;
};

responseHelper.generateError = function(request, err) {
  debug.errors(responseHelper._baseUrl + request.route.path, err);
  if (!(err instanceof Array)) err = [ err ];

  var errorResponse = {
    jsonapi: {
      version: "1.0"
    },
    meta: responseHelper._generateMeta(request),
    links: {
      self: responseHelper._baseUrl + request.route.path
    },
    errors: err.map(function(error) {
      return {
        status: error.status,
        code: error.code,
        title: error.title,
        detail: error.detail
      };
    })
  };

  return errorResponse;
};

responseHelper._generateResponse = function(request, resourceConfig, sanitisedData, handlerTotal) {
  return {
    jsonapi: {
      version: "1.0"
    },
    meta: responseHelper._generateMeta(request, handlerTotal),
    links: _.extend({
      self: responseHelper._baseUrl + request.route.path + (request.route.query ? ("?" + request.route.query) : "")
    }, pagination.generatePageLinks(request, handlerTotal)),
    data: sanitisedData
  };
};

responseHelper._generateMeta = function(request, handlerTotal) {
  var meta = _.extend({ }, responseHelper._metadata);

  if (handlerTotal) {
    meta.page = pagination.generateMetaSummary(request, handlerTotal);
  }

  return meta;
};
<commit_msg>More helpful error debugging info<commit_after>"use strict";
var responseHelper = module.exports = { };

var _ = require("underscore");
var async = require("async");
var pagination = require("./pagination.js");
var Joi = require("joi");
var debug = require("./debugging.js");

responseHelper.setBaseUrl = function(baseUrl) {
  responseHelper._baseUrl = baseUrl;
};
responseHelper.setMetadata = function(meta) {
  responseHelper._metadata = meta;
};

responseHelper._enforceSchemaOnArray = function(items, schema, callback) {
  if (!(items instanceof Array)) {
    items = [ items ];
  }
  async.map(items, function(item, done) {
    return responseHelper._enforceSchemaOnObject(item, schema, done);
  }, function(err, results) {
    if (err) return callback(err);

    results = results.filter(function(result) {
      return !!result;
    });
    return callback(null, results);
  });
};

responseHelper._enforceSchemaOnObject = function(item, schema, callback) {
  debug.validationOutput(JSON.stringify(item));
  Joi.validate(item, schema, function (err) {
    if (err) {
      console.log("Failed to validate internal object?!", JSON.stringify(arguments));
      return callback(null, null);
    }

    var dataItem = responseHelper._generateDataItem(item, schema);
    return callback(null, dataItem);
  });
};

responseHelper._generateDataItem = function(item, schema) {

  var isSpecialProperty = function(value) {
    if (!(value instanceof Object)) return false;
    if (value._settings) return true;
    return false;
  };
  var linkProperties = Object.keys(schema).filter(function(someProperty) {
    return isSpecialProperty(schema[someProperty]);
  });
  var attributeProperties = Object.keys(schema).filter(function(someProperty) {
    if (someProperty === "id") return false;
    if (someProperty === "type") return false;
    if (someProperty === "meta") return false;
    return !isSpecialProperty(schema[someProperty]);
  });

  var result = {
    type: item.type,
    id: item.id,
    attributes: _.pick(item, attributeProperties),
    links: responseHelper._generateLinks(item, schema, linkProperties),
    relationships: responseHelper._generateRelationships(item, schema, linkProperties),
    meta: item.meta
  };

  return result;
};

responseHelper._generateLinks = function(item) {
  return {
    self: responseHelper._baseUrl + item.type + "/" + item.id
  };
};

responseHelper._generateRelationships = function(item, schema, linkProperties) {
  if (linkProperties.length === 0) return undefined;

  var links = { };

  linkProperties.forEach(function(linkProperty) {
    links[linkProperty] = responseHelper._generateLink(item, schema[linkProperty], linkProperty);
  });

  return links;
};

responseHelper._generateLink = function(item, schemaProperty, linkProperty) {
  var link = {
    meta: {
      relation: "primary",
      // type: schemaProperty._settings.__many || schemaProperty._settings.__one,
      readOnly: false
    },
    links: {
      self: responseHelper._baseUrl + item.type + "/" + item.id + "/relationships/" + linkProperty,
      related: responseHelper._baseUrl + item.type + "/" + item.id + "/" + linkProperty
    },
    data: null
  };

  if (schemaProperty._settings.__many) {
    link.data = [ ];
    var linkItems = item[linkProperty];
    if (linkItems) {
      if (!(linkItems instanceof Array)) linkItems = [ linkItems ];
      linkItems.forEach(function(linkItem) {
        link.data.push({
          type: linkItem.type,
          id: linkItem.id,
          meta: linkItem.meta
        });
      });
    }
  }

  if (schemaProperty._settings.__one) {
    var linkItem = item[linkProperty];
    if (linkItem) {
      link.data = {
        type: linkItem.type,
        id: linkItem.id,
        meta: linkItem.meta
      };
    }
  }

  if (schemaProperty._settings.__as) {
    var relatedResource = schemaProperty._settings.__one || schemaProperty._settings.__many;
    // get information about the linkage - list of ids and types
    // /rest/bookings/relationships/?customer=26aa8a92-2845-4e40-999f-1fa006ec8c63
    link.links.self = responseHelper._baseUrl + relatedResource + "/relationships/?" + schemaProperty._settings.__as + "=" + item.id;
    // get full details of all linked resources
    // /rest/bookings/?relationships[customer]=26aa8a92-2845-4e40-999f-1fa006ec8c63
    link.links.related = responseHelper._baseUrl + relatedResource + "/?relationships[" + schemaProperty._settings.__as + "]=" + item.id;
    if (!item[linkProperty]) {
      link.data = undefined;
    }
    link.meta = {
      relation: "foreign",
      belongsTo: relatedResource,
      as: schemaProperty._settings.__as,
      many: !!schemaProperty._settings.__many,
      readOnly: true
    };
  }

  return link;
};

responseHelper.generateError = function(request, err) {
  debug.errors(responseHelper._baseUrl + request.route.path, JSON.stringify(err));
  if (!(err instanceof Array)) err = [ err ];

  var errorResponse = {
    jsonapi: {
      version: "1.0"
    },
    meta: responseHelper._generateMeta(request),
    links: {
      self: responseHelper._baseUrl + request.route.path
    },
    errors: err.map(function(error) {
      return {
        status: error.status,
        code: error.code,
        title: error.title,
        detail: error.detail
      };
    })
  };

  return errorResponse;
};

responseHelper._generateResponse = function(request, resourceConfig, sanitisedData, handlerTotal) {
  return {
    jsonapi: {
      version: "1.0"
    },
    meta: responseHelper._generateMeta(request, handlerTotal),
    links: _.extend({
      self: responseHelper._baseUrl + request.route.path + (request.route.query ? ("?" + request.route.query) : "")
    }, pagination.generatePageLinks(request, handlerTotal)),
    data: sanitisedData
  };
};

responseHelper._generateMeta = function(request, handlerTotal) {
  var meta = _.extend({ }, responseHelper._metadata);

  if (handlerTotal) {
    meta.page = pagination.generateMetaSummary(request, handlerTotal);
  }

  return meta;
};
<|endoftext|>


<commit_before>var _ = require('underscore');

// Browsers to run on Sauce Labs platforms
var sauceBrowsers = _.reduce([
  ['firefox', 'latest'],
  ['firefox', '60'],
  ['firefox', '40'],
  // TODO: find a way to get testing on old Firefox to work. See
  // https://github.com/jashkenas/backbone/runs/4907194010?check_suite_focus=true
  // ['firefox', '11'],

  ['chrome', 'latest'],
  ['chrome', '60'],
  ['chrome', '40'],
  ['chrome', '26'],

  // latest Edge as well as pre-Blink versions
  ['microsoftedge', 'latest', 'Windows 11'],
  ['microsoftedge', '18', 'Windows 10'],
  ['microsoftedge', '13', 'Windows 10'],

  ['internet explorer', 'latest', 'Windows 10'],
  ['internet explorer', '10', 'Windows 8'],
  ['internet explorer', '9', 'Windows 7'],
  // Older versions of IE no longer supported by Sauce Labs

  ['safari', 'latest', 'macOS 12'],
  ['safari', '12', 'macOS 10.14'],
  ['safari', '11', 'macOS 10.13'],
  ['safari', '8', 'OS X 10.10'],

], function(memo, platform) {
  // internet explorer -> ie
  var label = platform[0].split(' ');
  if (label.length > 1) {
    label = _.invoke(label, 'charAt', 0);
  }
  label = (label.join('') + '_v' + platform[1]).replace(' ', '_').toUpperCase();
  memo[label] = _.pick({
    base: 'SauceLabs',
    browserName: platform[0],
    version: platform[1],
    platform: platform[2]
  }, Boolean);
  return memo;
}, {});

module.exports = function(config) {
  if ( !process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY ) {
    // eslint-disable-next-line no-console
    console.log('Sauce environments not set --- Skipping');
    return process.exit(0);
  }

  config.set({
    basePath: '',
    frameworks: ['qunit'],
    singleRun: true,
    browserDisconnectTimeout: 120000,
    browserDisconnectTolerance: 5,
    browserNoActivityTimeout: 240000,

    // list of files / patterns to load in the browser
    files: [
      'test/vendor/jquery.js',
      'test/vendor/json2.js',
      'test/vendor/underscore.js',
      'backbone.js',
      'test/setup/*.js',
      'test/*.js'
    ],

    // Number of sauce tests to start in parallel
    concurrency: 2,

    // test results reporter to use
    reporters: ['dots', 'saucelabs'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    sauceLabs: {
      build: 'GH #' + process.env.BUILD_NUMBER + ' (' + process.env.BUILD_ID + ')',
      startConnect: true,
      tunnelIdentifier: process.env.JOB_NUMBER,
      region: 'eu'
    },

    captureTimeout: 120000,
    customLaunchers: sauceBrowsers,

    // Browsers to launch, commented out to prevent karma from starting
    // too many concurrent browsers and timing sauce out.
    browsers: _.keys(sauceBrowsers)
  });
};
<commit_msg>Speed up Sauce testing (#4251 #4252)<commit_after>var _ = require('underscore');

// Browsers to run on Sauce Labs platforms
var sauceBrowsers = _.reduce([
  ['firefox', 'latest'],
  ['firefox', '60'],
  ['firefox', '40'],
  // TODO: find a way to get testing on old Firefox to work. See
  // https://github.com/jashkenas/backbone/runs/4907194010?check_suite_focus=true
  // ['firefox', '11'],

  ['chrome', 'latest'],
  ['chrome', '60'],
  ['chrome', '40'],
  ['chrome', '26'],

  // latest Edge as well as pre-Blink versions
  ['microsoftedge', 'latest', 'Windows 11'],
  ['microsoftedge', '18', 'Windows 10'],
  ['microsoftedge', '13', 'Windows 10'],

  ['internet explorer', 'latest', 'Windows 10'],
  ['internet explorer', '10', 'Windows 8'],
  ['internet explorer', '9', 'Windows 7'],
  // Older versions of IE no longer supported by Sauce Labs

  ['safari', 'latest', 'macOS 12'],
  ['safari', '12', 'macOS 10.14'],
  ['safari', '11', 'macOS 10.13'],
  ['safari', '8', 'OS X 10.10'],

], function(memo, platform) {
  // internet explorer -> ie
  var label = platform[0].split(' ');
  if (label.length > 1) {
    label = _.invoke(label, 'charAt', 0);
  }
  label = (label.join('') + '_v' + platform[1]).replace(' ', '_').toUpperCase();
  memo[label] = _.pick({
    base: 'SauceLabs',
    browserName: platform[0],
    version: platform[1],
    platform: platform[2]
  }, Boolean);
  return memo;
}, {});

module.exports = function(config) {
  if ( !process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY ) {
    // eslint-disable-next-line no-console
    console.log('Sauce environments not set --- Skipping');
    return process.exit(0);
  }

  config.set({
    basePath: '',
    frameworks: ['qunit'],
    singleRun: true,
    browserDisconnectTimeout: 60000,
    browserDisconnectTolerance: 2,
    browserNoActivityTimeout: 60000,

    // list of files / patterns to load in the browser
    files: [
      'test/vendor/jquery.js',
      'test/vendor/json2.js',
      'test/vendor/underscore.js',
      'backbone.js',
      'test/setup/*.js',
      'test/*.js'
    ],

    // Number of sauce tests to start in parallel
    concurrency: 4,

    // test results reporter to use
    reporters: ['dots', 'saucelabs'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    sauceLabs: {
      build: 'GH #' + process.env.BUILD_NUMBER + ' (' + process.env.BUILD_ID + ')',
      startConnect: true,
      tunnelIdentifier: process.env.JOB_NUMBER,
      region: 'eu'
    },

    captureTimeout: 60000,
    customLaunchers: sauceBrowsers,

    // Browsers to launch, commented out to prevent karma from starting
    // too many concurrent browsers and timing sauce out.
    browsers: _.keys(sauceBrowsers)
  });
};
<|endoftext|>


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

// Browsers to run on Sauce Labs platforms
var sauceBrowsers = _.reduce([
  ['firefox', '35'],
  ['firefox', '30'],
  ['firefox', '21'],
  ['firefox', '11'],
  ['firefox', '4'],

  ['chrome', '40'],
  ['chrome', '39'],
  ['chrome', '31'],
  ['chrome', '26'],

  ['microsoftedge', '20', 'Windows 10'],
  ['internet explorer', '11', 'Windows 10'],
  ['internet explorer', '10', 'Windows 8'],
  ['internet explorer', '9', 'Windows 7'],
  ['internet explorer', '8'],
  ['internet explorer', '7', 'Windows XP'],
  // ['internet explorer', '6', 'Windows XP'],

  ['opera', '12'],
  ['opera', '11'],

  ['android', '5'],
  ['android', '4.4'],
  ['android', '4.3'],
  ['android', '4.0'],

  ['safari', '8.0', 'OS X 10.10'],
  ['safari', '7'],
  ['safari', '6'],
  ['safari', '5']
], function(memo, platform) {
  var label = (platform[0] + '_v' + platform[1]).replace(' ', '_').toUpperCase();
  memo[label] = _.pick({
    'base': 'SauceLabs',
    'browserName': platform[0],
    'version': platform[1],
    'platform': platform[2]
  }, Boolean);
  return memo;
}, {});

module.exports = function(config) {
  if ( !process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY ) {
    console.log('Sauce environments not set --- Skipping');
    return process.exit(0);
  }

  config.set({
    basePath: '',
    frameworks: ['qunit'],
    singleRun: true,

    // list of files / patterns to load in the browser
    files: [
      'test/vendor/qunit-extras.js',
      'underscore.js',
      'test/*.js'
    ],

    // Number of sauce tests to start in parallel
    concurrency: 2,

    // test results reporter to use
    reporters: ['dots', 'saucelabs'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    sauceLabs: {
      build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
      startConnect: true,
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
    },

    // TODO(vojta): remove once SauceLabs supports websockets.
    // This speeds up the capturing a bit, as browsers don't even try to use websocket.
    transports: ['xhr-polling'],
    captureTimeout: 120000,
    customLaunchers: sauceBrowsers

    // Browsers to launch, commented out to prevent karma from starting
    // too many concurrent browsers and timing sauce out.
    // browsers: _.keys(sauceBrowsers)
  });
};
<commit_msg>Fix karma sauce init for default browser case<commit_after>var _ = require('./');

// Browsers to run on Sauce Labs platforms
var sauceBrowsers = _.reduce([
  ['firefox', '35'],
  ['firefox', '30'],
  ['firefox', '21'],
  ['firefox', '11'],
  ['firefox', '4'],

  ['chrome', '40'],
  ['chrome', '39'],
  ['chrome', '31'],
  ['chrome', '26'],

  ['microsoftedge', '20.10240', 'Windows 10'],
  ['internet explorer', '11', 'Windows 10'],
  ['internet explorer', '10', 'Windows 8'],
  ['internet explorer', '9', 'Windows 7'],
  ['internet explorer', '8'],
  // Currently karma-sauce has issues with sockets and these browsers
  // ['internet explorer', '7'],
  // ['internet explorer', '6'],

  ['opera', '12'],
  ['opera', '11'],

  ['android', '5'],
  ['android', '4.4'],
  ['android', '4.3'],
  ['android', '4.0'],

  ['safari', '8.0', 'OS X 10.10'],
  ['safari', '7'],
  ['safari', '6'],
  ['safari', '5']
], function(memo, platform) {
  // internet explorer -> ie
  var label = platform[0].split(' ');
  if (label.length > 1) {
    label = _.invoke(label, 'charAt', 0)
  }
  label = (label.join("") + '_v' + platform[1]).replace(' ', '_').toUpperCase();
  memo[label] = _.pick({
    'base': 'SauceLabs',
    'browserName': platform[0],
    'version': platform[1],
    'platform': platform[2]
  }, Boolean);
  return memo;
}, {});

module.exports = function(config) {
  if ( !process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY ) {
    console.log('Sauce environments not set --- Skipping');
    return process.exit(0);
  }

  config.set({
    basePath: '',
    frameworks: ['qunit'],
    singleRun: true,

    // list of files / patterns to load in the browser
    files: [
      'test/vendor/qunit-extras.js',
      'underscore.js',
      'test/*.js'
    ],

    // Number of sauce tests to start in parallel
    concurrency: 9,

    // test results reporter to use
    reporters: ['dots', 'saucelabs'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    sauceLabs: {
      build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
      startConnect: true,
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
    },

    captureTimeout: 120000,
    customLaunchers: sauceBrowsers,

    // Browsers to launch, commented out to prevent karma from starting
    // too many concurrent browsers and timing sauce out.
    browsers: _.keys(sauceBrowsers)
  });
};
<|endoftext|>


<commit_before>$(document).ready(function(){
  SUGAR.util.doWhen("typeof $('#fieldTree').tree != 'undefined'", function(){
    var $moduleTree = $('#fieldTree').tree({
      data: {},
      dragAndDrop: false,
      selectable: false,
      onDragStop: function(node, e,thing){
//                    var target = $(document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset));
//                    if(node.type != 'field'){
//                        return;
//                    }
//                    if(target.closest('#fieldLines').length > 0){
//                        addNodeToFields(node);
//                        updateChartDimensionSelects();
//                    }else if(target.closest('#conditionLines').length > 0){
//                        addNodeToConditions(node);
//                    }

      },
      onCanMoveTo: function(){
        return false;
      }
    });

    function loadTreeData(module, node){
      var _node = node;
      $.getJSON('index.php',
        {
          'module' : 'AOR_Reports',
          'action' : 'getModuleTreeData',
          'aor_module' : module,
          'view' : 'JSON'
        },
        function(relData){
          processTreeData(relData, _node);
        }
      );
    }

    var treeDataLeafs = [];

    var dropFieldLine = function(node) {
      addNodeToFields(node);
      updateChartDimensionSelects();
    };

    var dropConditionLine = function(node) {
      var newConditionLine = addNodeToConditions(node);
      LogicalOperatorHandler.hideUnnecessaryLogicSelects();
      ConditionOrderHandler.setConditionOrders();
      ParenthesisHandler.addParenthesisLineIdent();
      return newConditionLine;
    };

    var showTreeDataLeafs = function(treeDataLeafs, module, module_name, module_path_display) {
      if (typeof module_name == 'undefined' || !module_name) {
        module_name = module;
      }
      if (typeof module_path_display == 'undefined' || !module_path_display) {
        module_path_display = module_name;
      }
      $('#module-name').html('(' + module_name + ')');
      $('#fieldTreeLeafs').remove();
      $('#detailpanel_fields_select').append(
        '

'
      );
      $('#fieldTreeLeafs').tree({
        data: treeDataLeafs,
        dragAndDrop: true,
        selectable: true,
        onCanSelectNode: function(node) {
          if($('#report-editview-footer .toggle-detailpanel_fields').hasClass('active')) {
            dropFieldLine(node);
          }
          else if($('#report-editview-footer .toggle-detailpanel_conditions').hasClass('active')) {
            dropConditionLine(node);
          }
        },
        onDragMove: function() {
          $('.drop-area').addClass('highlighted');
        },
        onDragStop: function(node, e,thing){
          $('.drop-area').removeClass('highlighted');
          var target = $(document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset));
          if(node.type != 'field'){
            return;
          }
          if(target.closest('#fieldLines').length > 0){
            dropFieldLine(node);
          }else if(target.closest('#aor_conditionLines').length > 0){
            var conditionLineTarget = ConditionOrderHandler.getConditionLineByPageEvent(e);
            var conditionLineNew = dropConditionLine(node);
            if(conditionLineTarget) {
              ConditionOrderHandler.putPositionedConditionLines(conditionLineTarget, conditionLineNew);
              ConditionOrderHandler.setConditionOrders();
            }
            ParenthesisHandler.addParenthesisLineIdent();
          }
          else if(target.closest('.tab-toggler').length > 0) {
            target.closest('.tab-toggler').click();
            if(target.closest('.tab-toggler').hasClass('toggle-detailpanel_fields')) {
              dropFieldLine(node);
            }
            else if (target.closest('.tab-toggler').hasClass('toggle-detailpanel_conditions')) {
              dropConditionLine(node);
            }
          }

        },
        onCanMoveTo: function(){
          return false;
        }
      });
    };

    function loadTreeLeafData(node){
      var module = node.module;
      var module_name = node.name;
      var module_path_display = node.module_path_display;

      if(!treeDataLeafs[module]) {
        $.getJSON('index.php',
          {
            'module': 'AOR_Reports',
            'action': 'getModuleFields',
            'aor_module': node.module,
            'view': 'JSON'
          },
          function (fieldData) {
            var treeData = [];

            for (var field in fieldData) {
              if (field) {
                treeData.push(
                  {
                    id: field,
                    label: fieldData[field],
                    'load_on_demand': false,
                    type: 'field',
                    module: node.module,
                    module_path: node.module_path,
                    module_path_display: node.module_path_display
                  });
              }
            }
            //$('#fieldTree').tree('loadData',treeData,node);
            //node.loaded = true;
            //$('#fieldTree').tree('openNode', node);
            treeDataLeafs[module] = treeData;
            showTreeDataLeafs(treeDataLeafs[module], module, module_name, module_path_display);
          }
        );
      }
      else {
        showTreeDataLeafs(treeDataLeafs[module], module, module_name, module_path_display);
      }
    }

    function processTreeData(relData, node){
      var treeData = [];

      for(var field in relData){
        // We don't want to show the parent module as child of itself
        if(node && node.module == relData[field]['module']){
          continue;
        }
        if(field) {
          var modulePath = '';
          var modulePathDisplay = '';
          if(relData[field]['type'] == 'relationship') {
            modulePath = field;
            if (node) {
              modulePath = node.module_path + ":" + field;
              modulePathDisplay = node.module_path_display + " : "+relData[field]['module_label'];
            }else{
              modulePathDisplay = $('#report_module option:selected').text() + ' : ' + relData[field]['module_label'];
            }
          }else{
            if (node) {
              modulePath = node.module_path;
              modulePathDisplay = node.module_path_display;
            }else{
              modulePathDisplay = relData[field]['module_label'];
            }
          }
          var newNode = {
            id: field,
            label: relData[field]['module_label'],
            load_on_demand : true,
            type: relData[field]['type'],
            module: relData[field]['module'],
            module_path: modulePath,
            module_path_display: modulePathDisplay};
          treeData.push(newNode);
        }
      }
      $('#fieldTree').tree('loadData',treeData, node);
      if(node){
        if(node.opened){
          $('#fieldTree').tree('openNode', node);
        }
        setNodeSelected(node);
        node.loaded = true;
      }
    }

    function setNodeSelected(node){
      $('.jqtree-selected').removeClass('jqtree-selected');
      $('#fieldTree').tree('addToSelection', node);
    }

    $('#fieldTree').on(
      'click',
      '.jqtree-toggler, .jqtree-title', //
      function(event) {
        var node = $(this).closest('li.jqtree_common').data('node');

        node.opened = !$(this).hasClass('jqtree-title');

        if(!node.loaded) {
          loadTreeData(node.module, node);
        }

        loadTreeLeafData(node);

        setNodeSelected(node);

        return true;
      }
    );

    var clearTreeDataFields = function() {
      $('#module-name').html('');
      $('#fieldTreeLeafs').html('');
    }

    $('#report_module').change(function(){
      report_module = $(this).val();
      loadTreeData($(this).val());
      clearTreeDataFields();
      clearFieldLines();
      clearConditionLines();
      clearChartLines();
    });

    $('#addChartButton').click(function(){
      loadChartLine({});
      updateChartDimensionSelects();

    });

    report_module = $('#report_module').val();
    loadTreeData($('#report_module').val());

    $.each(fieldLines,function(key,val){
      loadFieldLine(val);
    });
    $.each(conditionLines,function(key,val){
      loadConditionLine(val);
    });
    $.each(chartLines,function(key,val){
      loadChartLine(val);
    });
    updateChartDimensionSelects();
  });
});<commit_msg>Fixed #6037 - Reports: Fix adding relations from the first tree node<commit_after>$(document).ready(function(){
  SUGAR.util.doWhen("typeof $('#fieldTree').tree != 'undefined'", function(){
    var $moduleTree = $('#fieldTree').tree({
      data: {},
      dragAndDrop: false,
      selectable: false,
      onDragStop: function(node, e,thing){
//                    var target = $(document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset));
//                    if(node.type != 'field'){
//                        return;
//                    }
//                    if(target.closest('#fieldLines').length > 0){
//                        addNodeToFields(node);
//                        updateChartDimensionSelects();
//                    }else if(target.closest('#conditionLines').length > 0){
//                        addNodeToConditions(node);
//                    }

      },
      onCanMoveTo: function(){
        return false;
      }
    });

    function loadTreeData(module, node){
      var _node = node;
      $.getJSON('index.php',
        {
          'module' : 'AOR_Reports',
          'action' : 'getModuleTreeData',
          'aor_module' : module,
          'view' : 'JSON'
        },
        function(relData){
          processTreeData(relData, _node);
        }
      );
    }

    var treeDataLeafs = [];

    var dropFieldLine = function(node) {
      addNodeToFields(node);
      updateChartDimensionSelects();
    };

    var dropConditionLine = function(node) {
      var newConditionLine = addNodeToConditions(node);
      LogicalOperatorHandler.hideUnnecessaryLogicSelects();
      ConditionOrderHandler.setConditionOrders();
      ParenthesisHandler.addParenthesisLineIdent();
      return newConditionLine;
    };

    var showTreeDataLeafs = function(treeDataLeafs, module, module_name, module_path_display) {
      if (typeof module_name == 'undefined' || !module_name) {
        module_name = module;
      }
      if (typeof module_path_display == 'undefined' || !module_path_display) {
        module_path_display = module_name;
      }
      $('#module-name').html('(' + module_name + ')');
      $('#fieldTreeLeafs').remove();
      $('#detailpanel_fields_select').append(
        '

'
      );
      $('#fieldTreeLeafs').tree({
        data: treeDataLeafs,
        dragAndDrop: true,
        selectable: true,
        onCanSelectNode: function(node) {
          if($('#report-editview-footer .toggle-detailpanel_fields').hasClass('active')) {
            dropFieldLine(node);
          }
          else if($('#report-editview-footer .toggle-detailpanel_conditions').hasClass('active')) {
            dropConditionLine(node);
          }
        },
        onDragMove: function() {
          $('.drop-area').addClass('highlighted');
        },
        onDragStop: function(node, e,thing){
          $('.drop-area').removeClass('highlighted');
          var target = $(document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset));
          if(node.type != 'field'){
            return;
          }
          if(target.closest('#fieldLines').length > 0){
            dropFieldLine(node);
          }else if(target.closest('#aor_conditionLines').length > 0){
            var conditionLineTarget = ConditionOrderHandler.getConditionLineByPageEvent(e);
            var conditionLineNew = dropConditionLine(node);
            if(conditionLineTarget) {
              ConditionOrderHandler.putPositionedConditionLines(conditionLineTarget, conditionLineNew);
              ConditionOrderHandler.setConditionOrders();
            }
            ParenthesisHandler.addParenthesisLineIdent();
          }
          else if(target.closest('.tab-toggler').length > 0) {
            target.closest('.tab-toggler').click();
            if(target.closest('.tab-toggler').hasClass('toggle-detailpanel_fields')) {
              dropFieldLine(node);
            }
            else if (target.closest('.tab-toggler').hasClass('toggle-detailpanel_conditions')) {
              dropConditionLine(node);
            }
          }

        },
        onCanMoveTo: function(){
          return false;
        }
      });
    };

    function loadTreeLeafData(node){
      var module = node.module;
      var module_name = node.name;
      var module_path_display = node.module_path_display;

      if(!treeDataLeafs[module]) {
        $.getJSON('index.php',
          {
            'module': 'AOR_Reports',
            'action': 'getModuleFields',
            'aor_module': node.module,
            'view': 'JSON'
          },
          function (fieldData) {
            var treeData = [];

            for (var field in fieldData) {
              if (field) {
                treeData.push(
                  {
                    id: field,
                    label: fieldData[field],
                    'load_on_demand': false,
                    type: 'field',
                    module: node.module,
                    module_path: node.module_path,
                    module_path_display: node.module_path_display
                  });
              }
            }
            //$('#fieldTree').tree('loadData',treeData,node);
            //node.loaded = true;
            //$('#fieldTree').tree('openNode', node);
            treeDataLeafs[module] = treeData;
            showTreeDataLeafs(treeDataLeafs[module], module, module_name, module_path_display);
          }
        );
      }
      else {
        showTreeDataLeafs(treeDataLeafs[module], module, module_name, module_path_display);
      }
    }

    function processTreeData(relData, node){
      var treeData = [];

      for(var field in relData){
        // We don't want to show the parent module as child of itself
        if(node && node.module == relData[field]['module']){
          continue;
        }
        if(field) {
          var modulePath = '';
          var modulePathDisplay = '';
          if(relData[field]['type'] == 'relationship') {
            modulePath = field;
            if (node) {
              if (node.module_path) {
                modulePath = node.module_path + ":" + field;
              }
              modulePathDisplay = node.module_path_display + " : "+relData[field]['module_label'];
            }else{
              modulePathDisplay = $('#report_module option:selected').text() + ' : ' + relData[field]['module_label'];
            }
          }else{
            if (node) {
              modulePath = node.module_path;
              modulePathDisplay = node.module_path_display;
            }else{
              modulePathDisplay = relData[field]['module_label'];
            }
          }
          var newNode = {
            id: field,
            label: relData[field]['module_label'],
            load_on_demand : true,
            type: relData[field]['type'],
            module: relData[field]['module'],
            module_path: modulePath,
            module_path_display: modulePathDisplay};
          treeData.push(newNode);
        }
      }
      $('#fieldTree').tree('loadData',treeData, node);
      if(node){
        if(node.opened){
          $('#fieldTree').tree('openNode', node);
        }
        setNodeSelected(node);
        node.loaded = true;
      }
    }

    function setNodeSelected(node){
      $('.jqtree-selected').removeClass('jqtree-selected');
      $('#fieldTree').tree('addToSelection', node);
    }

    $('#fieldTree').on(
      'click',
      '.jqtree-toggler, .jqtree-title', //
      function(event) {
        var node = $(this).closest('li.jqtree_common').data('node');

        node.opened = !$(this).hasClass('jqtree-title');

        if(!node.loaded) {
          loadTreeData(node.module, node);
        }

        loadTreeLeafData(node);

        setNodeSelected(node);

        return true;
      }
    );

    var clearTreeDataFields = function() {
      $('#module-name').html('');
      $('#fieldTreeLeafs').html('');
    }

    $('#report_module').change(function(){
      report_module = $(this).val();
      loadTreeData($(this).val());
      clearTreeDataFields();
      clearFieldLines();
      clearConditionLines();
      clearChartLines();
    });

    $('#addChartButton').click(function(){
      loadChartLine({});
      updateChartDimensionSelects();

    });

    report_module = $('#report_module').val();
    loadTreeData($('#report_module').val());

    $.each(fieldLines,function(key,val){
      loadFieldLine(val);
    });
    $.each(conditionLines,function(key,val){
      loadConditionLine(val);
    });
    $.each(chartLines,function(key,val){
      loadChartLine(val);
    });
    updateChartDimensionSelects();
  });
});
<|endoftext|>


<commit_before>/*
 Copyright 2017 IBM Corp.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/* eslint-env mocha */

'use strict';

const helpers = require('yeoman-test');
const assert = require('yeoman-assert');
const path = require('path');

const scaffolderSample = require('./samples/scaffolder-sample');
const scaffolderSampleNode = scaffolderSample.getJson('NODE');
const scaffolderSampleSwift = scaffolderSample.getJson('SWIFT');
const scaffolderSampleJava = scaffolderSample.getJson('JAVA');
const scaffolderSampleSpring = scaffolderSample.getJson('SPRING');
const scaffolderSamplePython = scaffolderSample.getJson('PYTHON');

const applicationName = "AcmeProject"; // From all scaffolder samples

describe('cloud-enablement:dockertools', () => {

	before(function(){
		this.timeout(5000);
	});

	describe('cloud-enablement:dockertools with Swift project', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleSwift)});
		});

		it('create Dockerfile for running', () => {
			assert.file([
				'Dockerfile'
			]);
		});

		it('should have the executableName property set in Dockerfile', () => {
			assert.fileContent('Dockerfile', `CMD [ "sh", "-c", "cd /swift-project && .build-ubuntu/release/${applicationName}" ]`);
		});

		it('create Dockerfile-tools for compilation', () => {
			assert.file([
				'Dockerfile-tools'
			]);
		});

		it('create cli-config for CLI tool', () => {
			assert.file(['cli-config.yml']);
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
			assert.fileContent('cli-config.yml', 'run-cmd : ""');
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});

		it('should have the chart-path property set in cli-config.yml', () => {
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});
	});

	describe('cloud-enablement:dockertools with NodeJS project', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleNode)})
		});

		it('create Dockerfile for running', () => {
			assert.file(['Dockerfile', 'cli-config.yml', 'Dockerfile-tools']);
		});

		it('has correct default port', () => {
			assert.fileContent('cli-config.yml', '3000:3000');
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});

		it('should have the chart-path property set in cli-config.yml', () => {
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});
	});

	describe('cloud-enablement:dockertools with NodeJS project and storage', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleNode)})
		});

		it('create Dockerfile for running', () => {
			assert.file(['Dockerfile', 'cli-config.yml', 'Dockerfile-tools']);
		});

		it('has correct port', () => {
			assert.fileContent('cli-config.yml', '3000:3000');
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});

		it('should have the chart-path property set in cli-config.yml', () => {
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});
	});

	let buildTypes = ['maven', 'gradle'];
	let frameworks = ['liberty', 'spring'];
	buildTypes.forEach(buildType => {
		frameworks.forEach(framework => {
			describe('cloud-enablement:dockertools with Java project with buildType ' + buildType + ' and framework ' + framework, () => {
				let bluemixJson = framework === 'spring' ? scaffolderSampleSpring : scaffolderSampleJava;
				let options = {bluemix: JSON.stringify(bluemixJson), buildType: buildType, frameworkType: framework};
				beforeEach(() => {
					return helpers.run(path.join(__dirname, '../generators/app'))
						.inDir(path.join(__dirname, './tmp'))
						.withOptions(options)
				});

				it('create Dockerfile for running', () => {
					assert.file(['Dockerfile', 'cli-config.yml', 'Dockerfile-tools']);
				});

				it('create Dockerfile-tools for compilation', () => {
					assert.file('Dockerfile-tools');
				});

				it('create cli-config for CLI tool', () => {
					assert.file(['cli-config.yml']);
					assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
				});

				it('create dockerignore file', () => {
					assert.file([
						'.dockerignore'
					]);
				});
			});
		})
	})

	describe('cloud-enablement:dockertools with Java-liberty project with buildType maven with NO platforms', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleJava), platforms: [], buildType: 'maven', frameworkType: 'liberty'})
		});

		it('creates a Dockerfile and .dockerignore', () => {
			assert.file('Dockerfile');
			assert.file('.dockerignore');
		});

		it('does not create a Dockerfile-tools or cli-config.yml', () => {
			assert.noFile('Dockerfile-tools');
			assert.noFile('cli-config.yml');
		});
	});

	describe('cloud-enablement:dockertools with Java-liberty project with buildType maven with platforms including cli', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleJava), platforms: ['cli'], buildType: 'maven', frameworkType: 'liberty'})
		});

		it('creates all docker and cli files', () => {
			assert.file('Dockerfile');
			assert.file('.dockerignore');
			assert.file('Dockerfile-tools');
			assert.file('cli-config.yml');
		});
	});

	describe('cloud-enablement:dockertools with Python project', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSamplePython)})
		});

		it('create Dockerfile with gunicorn', () => {
			assert.file(['Dockerfile']);
			assert.fileContent('Dockerfile', 'gunicorn');
		});

		it('create Dockerfile-tools with flask', () => {
			assert.file(['Dockerfile-tools']);
		})

		it('create CLI-config file', () => {
			assert.file(['cli-config.yml']);
			assert.fileContent('cli-config.yml', 'flask run');
			assert.fileContent('cli-config.yml', 'acmeproject-flask-run');
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});
	});

	describe('cloud-enablement:dockertools with Python project and storage', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSamplePython)})
		});

		it('create Dockerfile with gunicorn', () => {
			assert.file(['Dockerfile']);
			assert.fileContent('Dockerfile', 'gunicorn');
		});

		it('create Dockerfile-tools with flask', () => {
			assert.file(['Dockerfile-tools']);
		})

		it('create CLI-config file', () => {
			assert.file(['cli-config.yml']);
			assert.fileContent('cli-config.yml', 'flask run');
			assert.fileContent('cli-config.yml', 'acmeproject-flask-run');
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});
	});
	describe('cloud-enablement:dockertools with empty bluemix object', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/dockertools'))
				.withOptions({ bluemix: '{"backendPlatform":"NODE"}' })
		});
		it('should give us the default output with no project name', () => {
			assert.file('Dockerfile');
			assert.fileContent('cli-config.yml', 'container-name-run : "app-express-run"');
		});
	});
});
<commit_msg>add javametrics tests<commit_after>/*
 Copyright 2017 IBM Corp.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/* eslint-env mocha */

'use strict';

const helpers = require('yeoman-test');
const assert = require('yeoman-assert');
const path = require('path');

const scaffolderSample = require('./samples/scaffolder-sample');
const scaffolderSampleNode = scaffolderSample.getJson('NODE');
const scaffolderSampleSwift = scaffolderSample.getJson('SWIFT');
const scaffolderSampleJava = scaffolderSample.getJson('JAVA');
const scaffolderSampleSpring = scaffolderSample.getJson('SPRING');
const scaffolderSamplePython = scaffolderSample.getJson('PYTHON');

const applicationName = "AcmeProject"; // From all scaffolder samples

describe('cloud-enablement:dockertools', () => {

	before(function(){
		this.timeout(5000);
	});

	describe('cloud-enablement:dockertools with Swift project', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleSwift)});
		});

		it('create Dockerfile for running', () => {
			assert.file([
				'Dockerfile'
			]);
		});

		it('should have the executableName property set in Dockerfile', () => {
			assert.fileContent('Dockerfile', `CMD [ "sh", "-c", "cd /swift-project && .build-ubuntu/release/${applicationName}" ]`);
		});

		it('create Dockerfile-tools for compilation', () => {
			assert.file([
				'Dockerfile-tools'
			]);
		});

		it('create cli-config for CLI tool', () => {
			assert.file(['cli-config.yml']);
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
			assert.fileContent('cli-config.yml', 'run-cmd : ""');
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});

		it('should have the chart-path property set in cli-config.yml', () => {
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});
	});

	describe('cloud-enablement:dockertools with NodeJS project', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleNode)})
		});

		it('create Dockerfile for running', () => {
			assert.file(['Dockerfile', 'cli-config.yml', 'Dockerfile-tools']);
		});

		it('has correct default port', () => {
			assert.fileContent('cli-config.yml', '3000:3000');
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});

		it('should have the chart-path property set in cli-config.yml', () => {
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});
	});

	describe('cloud-enablement:dockertools with NodeJS project and storage', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleNode)})
		});

		it('create Dockerfile for running', () => {
			assert.file(['Dockerfile', 'cli-config.yml', 'Dockerfile-tools']);
		});

		it('has correct port', () => {
			assert.fileContent('cli-config.yml', '3000:3000');
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});

		it('should have the chart-path property set in cli-config.yml', () => {
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});
	});

	let buildTypes = ['maven', 'gradle'];
	let frameworks = ['liberty', 'spring'];
	buildTypes.forEach(buildType => {
		frameworks.forEach(framework => {
			describe('cloud-enablement:dockertools with Java project with buildType ' + buildType + ' and framework ' + framework, () => {
				let bluemixJson = framework === 'spring' ? scaffolderSampleSpring : scaffolderSampleJava;
				let options = {bluemix: JSON.stringify(bluemixJson), buildType: buildType, frameworkType: framework};
				beforeEach(() => {
					return helpers.run(path.join(__dirname, '../generators/app'))
						.inDir(path.join(__dirname, './tmp'))
						.withOptions(options)
				});

				it('create Dockerfile for running', () => {
					assert.file(['Dockerfile', 'cli-config.yml', 'Dockerfile-tools']);
				});

				it('create Dockerfile-tools for compilation', () => {
					assert.file('Dockerfile-tools');
				});

				it('create cli-config for CLI tool', () => {
					assert.file(['cli-config.yml']);
					assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
				});

				it('create dockerignore file', () => {
					assert.file([
						'.dockerignore'
					]);
				});
			});
		})
	})

	describe('cloud-enablement:dockertools with Java-liberty project with buildType maven with NO platforms', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleJava), platforms: [], buildType: 'maven', frameworkType: 'liberty'})
		});

		it('creates a Dockerfile and .dockerignore', () => {
			assert.file('Dockerfile');
			assert.file('.dockerignore');
		});

		it('does not create a Dockerfile-tools or cli-config.yml', () => {
			assert.noFile('Dockerfile-tools');
			assert.noFile('cli-config.yml');
		});
	});

	describe('cloud-enablement:dockertools with Java-liberty project with buildType maven with platforms including cli', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleJava), platforms: ['cli'], buildType: 'maven', frameworkType: 'liberty'})
		});

		it('creates all docker and cli files', () => {
			assert.file('Dockerfile');
			assert.file('.dockerignore');
			assert.file('Dockerfile-tools');
			assert.file('cli-config.yml');
		});
	});

	describe('cloud-enablement:dockertools with Java-liberty project with buildType maven with javametrics enabled', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleJava), javametrics: true, buildType: 'maven', frameworkType: 'liberty'})
		});

		it('creates all docker with javametrics options', () => {
				assert.fileContent('Dockerfile','COPY /target/liberty/wlp/usr/shared/resources /config/resources/');
				assert.fileContent('Dockerfile','COPY /src/main/liberty/config/jvmbx.options /config/jvm.options');
		});
	});

	describe('cloud-enablement:dockertools with Java-liberty project with buildType maven with javametrics disabled', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSampleJava), javametrics: false, buildType: 'maven', frameworkType: 'liberty'})
		});

		it('creates all docker without javametrics options', () => {
				assert.noFileContent('Dockerfile','COPY /target/liberty/wlp/usr/shared/resources /config/resources/');
				assert.noFileContent('Dockerfile','COPY /src/main/liberty/config/jvmbx.options /config/jvm.options');
		});
	});

	describe('cloud-enablement:dockertools with Python project', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSamplePython)})
		});

		it('create Dockerfile with gunicorn', () => {
			assert.file(['Dockerfile']);
			assert.fileContent('Dockerfile', 'gunicorn');
		});

		it('create Dockerfile-tools with flask', () => {
			assert.file(['Dockerfile-tools']);
		})

		it('create CLI-config file', () => {
			assert.file(['cli-config.yml']);
			assert.fileContent('cli-config.yml', 'flask run');
			assert.fileContent('cli-config.yml', 'acmeproject-flask-run');
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});
	});

	describe('cloud-enablement:dockertools with Python project and storage', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/app'))
				.inDir(path.join(__dirname, './tmp'))
				.withOptions({bluemix: JSON.stringify(scaffolderSamplePython)})
		});

		it('create Dockerfile with gunicorn', () => {
			assert.file(['Dockerfile']);
			assert.fileContent('Dockerfile', 'gunicorn');
		});

		it('create Dockerfile-tools with flask', () => {
			assert.file(['Dockerfile-tools']);
		})

		it('create CLI-config file', () => {
			assert.file(['cli-config.yml']);
			assert.fileContent('cli-config.yml', 'flask run');
			assert.fileContent('cli-config.yml', 'acmeproject-flask-run');
			assert.fileContent('cli-config.yml', `chart-path : "chart/${applicationName.toLowerCase()}"`);
		});

		it('create dockerignore file', () => {
			assert.file([
				'.dockerignore'
			]);
		});
	});
	describe('cloud-enablement:dockertools with empty bluemix object', () => {
		beforeEach(() => {
			return helpers.run(path.join(__dirname, '../generators/dockertools'))
				.withOptions({ bluemix: '{"backendPlatform":"NODE"}' })
		});
		it('should give us the default output with no project name', () => {
			assert.file('Dockerfile');
			assert.fileContent('cli-config.yml', 'container-name-run : "app-express-run"');
		});
	});
});
<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        expect(fs.existsSync(__dirname + '/../LICENSE'), 'A LICENSE must exist');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should have a section ## License');
            console.log();
        }
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    fs = require('fs'),
    argv = require('minimist')(process.argv.slice(2)),
    tildify = require('tildify'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    replace = require('gulp-replace'),
    rename = require('gulp-rename');

function capitaliseFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

function isArray ( obj ) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

var STRING_CAMELIZE_REGEXP = (/(\-|_|\.|\s)+(.)?/g);

function camelize(str) {
  return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) {
    return chr ? chr.toUpperCase() : '';
  });
}

function dashizeNameError ( filename ) {
  if ( filename.indexOf('-') === -1 ) {
    gutil.log(
      gutil.colors.red('[-Error:] '),
      gutil.colors.cyan( filename ),
      gutil.colors.red(' must be a dashize string. ex: my-component')
    );
    gutil.log(
      gutil.colors.red('[-Error:]  Generate task has been canceled')
    );
    process.exit(0);
  }
}

function generatorEngine(type, srcPath, moduleName, fileName, finalPath, destPath ) {

     var ext = (type === 'template') ? '.hbs' : '.js',
        fullFilePath = destPath + '/' + fileName + ext;

    // if the file has existed, it will abort the task
    if ( fs.existsSync( fullFilePath ) ) {
      gutil.log(
        gutil.colors.red('[-Error:] '),
        gutil.colors.cyan(fileName + ext),
        gutil.colors.red('has existed at '),
        gutil.colors.magenta( tildify(destPath) )
      );
      gutil.log(
        gutil.colors.red('[-Error:]  Generate task has been canceled')
      );
      process.exit(0);
    }

    // @TODO when generate multiple files on certain type
    // moduleName is not being defined correctly.
    // fine for now, since multiple file generation are only template file
    return gulp.src( srcPath )
      .pipe(replace(/__NAMESPACE__/g, moduleName))
      .pipe(rename({
        basename : fileName,
        extname: ext
      }))
      .on('end', function() {
        gutil.log(
          gutil.colors.green('[-done:] Generate'),
          gutil.colors.cyan(fileName + ext),
          gutil.colors.green('at'),
          gutil.colors.magenta( tildify(destPath) )
        );
      })
      .pipe(gulp.dest(destPath));
}

function setupTask( generator ) {
  //   task: gen
  //   @describe	generate an model,view,store,controller from base template
  return gulp.task('gen', function() {
      var type = generator.type,
        name = generator.name,
        pathName = '',
        moduleName = '',
        i = 0,
        pathNested;

      if ( name.indexOf('/') > -1 ) {
        name = name.split('/');
        pathNested = true;
      } else {
        pathNested = false;
      }

      // setup the fileName which used for rename module
      var fileName = pathNested ? name.pop() : name;

      // handle the error case when arg is  component:foo
      // component name has to be dashized string
      // here does not handle the nested path case
      if ( type === 'component' && !pathNested ) {
        dashizeNameError(fileName);
      }

      if ( isArray(name) ) {
        // when type is component, name of nest path has to be dashized string
        // when type is template, name[0] is component, name of nest path has to be dashized string
        if ( type === 'template' && name[0] === 'component' || type === 'component') {
          dashizeNameError(fileName);
        }
        // build up the nested path
        for( ; i < name.length; i++) {
          // 'component' and 'components' resolve as a 'app/templates/components/'
          if ( type === 'template' && name[0] === 'component') {
            name[i] = 'components';
          }
          pathName += '/' + name[i];
          moduleName += capitaliseFirstLetter(name[i]);
        }
        // append fileName to the moduleName string
        moduleName += capitaliseFirstLetter(fileName);
      } else {
        pathName += name;
        moduleName += capitaliseFirstLetter(name);
      }

      moduleName += capitaliseFirstLetter(type);

      // if it has dashized moduleName, it will camelize
      moduleName = camelize(moduleName);

      // ignore the 'store' case, since it is already created
      var typeFolder = path.resolve('client/app', type+'s');

      // if client/app/[type](s) is not existed, simply create one
      if (!fs.existsSync(typeFolder)) {
        fs.mkdirSync(typeFolder);
        gutil.log(
          gutil.colors.gray('[-log:] Created a new folder at '),
          gutil.colors.cyan( '~/client/app/' +  type + 's')
        );
      }

      // when generator type is route or component
      // it will also generate the template as well
      var srcPath =
          (type === 'route' || type === 'component') ?
            [{
                type: type,
                generatorPath: path.join(__dirname, '..', 'skeletons/generators', type)  + '.js'
              }, {
                type: 'template',
                injection: ( type === 'component' ) ? 'components' : void 0,
                generatorPath: path.join(__dirname, '..', 'skeletons/generators', 'template.js')
              }]
            : path.join(__dirname, '..', 'skeletons/generators', type) + '.js';

      var dirName, finalDirName, finalPath, destPath;

      // if type is test, or route-test or any sorts, it should append `-test` to the filename
      fileName = (type.indexOf('test') > -1) ? fileName+'-test' : fileName;

      // if it is a string, simple call generatorEngine once
      // else it is an object(array), repeat the generatorEngine call
      if ( typeof srcPath === 'string' ) {

        dirName = (type === 'store') ? type : ( type.slice(-1) === 's' ) ? type : type +'s';

        if (type.indexOf('test') > -1) {
          if(type.indexOf('-test') > -1) {
            var typeArray = type.split('-');
            finalDirName = 'tests/' + typeArray[0] + 's/unit';
          } else {
            finalDirName = dirName + '/integration';
          }
        } else {
          finalDirName = dirName;
        }

        finalPath = pathNested ? finalDirName + pathName : finalDirName;
        destPath =  (type.indexOf('test') > -1) ?
          path.resolve('client') + '/' + finalPath
          : path.resolve('client/app') + '/' + finalPath;

        generatorEngine( type, srcPath, moduleName, fileName, finalPath, destPath );
      } else {

        for ( var j = 0, l = srcPath.length; j < l; j++ ) {
          var _type = srcPath[j].type,
            // when original type is 'component'
            // it will create a template file at 'templates/components' folder
            injection = srcPath[j].injection;

          dirName = (_type === 'store') ? _type : ( _type.slice(-1) === 's' ) ? _type : _type +'s';
          dirName = ( injection ) ? dirName + '/' + injection : dirName;

          finalPath = pathNested ? dirName + pathName : dirName;
          destPath =  path.resolve('client/app') + '/' + finalPath;

          generatorEngine(
            _type, srcPath[j].generatorPath, moduleName, fileName, finalPath, destPath
          );
        }
      }
    });
}

var generate = function(options) {

  // if the folder 'client/app' is not existed
  // can assume that the project may not be created by Ember Rocks
  if ( !fs.existsSync('client') && !fs.existsSync('client/app') ) {
    gutil.log(
      gutil.colors.red(
        '[-Error:] This project may not be created by \'Ember-Rocks\'\n'
      ),
      gutil.colors.red(
        '[-Error:] `em new [dirName]` does not install the NPM packages dependencies correctly'
      )
    );
    process.exit(1);
  }

  // Error out when user did not provide any arugments
  if (argv._.length < 2) {
    gutil.log(gutil.colors.red('[-Error:] Missing type:name argument.'), 'ex: em new route:post');
    gutil.log(gutil.colors.red('[-Error:]'), 'See \'em generate --help\'');
    process.exit(0);
  }

  var typeAndName = argv._.slice()[1],
    generatorAndTasks = typeAndName.length ? typeAndName.split(':') : undefined,
    validTypes = [
      'adapter', 'component', 'controller', 'helper', 'initializer',
      'mixin', 'model', 'route', 'serializer', 'template',
      'transform', 'util', 'view',
      'test', 'route-test'
    ],
    gen;

  // Arugments must be in this format: type:name
  if( generatorAndTasks && generatorAndTasks.length > 1 ) {
    var type = generatorAndTasks[0],
        name = generatorAndTasks[1];

    // type could be either route or routes
    type = ( type.slice(-1) === 's' ) ? type.substring(0, type.length - 1) : type;

    // Type must be in the `validTypes` array
    if (validTypes.indexOf(type) > -1) {
      // Name must be a valid string
      if( name.length > 0 ) {
        gen = {
          type: type,
          name: name
        };
      } else {
        gutil.log(
          gutil.colors.red('[-Error:] '),
          gutil.colors.cyan( name ),
          gutil.colors.red(' must be a valid string.')
        );
        gutil.log(gutil.colors.red('[-Error:]'), 'See \'em generate --help\'');
        process.exit(0);
      }
    } else {
      gutil.log(
        gutil.colors.red('[-Error:] '),
        gutil.colors.cyan(type),
        gutil.colors.red(' is not a valid type.')
      );
      gutil.log(
        gutil.colors.bold('[-note:] valid types are'),
        gutil.colors.cyan( validTypes.join(', ') )
      );
      process.exit(0);
    }
  } else {
    gutil.log(
      gutil.colors.red('[-Error:] Provide the wrong argument. It must be in this format '),
      gutil.colors.cyan('type:name'), ' ex: em generate route:post'
    );
    gutil.log(
      gutil.colors.red('[-Error:]'),
      'See \'em generate --help\''
    );
    process.exit(0);
  }

  setupTask(gen);
  // Trigger the generator task
  gulp.start('gen');
};

module.exports = generate;
<commit_msg>update the unit test filepath<commit_after>'use strict';

var path = require('path'),
    fs = require('fs'),
    argv = require('minimist')(process.argv.slice(2)),
    tildify = require('tildify'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    replace = require('gulp-replace'),
    rename = require('gulp-rename');

function capitaliseFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

function isArray ( obj ) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

var STRING_CAMELIZE_REGEXP = (/(\-|_|\.|\s)+(.)?/g);

function camelize(str) {
  return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) {
    return chr ? chr.toUpperCase() : '';
  });
}

function dashizeNameError ( filename ) {
  if ( filename.indexOf('-') === -1 ) {
    gutil.log(
      gutil.colors.red('[-Error:] '),
      gutil.colors.cyan( filename ),
      gutil.colors.red(' must be a dashize string. ex: my-component')
    );
    gutil.log(
      gutil.colors.red('[-Error:]  Generate task has been canceled')
    );
    process.exit(0);
  }
}

function generatorEngine(type, srcPath, moduleName, fileName, finalPath, destPath ) {

     var ext = (type === 'template') ? '.hbs' : '.js',
        fullFilePath = destPath + '/' + fileName + ext;

    // if the file has existed, it will abort the task
    if ( fs.existsSync( fullFilePath ) ) {
      gutil.log(
        gutil.colors.red('[-Error:] '),
        gutil.colors.cyan(fileName + ext),
        gutil.colors.red('has existed at '),
        gutil.colors.magenta( tildify(destPath) )
      );
      gutil.log(
        gutil.colors.red('[-Error:]  Generate task has been canceled')
      );
      process.exit(0);
    }

    // @TODO when generate multiple files on certain type
    // moduleName is not being defined correctly.
    // fine for now, since multiple file generation are only template file
    return gulp.src( srcPath )
      .pipe(replace(/__NAMESPACE__/g, moduleName))
      .pipe(rename({
        basename : fileName,
        extname: ext
      }))
      .on('end', function() {
        gutil.log(
          gutil.colors.green('[-done:] Generate'),
          gutil.colors.cyan(fileName + ext),
          gutil.colors.green('at'),
          gutil.colors.magenta( tildify(destPath) )
        );
      })
      .pipe(gulp.dest(destPath));
}

function setupTask( generator ) {
  //   task: gen
  //   @describe	generate an model,view,store,controller from base template
  return gulp.task('gen', function() {
      var type = generator.type,
        name = generator.name,
        pathName = '',
        moduleName = '',
        i = 0,
        pathNested;

      if ( name.indexOf('/') > -1 ) {
        name = name.split('/');
        pathNested = true;
      } else {
        pathNested = false;
      }

      // setup the fileName which used for rename module
      var fileName = pathNested ? name.pop() : name;

      // handle the error case when arg is  component:foo
      // component name has to be dashized string
      // here does not handle the nested path case
      if ( type === 'component' && !pathNested ) {
        dashizeNameError(fileName);
      }

      if ( isArray(name) ) {
        // when type is component, name of nest path has to be dashized string
        // when type is template, name[0] is component, name of nest path has to be dashized string
        if ( type === 'template' && name[0] === 'component' || type === 'component') {
          dashizeNameError(fileName);
        }
        // build up the nested path
        for( ; i < name.length; i++) {
          // 'component' and 'components' resolve as a 'app/templates/components/'
          if ( type === 'template' && name[0] === 'component') {
            name[i] = 'components';
          }
          pathName += '/' + name[i];
          moduleName += capitaliseFirstLetter(name[i]);
        }
        // append fileName to the moduleName string
        moduleName += capitaliseFirstLetter(fileName);
      } else {
        pathName += name;
        moduleName += capitaliseFirstLetter(name);
      }

      moduleName += capitaliseFirstLetter(type);

      // if it has dashized moduleName, it will camelize
      moduleName = camelize(moduleName);

      // ignore the 'store' case, since it is already created
      var typeFolder = path.resolve('client/app', type+'s');

      // if client/app/[type](s) is not existed, simply create one
      if (!fs.existsSync(typeFolder)) {
        fs.mkdirSync(typeFolder);
        gutil.log(
          gutil.colors.gray('[-log:] Created a new folder at '),
          gutil.colors.cyan( '~/client/app/' +  type + 's')
        );
      }

      // when generator type is route or component
      // it will also generate the template as well
      var srcPath =
          (type === 'route' || type === 'component') ?
            [{
                type: type,
                generatorPath: path.join(__dirname, '..', 'skeletons/generators', type)  + '.js'
              }, {
                type: 'template',
                injection: ( type === 'component' ) ? 'components' : void 0,
                generatorPath: path.join(__dirname, '..', 'skeletons/generators', 'template.js')
              }]
            : path.join(__dirname, '..', 'skeletons/generators', type) + '.js';

      var dirName, finalDirName, finalPath, destPath;

      // if type is test, or route-test or any sorts, it should append `-test` to the filename
      fileName = (type.indexOf('test') > -1) ? fileName+'-test' : fileName;

      // if it is a string, simple call generatorEngine once
      // else it is an object(array), repeat the generatorEngine call
      if ( typeof srcPath === 'string' ) {

        dirName = (type === 'store') ? type : ( type.slice(-1) === 's' ) ? type : type +'s';

        if (type.indexOf('test') > -1) {
          if(type.indexOf('-test') > -1) {
            var typeArray = type.split('-');
            finalDirName = 'tests/unit/' + typeArray[0] + 's';
          } else {
            finalDirName = dirName + '/integration';
          }
        } else {
          finalDirName = dirName;
        }

        finalPath = pathNested ? finalDirName + pathName : finalDirName;
        destPath =  (type.indexOf('test') > -1) ?
          path.resolve('client') + '/' + finalPath
          : path.resolve('client/app') + '/' + finalPath;

        generatorEngine( type, srcPath, moduleName, fileName, finalPath, destPath );
      } else {

        for ( var j = 0, l = srcPath.length; j < l; j++ ) {
          var _type = srcPath[j].type,
            // when original type is 'component'
            // it will create a template file at 'templates/components' folder
            injection = srcPath[j].injection;

          dirName = (_type === 'store') ? _type : ( _type.slice(-1) === 's' ) ? _type : _type +'s';
          dirName = ( injection ) ? dirName + '/' + injection : dirName;

          finalPath = pathNested ? dirName + pathName : dirName;
          destPath =  path.resolve('client/app') + '/' + finalPath;

          generatorEngine(
            _type, srcPath[j].generatorPath, moduleName, fileName, finalPath, destPath
          );
        }
      }
    });
}

var generate = function(options) {

  // if the folder 'client/app' is not existed
  // can assume that the project may not be created by Ember Rocks
  if ( !fs.existsSync('client') && !fs.existsSync('client/app') ) {
    gutil.log(
      gutil.colors.red(
        '[-Error:] This project may not be created by \'Ember-Rocks\'\n'
      ),
      gutil.colors.red(
        '[-Error:] `em new [dirName]` does not install the NPM packages dependencies correctly'
      )
    );
    process.exit(1);
  }

  // Error out when user did not provide any arugments
  if (argv._.length < 2) {
    gutil.log(gutil.colors.red('[-Error:] Missing type:name argument.'), 'ex: em new route:post');
    gutil.log(gutil.colors.red('[-Error:]'), 'See \'em generate --help\'');
    process.exit(0);
  }

  var typeAndName = argv._.slice()[1],
    generatorAndTasks = typeAndName.length ? typeAndName.split(':') : undefined,
    validTypes = [
      'adapter', 'component', 'controller', 'helper', 'initializer',
      'mixin', 'model', 'route', 'serializer', 'template',
      'transform', 'util', 'view',
      'test', 'route-test'
    ],
    gen;

  // Arugments must be in this format: type:name
  if( generatorAndTasks && generatorAndTasks.length > 1 ) {
    var type = generatorAndTasks[0],
        name = generatorAndTasks[1];

    // type could be either route or routes
    type = ( type.slice(-1) === 's' ) ? type.substring(0, type.length - 1) : type;

    // Type must be in the `validTypes` array
    if (validTypes.indexOf(type) > -1) {
      // Name must be a valid string
      if( name.length > 0 ) {
        gen = {
          type: type,
          name: name
        };
      } else {
        gutil.log(
          gutil.colors.red('[-Error:] '),
          gutil.colors.cyan( name ),
          gutil.colors.red(' must be a valid string.')
        );
        gutil.log(gutil.colors.red('[-Error:]'), 'See \'em generate --help\'');
        process.exit(0);
      }
    } else {
      gutil.log(
        gutil.colors.red('[-Error:] '),
        gutil.colors.cyan(type),
        gutil.colors.red(' is not a valid type.')
      );
      gutil.log(
        gutil.colors.bold('[-note:] valid types are'),
        gutil.colors.cyan( validTypes.join(', ') )
      );
      process.exit(0);
    }
  } else {
    gutil.log(
      gutil.colors.red('[-Error:] Provide the wrong argument. It must be in this format '),
      gutil.colors.cyan('type:name'), ' ex: em generate route:post'
    );
    gutil.log(
      gutil.colors.red('[-Error:]'),
      'See \'em generate --help\''
    );
    process.exit(0);
  }

  setupTask(gen);
  // Trigger the generator task
  gulp.start('gen');
};

module.exports = generate;
<|endoftext|>


<commit_before>var sliderInit = $('.slick-slider-init');

$(document).ready(function(){

    sliderInit.slick({
        autoplay: false,
        pauseOnHover: false,
        speed: 1500,
        autoplaySpeed: 6000
    });

});<commit_msg>[task] init jquery plugin slickAnimation<commit_after>var sliderInit = $('.slick-slider-init');

$(document).ready(function () {

    sliderInit.slick({
        autoplay: false,
        pauseOnHover: false,
        speed: 1500,
        autoplaySpeed: 6000
    });

    sliderInit.slickAnimation();
});
<|endoftext|>


<commit_before>
/*!
 * Express - router - methods
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Supported HTTP / WebDAV methods.
 */

module.exports = [
    'get'
  , 'post'
  , 'put'
  , 'delete'
  , 'connect'
  , 'options'
  , 'trace'
  , 'copy'
  , 'lock'
  , 'mkcol'
  , 'move'
  , 'propfind'
  , 'proppatch'
  , 'unlock'
  , 'report'
  , 'mkactivity'
  , 'checkout'
  , 'merge'
];<commit_msg>split methods supported by rfc [slaskis]<commit_after>
/*!
 * Express - router - methods
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Hypertext Transfer Protocol -- HTTP/1.1
 * http://www.ietf.org/rfc/rfc2616.txt
 */

var RFC2616 = ['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT'];

/**
 * HTTP Extensions for Distributed Authoring -- WEBDAV
 * http://www.ietf.org/rfc/rfc2518.txt
 */

var RFC2518 = ['PROPFIND', 'PROPPATCH', 'MKCOL', 'COPY', 'MOVE', 'LOCK', 'UNLOCK'];

/**
 * Versioning Extensions to WebDAV
 * http://www.ietf.org/rfc/rfc3253.txt
 */

var RFC3253 = ['VERSION-CONTROL', 'REPORT', 'CHECKOUT', 'CHECKIN', 'UNCHECKOUT', 'MKWORKSPACE', 'UPDATE', 'LABEL', 'MERGE', 'BASELINE-CONTROL', 'MKACTIVITY'];

/**
 * Ordered Collections Protocol (WebDAV)
 * http://www.ietf.org/rfc/rfc3648.txt
 */

var RFC3648 = ['ORDERPATCH'];

/**
 * Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol
 * http://www.ietf.org/rfc/rfc3744.txt
 */

var RFC3744 = ['ACL'];

/**
 * Web Distributed Authoring and Versioning (WebDAV) SEARCH
 * http://www.ietf.org/rfc/rfc5323.txt
 */

var RFC5323 = ['SEARCH'];

/**
 * PATCH Method for HTTP
 * http://www.ietf.org/rfc/rfc5789.txt
 */

var RFC5789 = ['PATCH'];

/**
 * Expose the methods.
 */

module.exports = [].concat(
    RFC2616
  , RFC2518
  , RFC3253
  , RFC3648
  , RFC3744
  , RFC5323
  , RFC5789).map(function(method){
    return method.toLowerCase();
  });<|endoftext|>