<commit_before>require('babel/register')({optional: ['es7.objectRestSpread', 'regenerator']});

var argv = require('yargs').argv,
  autoprefixer = require('gulp-autoprefixer'),
  browserify = require('browserify'),
  connect = require('gulp-connect'),
  del = require('del'),
  errorHandler = require('./tasks/errorHandler.js'),
  fs = require('fs'),
  gulp = require('gulp'),
  jshint = require('gulp-jshint'),
  open = require('gulp-open'),
  path = require('path'),
  reactify = require('reactify'),
  rename = require('gulp-rename'),
  replace = require('gulp-replace'),
  shell = require('gulp-shell'),
  source = require('vinyl-source-stream'),
  stylish = require('jshint-stylish'),
  jsxTransform = require('gulp-react'),
  sass = require('gulp-sass'),
  through = require('through2');

require('./tasks/build.js');
require('./tasks/publish.js');
require('./tasks/test.js');
require('./tasks/release.js');
var src = require('./tasks/util').src;

gulp.task('default', [
  'watch',
  'serve'
]);

gulp.task('watch', ['assets'], function() {
  gulp.watch(['src/pivotal-ui/components/**/*.scss', 'src/pivotal-ui/pivotal-ui.scss'], ['_puiScss']);
  gulp.watch(['src/pivotal-ui/javascripts/**/*.js', 'src/pivotal-ui/javascripts/**/*.jsx'], ['_puiJs']);
  gulp.watch(['src/styleguide/**/*.scss'], ['_styleguideScss']);
});

gulp.task('serve', function() {
  connect.server({
    root: ['build'],
    port: 8000,
    livereload: true
  });
});

gulp.task('lint', function() {
  return src('./src/pivotal-ui/javascripts/**/*.js?(x)')
    .pipe(jsxTransform())
    .pipe(jshint().on('error', errorHandler.handleError))
    .pipe(jshint.reporter(stylish))
    .pipe(jshint.reporter('fail'));
});

gulp.task('assets', [
  '_puiScss',
  '_styleguideScss',
  '_puiJs',
  '_otherAssets',
  '_testAssets'
]);

gulp.task('clean', function(done) {
  del(['build', 'test/css/build'], {force: true}, done);
});

// private

gulp.task('_puiScss', [
  '_sassBuildPui',
  '_sassBuildPuiRails',
  '_buildComponents',
  '_copyPuiScssToTest',
  '_hologramBuild',
  '_copyOtherHtmlFiles'
]);

gulp.task('_cleanBuiltPuiScss', function(done) {
  del([
    'build/pivotal-ui.css',
    'build/pivotal-ui-rails.css',
    'build/*.html',
    'dist/',
    'test/css/components',
    'test/css/build/'
  ], {force: true}, function() {
    fs.mkdir('test/css/components', done);
  });
});

gulp.task('_sassBuildPui', ['_cleanBuiltPuiScss'], function() {
  return src(['src/pivotal-ui/pivotal-ui.scss'])
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(gulp.dest('build'));
});

gulp.task('_sassBuildPuiRails', ['_cleanBuiltPuiScss', '_sassBuildPui'], function() {
  return src('build/pivotal-ui.css')
    .pipe(
      replace(/url\(('|")\.\.\/fonts\//g, 'font-url\($1fonts/')
    )
    .pipe(
      replace(/url\(('|")\.\.\/images\//g, 'image-url\($1images/')
    )
    .pipe(rename('pivotal-ui-rails.css'))
    .pipe(gulp.dest('build/'));
});

gulp.task('_copyPuiScssToTest', ['_sassBuildPui'], function() {
  return src(['build/pivotal-ui.css'])
    .pipe(gulp.dest('test/css/build/'));
});

gulp.task('_hologramBuild', ['_cleanBuiltPuiScss'], function() {
  return src('')
    .pipe(shell('bundle exec hologram'))
    .on('error', errorHandler.handleError);
});

gulp.task('_copyOtherHtmlFiles', ['_cleanBuiltPuiScss'], function() {
  return src([
    'src/styleguide/404.html',
    'src/styleguide/pane.html',
    'src/styleguide/reset_password.html'
  ]).pipe(gulp.dest('./build/'));
});

gulp.task('_styleguideScss', [
  '_sassBuildStyleguide'
]);

gulp.task('_cleanBuiltStyleguideScss', function(done) {
  del(['build/styleguide.css'], {force: true}, done);
});

gulp.task('_sassBuildStyleguide', ['_cleanBuiltStyleguideScss'], function() {
  return src(['src/styleguide/styleguide.scss'])
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(gulp.dest('build/styleguide'));
});

gulp.task('_puiJs', [
  '_buildPuiJs',
  '_buildPuiReactJs',
  '_copyPuiJsToTest'
]);

gulp.task('_cleanBuiltPuiJs', function(done) {
  del([
    'build/pivotal-ui.js',
    'build/pivotal-ui-react.js',
    'test/css/build/pivotal-ui-react.js'
  ], {force: true}, done);
});

gulp.task('_buildPuiJs', ['_cleanBuiltPuiJs'], function() {
  var b = browserify('./src/pivotal-ui/javascripts/pivotal-ui.js');

  return b.bundle()
    .pipe(source('./pivotal-ui.js'))
    .pipe(gulp.dest('build/'))
});

gulp.task('_buildPuiReactJs', ['_cleanBuiltPuiJs'], function() {
  var b = browserify('./src/pivotal-ui/javascripts/pivotal-ui-react.js');
  b.transform(reactify, {es6: true});

  return b.bundle()
    .pipe(source('./pivotal-ui-react.js'))
    .pipe(gulp.dest('build/'))
});

gulp.task('_copyPuiJsToTest', ['_cleanBuiltPuiJs', '_buildPuiReactJs'], function() {
  return src('build/pivotal-ui-react.js')
    .pipe(gulp.dest('test/css/build/'));
});

gulp.task('_otherAssets', [
  '_copyPrism',
  '_copyImages',
  '_copyFontAwesome',
  '_copySourceSansPro',
  '_copyStyleguideAssets',
  '_copyStaticfile',
  '_copyZeroClipboard',
  '_copyNginxConf'
]);

gulp.task('_cleanOtherAssets', function(done) {
  del([
    'build/syntax-highlighting',
    'build/images/',
    'build/fonts',
    'build/styleguide/*.js',
    'build/styleguide/github.css',
    'build/Staticfile',
    'build/zeroclipboard'
  ], {force: true}, done);
});

gulp.task('_copyPrism', ['_cleanOtherAssets'], function() {
  return src(['src/syntax-highlighting/*.css'])
    .pipe(gulp.dest('./build/syntax-highlighting/'));
});

gulp.task('_copyImages', ['_cleanOtherAssets'], function() {
  return src('src/images/**/*')
    .pipe(gulp.dest('./build/images/'));
});

gulp.task('_copyFontAwesome', ['_cleanOtherAssets'], function() {
  return src([
    'node_modules/font-awesome/fonts/*'
  ])
    .pipe(gulp.dest('./build/fonts/'));
});

gulp.task('_copySourceSansPro', ['_cleanOtherAssets'], function() {
  return src([
    'src/source-sans-pro/**/*',
    '!src/source-sans-pro/source-sans-pro.css.scss'
  ])
    .pipe(gulp.dest('./build/fonts/'));
});

gulp.task('_copyStyleguideAssets', ['_cleanOtherAssets'], function() {
  return src(['src/styleguide/*.js', 'src/styleguide/github.css'])
    .pipe(gulp.dest('./build/styleguide'));
});

gulp.task('_copyStaticfile', ['_cleanOtherAssets'], function() {
  return src(['src/Staticfile'])
    .pipe(gulp.dest('./build/'));
});

gulp.task('_copyZeroClipboard', ['_cleanOtherAssets'], function() {
  return src([
    'node_modules/zeroclipboard/dist/ZeroClipboard.js',
    'node_modules/zeroclipboard/dist/ZeroClipboard.swf'
  ])
    .pipe(gulp.dest('./build/zeroclipboard/'));
});

gulp.task('_copyNginxConf', ['_cleanOtherAssets'], function() {
  return src(['config/nginx.conf'])
    .pipe(gulp.dest('./build/'));
});

gulp.task('_testAssets', [
  '_copyTestFonts',
  '_copyTestImages',
  '_copyTestPrism',
  '_copyTestStyleguideAssets'
]);

gulp.task('_cleanTestAssets', function(done) {
  del([
    'test/css/build/fonts/**/*',
    'test/css/build/images/**/*',
    'test/css/build/syntax-highlighting/**/*'
  ], {force: true}, done);
});

gulp.task('_copyTestFonts', ['_cleanTestAssets', '_otherAssets'], function() {
  return src('build/fonts/**/*')
    .pipe(gulp.dest('./test/css/build/fonts'));
});

gulp.task('_copyTestImages', ['_cleanTestAssets', '_otherAssets'], function() {
  return src('build/images/**/*')
    .pipe(gulp.dest('./test/css/build/images'));
});

gulp.task('_copyTestPrism', ['_cleanTestAssets', '_otherAssets'], function() {
  return src('build/syntax-highlighting/**/*')
    .pipe(gulp.dest('./test/css/build/syntax-highlighting'));
});

gulp.task('_copyTestStyleguideAssets', ['_cleanTestAssets', '_otherAssets'], function() {
  return src('build/styleguide/github.css')
    .pipe(gulp.dest('./test/css/build/styleguide'));
});

<commit_msg>chore(packaging): do not delete the build folders in the middle of the build<commit_after>require('babel/register')({optional: ['es7.objectRestSpread', 'regenerator']});

var argv = require('yargs').argv,
  autoprefixer = require('gulp-autoprefixer'),
  browserify = require('browserify'),
  connect = require('gulp-connect'),
  del = require('del'),
  errorHandler = require('./tasks/errorHandler.js'),
  fs = require('fs'),
  gulp = require('gulp'),
  jshint = require('gulp-jshint'),
  open = require('gulp-open'),
  path = require('path'),
  reactify = require('reactify'),
  rename = require('gulp-rename'),
  replace = require('gulp-replace'),
  shell = require('gulp-shell'),
  source = require('vinyl-source-stream'),
  stylish = require('jshint-stylish'),
  jsxTransform = require('gulp-react'),
  sass = require('gulp-sass'),
  through = require('through2');

var runSequence = require('run-sequence');

require('./tasks/build.js');
require('./tasks/publish.js');
require('./tasks/test.js');
require('./tasks/release.js');
var src = require('./tasks/util').src;

gulp.task('default', [
  'watch',
  'serve'
]);

gulp.task('watch', ['assets'], function() {
  gulp.watch(['src/pivotal-ui/components/**/*.scss', 'src/pivotal-ui/pivotal-ui.scss'], ['_puiScss']);
  gulp.watch(['src/pivotal-ui/javascripts/**/*.js', 'src/pivotal-ui/javascripts/**/*.jsx'], ['_puiJs']);
  gulp.watch(['src/styleguide/**/*.scss'], ['_styleguideScss']);
});

gulp.task('serve', function() {
  connect.server({
    root: ['build'],
    port: 8000,
    livereload: true
  });
});

gulp.task('lint', function() {
  return src('./src/pivotal-ui/javascripts/**/*.js?(x)')
    .pipe(jsxTransform())
    .pipe(jshint().on('error', errorHandler.handleError))
    .pipe(jshint.reporter(stylish))
    .pipe(jshint.reporter('fail'));
});

gulp.task('assets', [
  '_puiScss',
  '_styleguideScss',
  '_puiJs',
  '_otherAssets',
  '_testAssets'
]);

gulp.task('clean', function(done) {
  del(['build', 'test/css/build'], {force: true}, done);
});

// private

gulp.task('_puiScss', function(callback) {
  runSequence(
    '_cleanBuiltPuiScss',
    ['_sassBuildPuiRails', '_buildComponents'],
    '_copyPuiScssToTest',
    '_hologramBuild',
    '_copyOtherHtmlFiles',
  callback);
});

gulp.task('_cleanBuiltPuiScss', function(done) {
  del([
    'build/pivotal-ui.css',
    'build/pivotal-ui-rails.css',
    'build/*.html',
    'dist/',
    'test/css/components',
    'test/css/build/'
  ], {force: true}, function() {
    fs.mkdir('test/css/components', done);
  });
});

gulp.task('_sassBuildPui', function() {
  return src(['src/pivotal-ui/pivotal-ui.scss'])
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(gulp.dest('build'));
});

gulp.task('_sassBuildPuiRails', ['_sassBuildPui'], function() {
  return src('build/pivotal-ui.css')
    .pipe(
      replace(/url\(('|")\.\.\/fonts\//g, 'font-url\($1fonts/')
    )
    .pipe(
      replace(/url\(('|")\.\.\/images\//g, 'image-url\($1images/')
    )
    .pipe(rename('pivotal-ui-rails.css'))
    .pipe(gulp.dest('build/'));
});

gulp.task('_copyPuiScssToTest', ['_sassBuildPui'], function() {
  return src(['build/pivotal-ui.css'])
    .pipe(gulp.dest('test/css/build/'));
});

gulp.task('_hologramBuild', function() {
  return src('')
    .pipe(shell('bundle exec hologram'))
    .on('error', errorHandler.handleError);
});

gulp.task('_copyOtherHtmlFiles', function() {
  return src([
    'src/styleguide/404.html',
    'src/styleguide/pane.html',
    'src/styleguide/reset_password.html'
  ]).pipe(gulp.dest('./build/'));
});

gulp.task('_styleguideScss', [
  '_sassBuildStyleguide'
]);

gulp.task('_cleanBuiltStyleguideScss', function(done) {
  del(['build/styleguide.css'], {force: true}, done);
});

gulp.task('_sassBuildStyleguide', ['_cleanBuiltStyleguideScss'], function() {
  return src(['src/styleguide/styleguide.scss'])
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(gulp.dest('build/styleguide'));
});

gulp.task('_puiJs', [
  '_buildPuiJs',
  '_buildPuiReactJs',
  '_copyPuiJsToTest'
]);

gulp.task('_cleanBuiltPuiJs', function(done) {
  del([
    'build/pivotal-ui.js',
    'build/pivotal-ui-react.js',
    'test/css/build/pivotal-ui-react.js'
  ], {force: true}, done);
});

gulp.task('_buildPuiJs', ['_cleanBuiltPuiJs'], function() {
  var b = browserify('./src/pivotal-ui/javascripts/pivotal-ui.js');

  return b.bundle()
    .pipe(source('./pivotal-ui.js'))
    .pipe(gulp.dest('build/'))
});

gulp.task('_buildPuiReactJs', ['_cleanBuiltPuiJs'], function() {
  var b = browserify('./src/pivotal-ui/javascripts/pivotal-ui-react.js');
  b.transform(reactify, {es6: true});

  return b.bundle()
    .pipe(source('./pivotal-ui-react.js'))
    .pipe(gulp.dest('build/'))
});

gulp.task('_copyPuiJsToTest', ['_cleanBuiltPuiJs', '_buildPuiReactJs'], function() {
  return src('build/pivotal-ui-react.js')
    .pipe(gulp.dest('test/css/build/'));
});

gulp.task('_otherAssets', [
  '_copyPrism',
  '_copyImages',
  '_copyFontAwesome',
  '_copySourceSansPro',
  '_copyStyleguideAssets',
  '_copyStaticfile',
  '_copyZeroClipboard',
  '_copyNginxConf'
]);

gulp.task('_cleanOtherAssets', function(done) {
  del([
    'build/syntax-highlighting',
    'build/images/',
    'build/fonts',
    'build/styleguide/*.js',
    'build/styleguide/github.css',
    'build/Staticfile',
    'build/zeroclipboard'
  ], {force: true}, done);
});

gulp.task('_copyPrism', ['_cleanOtherAssets'], function() {
  return src(['src/syntax-highlighting/*.css'])
    .pipe(gulp.dest('./build/syntax-highlighting/'));
});

gulp.task('_copyImages', ['_cleanOtherAssets'], function() {
  return src('src/images/**/*')
    .pipe(gulp.dest('./build/images/'));
});

gulp.task('_copyFontAwesome', ['_cleanOtherAssets'], function() {
  return src([
    'node_modules/font-awesome/fonts/*'
  ])
    .pipe(gulp.dest('./build/fonts/'));
});

gulp.task('_copySourceSansPro', ['_cleanOtherAssets'], function() {
  return src([
    'src/source-sans-pro/**/*',
    '!src/source-sans-pro/source-sans-pro.css.scss'
  ])
    .pipe(gulp.dest('./build/fonts/'));
});

gulp.task('_copyStyleguideAssets', ['_cleanOtherAssets'], function() {
  return src(['src/styleguide/*.js', 'src/styleguide/github.css'])
    .pipe(gulp.dest('./build/styleguide'));
});

gulp.task('_copyStaticfile', ['_cleanOtherAssets'], function() {
  return src(['src/Staticfile'])
    .pipe(gulp.dest('./build/'));
});

gulp.task('_copyZeroClipboard', ['_cleanOtherAssets'], function() {
  return src([
    'node_modules/zeroclipboard/dist/ZeroClipboard.js',
    'node_modules/zeroclipboard/dist/ZeroClipboard.swf'
  ])
    .pipe(gulp.dest('./build/zeroclipboard/'));
});

gulp.task('_copyNginxConf', ['_cleanOtherAssets'], function() {
  return src(['config/nginx.conf'])
    .pipe(gulp.dest('./build/'));
});

gulp.task('_testAssets', [
  '_copyTestFonts',
  '_copyTestImages',
  '_copyTestPrism',
  '_copyTestStyleguideAssets'
]);

gulp.task('_cleanTestAssets', function(done) {
  del([
    'test/css/build/fonts/**/*',
    'test/css/build/images/**/*',
    'test/css/build/syntax-highlighting/**/*'
  ], {force: true}, done);
});

gulp.task('_copyTestFonts', ['_cleanTestAssets', '_otherAssets'], function() {
  return src('build/fonts/**/*')
    .pipe(gulp.dest('./test/css/build/fonts'));
});

gulp.task('_copyTestImages', ['_cleanTestAssets', '_otherAssets'], function() {
  return src('build/images/**/*')
    .pipe(gulp.dest('./test/css/build/images'));
});

gulp.task('_copyTestPrism', ['_cleanTestAssets', '_otherAssets'], function() {
  return src('build/syntax-highlighting/**/*')
    .pipe(gulp.dest('./test/css/build/syntax-highlighting'));
});

gulp.task('_copyTestStyleguideAssets', ['_cleanTestAssets', '_otherAssets'], function() {
  return src('build/styleguide/github.css')
    .pipe(gulp.dest('./test/css/build/styleguide'));
});

<|endoftext|>


<commit_before>var debug = require('debug')('oauth');

var router = require('express').Router();

var key = process.env.TRELLO_KEY;
var secret = process.env.TRELLO_SECRET;

var appName = 'RUDoneYet';

var OAuth = (require("oauth")).OAuth;
var requestUrl = "https://trello.com/1/OAuthGetRequestToken";
var accessUrl = "https://trello.com/1/OAuthGetAccessToken";
var authorizeUrl = "https://trello.com/1/OAuthAuthorizeToken";

var loginCallback;
var oauth;

var login = (request, response) => {

  loginCallback = 'http://' + request.headers.host + '/callback';
  debug('Callback: ' + loginCallback);
  oauth = new OAuth(requestUrl, accessUrl, key, secret, "1.0", loginCallback, "HMAC-SHA1");

  oauth.getOAuthRequestToken(function (error, token, tokenSecret, results) {

    if (error) {
      debug('Error calling getOAuthRequestToken: ' + error);
      response.status(500).send(error);
      return;
    }

    request.session.requestTokenSecret = tokenSecret;

    response.redirect(authorizeUrl + "?oauth_token=" + token + "&scope=read,write&expiration=never&name=" + appName);

  });

};

var callback = (request, response) => {

  var requestToken = request.query.oauth_token;
  var verifier = request.query.oauth_verifier;

  oauth.getOAuthAccessToken(requestToken, request.session.requestTokenSecret, verifier, function (error, accessToken, accessTokenSecret, results) {

    if (error) {
      response.status(500).send(error);
      return;
    }

    request.session.requestToken = requestToken;
    request.session.accessToken = accessToken;
    request.session.accessTokenSecret = accessTokenSecret;

    response.redirect('/');

  });

};

router.get('/callback', callback);

router.get('/login', login);

export default router;
<commit_msg>Add additional logging for debugging oauth<commit_after>var debug = require('debug')('oauth');

var router = require('express').Router();

var key = process.env.TRELLO_KEY;
var secret = process.env.TRELLO_SECRET;

var appName = 'RUDoneYet';

var OAuth = (require("oauth")).OAuth;
var requestUrl = "https://trello.com/1/OAuthGetRequestToken";
var accessUrl = "https://trello.com/1/OAuthGetAccessToken";
var authorizeUrl = "https://trello.com/1/OAuthAuthorizeToken";

var loginCallback;
var oauth;

var login = (request, response) => {

  loginCallback = 'http://' + request.headers.host + '/callback';
  debug('Callback: ' + loginCallback);
  oauth = new OAuth(requestUrl, accessUrl, key, secret, "1.0", loginCallback, "HMAC-SHA1");

  oauth.getOAuthRequestToken(function (error, token, tokenSecret, results) {

    if (error) {
      debug('Error calling getOAuthRequestToken: ' + require('util').inspect(error));
      response.status(500).send(error);
      return;
    }

    request.session.requestTokenSecret = tokenSecret;

    response.redirect(authorizeUrl + "?oauth_token=" + token + "&scope=read,write&expiration=never&name=" + appName);

  });

};

var callback = (request, response) => {

  var requestToken = request.query.oauth_token;
  var verifier = request.query.oauth_verifier;

  oauth.getOAuthAccessToken(requestToken, request.session.requestTokenSecret, verifier, function (error, accessToken, accessTokenSecret, results) {

    if (error) {
      response.status(500).send(error);
      return;
    }

    request.session.requestToken = requestToken;
    request.session.accessToken = accessToken;
    request.session.accessTokenSecret = accessTokenSecret;

    response.redirect('/');

  });

};

router.get('/callback', callback);

router.get('/login', login);

export default router;
<|endoftext|>


<commit_before>//initialize all of our variables
var app, base, gulp, gutil, runSequence, shell, build_deps, path, through2, File, fs, run;

//load all of our dependencies
//add more here if you want to include more libraries
gulp          = require('gulp');
gutil         = require('gulp-util');
File          = gutil.File;
path          = require('path');
through2      = require('through2');
runSequence   = require('run-sequence');
shell         = require('gulp-shell');
fs            = require('fs');
run           = require('gulp-run');

gulp.task('write-deps', function () {
  return build_deps.parse_configs();
});

gulp.task('bundle-deps', function () {
  return build_deps.write_deps();
});

function string_buffer(filename, buffer) {
  var src = require('stream').Readable({ objectMode: true })
  src._read = function () {
    this.push(new gutil.File({ cwd: "", base: "", path: filename, contents: buffer}))
    this.push(null)
  }
  return src
}

build_deps = {
  retailers: [],
  parse_configs: function () {
    return gulp.src('./configs/*.json')
      .pipe(this.build_deps())
      .pipe(gulp.dest('./dependencies/'));
  },

  build_deps: function() {
    var self = this;
    return through2.obj(function(file, encoding, done) {
      var filename = path.basename(file.path);
      var config = require('./configs/' + filename);

      self.current_retailer = self.get_retailer(filename);
      var dep_string = self.get_deps(config);

      var target_name = self.get_dep_filename(filename);
      var dep = new File({ cwd: "", base: "", path: target_name, contents: new Buffer(dep_string) });
      done(null, dep);
    });
  },

  get_deps: function (config) {
    var components = config.components,
        import_strings = "",
        exports = [];
        self = this;
    components.forEach(function (obj) {
      var str = self.get_export_string(obj);
      if (str.length === 0) { return; }
      import_strings += str;
      exports.push(self.capitalize(obj));
    });

    var export_string = 'export { ' + exports.join(', ') + ' };';
    import_strings += '\n\n' + export_string;

    return import_strings;
  },

  capitalize: function (string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  },

  get_export_string: function (component) {
    var component_path = this.get_component_path(component)
    if (!component_path) { return '';}
    return "import " + this.capitalize(component) + " from '" + component_path + "';\n";
  },

  get_component_path: function (component) {
    var init_path = 'app/components/'
    var fullpath = init_path + component + '/retailers/' + this.current_retailer + '/' + component;
    var basepath = init_path + component + '/' + component;

    if(fs.existsSync(fullpath + '.js')) {
      return fullpath;
    } else if (fs.existsSync(basepath + '.js')) {
      return basepath;
    } else {
      console.log('Missing component file for component: ' + component + ', path: ' + basepath);
      return false;
    }
  },

  get_retailer: function (filename) {
    var reg = /^(configs|dependencies)\.(\w+?).js(on)?$/
    return reg.exec(filename)[2];
  },

  get_dep_filename: function (filename) {
    return 'dependencies.' + this.current_retailer + '.js';
  },

  write_deps: function () {
    var ret = {ret: null, comp: null}
    return gulp.src('./dependencies/*', {passthrough: true})
      .pipe(this.set_current_retailer(ret))
      .pipe(this.bundle_deps(ret))
      .pipe(this.bundle(ret))
  },

  set_current_retailer: function(ret) {
    var self = this;
    return through2.obj(function(file, encoding, done) {
      var filename = path.basename(file.path);

      self.current_retailer = self.get_retailer(filename);
      ret.ret = self.current_retailer;

      done(null, file);
    });
  },

  bundle_deps: function(ret) {
    var self = this;
    return through2.obj(function(file, encoding, done) {
      var filename = path.basename(file.path);

      self.current_retailer = self.get_retailer(filename);
      // self.current_retailer = self.get_retailer(filename);
      // var dep_string = self.get_deps(config);

      var target_name = 'components.js'
      ret.comp = file.contents;
      var dep = new File({ cwd: "", base: "", path: target_name, contents: file.contents });
      done(null, dep);
    });
  },

  bundle: function(retailer) {
    var self = this;
    return through2.obj(function(file, encoding, done) {
      var filename = path.basename(file.path);

      // Add current retailer to the list of retailers
      // We will use that to build all the bundles at the end
      self.retailers.push(retailer.ret);

      // Freeze retailer's reference to be used in our task callback
      // where the initial retailer.ret reference will have already changed
      var frozenRetailer = retailer.ret;

      // Write components.js to disk, with the specific retailer version
      gulp.task('write-component-' + frozenRetailer, function () {
        return string_buffer(filename, file.contents).pipe(gulp.dest('app/'));
      });

      // Bundle a specific retailer version
      // Along with all their specific components
      gulp.task('build-' + frozenRetailer, function () {
        return run('jspm bundle app/app build.' + frozenRetailer + '.js').exec();
      });

      done(null, file);
    });
  }
};

// Build an array of tasks to altenatively
// write each component file
// and bundle each retailer app
gulp.task('build-all', function () {
  var build_tasks = build_deps.retailers.reduce(function (tasks, retailer) {
    tasks.push('write-component-' + retailer);
    tasks.push('build-' + retailer);
    return tasks;
  }, []);

  // Run all tasks sequentially
  runSequence.apply(null, build_tasks);
});

gulp.task('build-deps', function () {
  runSequence('write-deps', 'bundle-deps', 'build-all');
});
<commit_msg>SF-6288 - Allow to build a sass import file<commit_after>//initialize all of our variables
var app, base, gulp, gutil, runSequence, shell, path, through2, File, fs, run, lazypipe;
var build_deps, build_sass;

//load all of our dependencies
//add more here if you want to include more libraries
gulp          = require('gulp');
gutil         = require('gulp-util');
File          = gutil.File;
path          = require('path');
through2      = require('through2');
runSequence   = require('run-sequence');
shell         = require('gulp-shell');
fs            = require('fs');
run           = require('gulp-run');
lazypipe      = require('lazypipe');

gulp.task('write-deps', function () {
  return build_deps.parse_configs();
});

gulp.task('bundle-deps', function () {
  return build_deps.write_deps();
});

// Wrapper to write to file within a stream
function string_buffer(filename, buffer) {
  var src = require('stream').Readable({ objectMode: true })
  src._read = function () {
    this.push(new gutil.File({ cwd: "", base: "", path: filename, contents: buffer}))
    this.push(null)
  }
  return src
}

// White label components build process

build_deps = {
  retailers: [],
  parse_configs: function () {
    return gulp.src('./configs/*.json')
      .pipe(this.build_deps())
      .pipe(gulp.dest('./dependencies/'));
  },

  build_deps: function() {
    var self = this;
    return through2.obj(function(file, encoding, done) {
      var filename = path.basename(file.path);
      var config = require('./configs/' + filename);

      self.current_retailer = self.get_retailer(filename);
      var dep_string = self.get_deps(config);

      var target_name = self.get_dep_filename(filename);
      var dep = new File({ cwd: "", base: "", path: target_name, contents: new Buffer(dep_string) });
      done(null, dep);
    });
  },

  get_deps: function (config) {
    var components = config.components,
        import_strings = "",
        exports = [];
        self = this;
    components.forEach(function (obj) {
      var str = self.get_export_string(obj);
      if (str.length === 0) { return; }
      import_strings += str;
      exports.push(self.capitalize(obj));
    });

    var export_string = 'export { ' + exports.join(', ') + ' };';
    import_strings += '\n\n' + export_string;

    return import_strings;
  },

  capitalize: function (string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  },

  get_export_string: function (component) {
    var component_path = this.get_component_path(component)
    if (!component_path) { return '';}
    return "import " + this.capitalize(component) + " from '" + component_path + "';\n";
  },

  get_component_path: function (component) {
    var init_path = 'app/components/'
    var fullpath = init_path + component + '/retailers/' + this.current_retailer + '/' + component;
    var basepath = init_path + component + '/' + component;

    if(fs.existsSync(fullpath + '.js')) {
      return fullpath;
    } else if (fs.existsSync(basepath + '.js')) {
      return basepath;
    } else {
      console.log('Missing component file for component: ' + component + ', path: ' + basepath);
      return false;
    }
  },

  get_retailer: function (filename) {
    var reg = /^(configs|dependencies)\.(\w+?).js(on)?$/
    return reg.exec(filename)[2];
  },

  get_dep_filename: function (filename) {
    return 'dependencies.' + this.current_retailer + '.js';
  },

  write_deps: function () {
    var ret = {ret: null, comp: null}
    return gulp.src('./dependencies/*', {passthrough: true})
      .pipe(this.set_current_retailer(ret))
      .pipe(this.bundle_deps(ret))
      .pipe(this.bundle(ret))
  },

  set_current_retailer: function(ret) {
    var self = this;
    return through2.obj(function(file, encoding, done) {
      var filename = path.basename(file.path);

      self.current_retailer = self.get_retailer(filename);
      ret.ret = self.current_retailer;

      done(null, file);
    });
  },

  bundle_deps: function(ret) {
    var self = this;
    return through2.obj(function(file, encoding, done) {
      var filename = path.basename(file.path);

      self.current_retailer = self.get_retailer(filename);
      // self.current_retailer = self.get_retailer(filename);
      // var dep_string = self.get_deps(config);

      var target_name = 'components.js'
      ret.comp = file.contents;
      var dep = new File({ cwd: "", base: "", path: target_name, contents: file.contents });
      done(null, dep);
    });
  },

  bundle: function(retailer) {
    var self = this;
    return through2.obj(function(file, encoding, done) {
      var filename = path.basename(file.path);

      // Add current retailer to the list of retailers
      // We will use that to build all the bundles at the end
      self.retailers.push(retailer.ret);

      // Freeze retailer's reference to be used in our task callback
      // where the initial retailer.ret reference will have already changed
      var frozenRetailer = retailer.ret;

      // Write components.js to disk, with the specific retailer version
      gulp.task('write-component-' + frozenRetailer, function () {
        return string_buffer(filename, file.contents).pipe(gulp.dest('app/'));
      });

      // Bundle a specific retailer version
      // Along with all their specific components
      gulp.task('build-' + frozenRetailer, function () {
        return run('jspm bundle app/app build.' + frozenRetailer + '.js').exec();
      });

      done(null, file);
    });
  }
};

// Build an array of tasks to altenatively
// write each component file
// and bundle each retailer app
gulp.task('build-all', function () {
  var build_tasks = build_deps.retailers.reduce(function (tasks, retailer) {
    tasks.push('write-component-' + retailer);
    tasks.push('build-' + retailer);
    return tasks;
  }, []);

  // Run all tasks sequentially
  runSequence.apply(null, build_tasks);
});

gulp.task('build-deps', function () {
  runSequence('write-deps', 'bundle-deps', 'build-all');
});

build_sass = {

  // Get scss base component path
  // And the path for each retailer's component
  paths: {
    'base': 'app/components/*/*.scss',
    retailer: function (retailer) {
      return 'app/components/*/retailers/' + retailer + '/*.scss'
    },
    get: function (path) {
      if (this[path]) { return this[path]; }
      else { return this.retailer(path); }
    }
  },

  // Returns a lazypipe to build the sass
  // imports for a given retailer
  build_sass_pipe: function (retailer) {
    return lazypipe()
      .pipe(gulp.src, this.paths.get(retailer))
      .pipe(this.gather_imports, this)
      .pipe(this.build_imports, this)
      .pipe(gulp.dest, './')
  },

  // Getter for a given sass lazypipe
  sass_pipe: {},
  get_sass_pipe: function (retailer) {
    if (this.sass_pipe[retailer] == null) {
      this.sass_pipe[retailer] = this.build_sass_pipe(retailer);
    }
    return this.sass_pipe[retailer];
  },

  // Gather import strings necessary for current build
  // and concatenate them in one string
  import_strings: '',
  gather_imports: function (self) {
    return through2.obj(function(file, encoding, done) {

      var filepath = self.get_component_filepath(file);
      self.import_strings += "@import " + filepath + ";\n";

      done(null, file);
    });
  },

  // Get the component path to import from
  get_component_filepath: function (file) {
    var filename = path.basename(file.path);
    var pattern = 'components/'
    return file.path.slice(file.path.search(pattern) + pattern.length);
  },

  // Build the final sass imports file
  build_imports: function (self) {
    return through2.obj(function(file, encoding, done) {

      var target_name = 'app/components/components.scss'
      var imports = new File({ cwd: "", base: "", path: target_name, contents: new Buffer(self.import_strings) });

      done(null, imports);
    });
  },

  // Execute the given sass lazypipe
  sass_task: function (retailer) {
    return this.get_sass_pipe(retailer)();
  }
};

gulp.task('sass-base', function () {
  return build_sass.sass_task('base');
});

gulp.task('sass-bru', function () {
  return build_sass.sass_task('bru');
});

gulp.task('sass-sw', function () {
  return build_sass.sass_task('sw');
});

gulp.task('sass-immu', function () {
  return build_sass.sass_task('immu');
});

gulp.task('sass-bru-base', function () {
  runSequence('sass-base', 'sass-bru');
});

gulp.task('sass-immu-base', function () {
  runSequence('sass-base', 'sass-immu');
});

gulp.task('sass-sw-base', function () {
  runSequence('sass-base', 'sass-sw');
});

<|endoftext|>


<commit_before>/* jshint node:true*/
'use strict';

var request = require('request'),
     Canvas = require('canvas'),
         fs = require('fs');

module.exports = function(app) {
  app.post('/createProfilePhoto',     createProfile);
  app.post('/createCoverPhoto',       createCover);
  app.get('/solarized/profile/:name', getProfile);
  app.get('/solarized/cover/:name',   getCover);
};

function getProfile(req, res) {
  // maybe check id right here
  var url = 'solarized/profile/' + req.params.name;
  res.sendfile(url);
}

function getCover(req, res) {
  // maybe check id right here
  var url = 'solarized/cover/' + req.params.name;
  res.sendfile(url);
}

function createProfile(req, res) {
  // maybe check id right here

  var file = process.cwd() + '/solarized/profile/' + req.body.id + '.jpg';
  var ws = fs.createWriteStream(file);

  request(req.body.url).pipe(ws);

  ws.on('close', function () {
    _solarizeProfile(file, function (err) {
      if (err) {
        res.send({
          success: false,
          err: err
        });
      } else {
        res.send({
          success: true,
          url: '/solarized/profile/' + req.body.id + '.jpg'
        });
      }
    });
  });
}

function createCover(req, res) {
  // maybe check id right here

  var file = process.cwd() + '/solarized/cover/' + req.body.id + '.jpg';
  var ws = fs.createWriteStream(file);

  request(req.body.url).pipe(ws);

  ws.on('close', function () {
    _solarizeCover(file, req.body.offset, function (err) {
      if (err) {
        res.send({
          success: false,
          err: err
        });
      } else {
        res.send({
          success: true,
          url: '/solarized/cover/' + req.body.id + '.jpg'
        });
      }
    });
  });
}

function _solarizeProfile(file, cb) {
  fs.readFile(file, function (err, pic) {
    if (err) return cb(err);
    var img = new Canvas.Image();

    img.onload = function () {
      var canvas  = new Canvas(img.width, img.height);
      var ctx     = canvas.getContext('2d');
      var logo    = new Canvas.Image();
      logo.onload = function () {
        ctx.drawImage(img, 0, 0, img.width, img.height);
        ctx.drawImage(logo, img.width - (logo.width + 10), img.height - (logo.height + 10), logo.width, logo.height);
        _saveCanvas(canvas, file, function (err) {
          if (err) return cb (err);
          cb();
        });
      };

      logo.src = process.cwd() + '/solarized/logo.png';
    };

    img.src = pic;
  });
}

function _solarizeCover(file, offset, cb) {
  fs.readFile(file, function (err, pic) {
    if (err) return cb(err);
    var img = new Canvas.Image();

    img.onload = function () {
      var canvas  = new Canvas(853, 316);
      var ctx     = canvas.getContext('2d');
      var logo    = new Canvas.Image();
	  var newheight = 853 * img.height / img.width;
	  var newoffset = (offset * newheight / img.height) + 20;
      logo.onload = function () {
        ctx.drawImage(img, 0, -newoffset, 853, newheight);
        ctx.drawImage(logo, 0, 210, 853, logo.height);
        _saveCanvas(canvas, file, function (err) {
          if (err) return cb (err);
          cb();
        });
      };

      logo.src = process.cwd() + '/solarized/cover-logo.png';
    };

    img.src = pic;
  });
}

function _saveCanvas(canvas, file, cb) {
  var out = fs.createWriteStream(file);
  var stream = canvas.jpegStream({
    quality : 100
  });

  stream.pipe(out);

  out.on('open', function () {
    cb(null);
  });
}
<commit_msg>correct dimensions<commit_after>/* jshint node:true*/
'use strict';

var request = require('request'),
     Canvas = require('canvas'),
         fs = require('fs');

module.exports = function(app) {
  app.post('/createProfilePhoto',     createProfile);
  app.post('/createCoverPhoto',       createCover);
  app.get('/solarized/profile/:name', getProfile);
  app.get('/solarized/cover/:name',   getCover);
};

function getProfile(req, res) {
  // maybe check id right here
  var url = 'solarized/profile/' + req.params.name;
  res.sendfile(url);
}

function getCover(req, res) {
  // maybe check id right here
  var url = 'solarized/cover/' + req.params.name;
  res.sendfile(url);
}

function createProfile(req, res) {
  // maybe check id right here

  var file = process.cwd() + '/solarized/profile/' + req.body.id + '.jpg';
  var ws = fs.createWriteStream(file);

  request(req.body.url).pipe(ws);

  ws.on('close', function () {
    _solarizeProfile(file, function (err) {
      if (err) {
        res.send({
          success: false,
          err: err
        });
      } else {
        res.send({
          success: true,
          url: '/solarized/profile/' + req.body.id + '.jpg'
        });
      }
    });
  });
}

function createCover(req, res) {
  // maybe check id right here

  var file = process.cwd() + '/solarized/cover/' + req.body.id + '.jpg';
  var ws = fs.createWriteStream(file);

  request(req.body.url).pipe(ws);

  ws.on('close', function () {
    _solarizeCover(file, req.body.offset, function (err) {
      if (err) {
        res.send({
          success: false,
          err: err
        });
      } else {
        res.send({
          success: true,
          url: '/solarized/cover/' + req.body.id + '.jpg'
        });
      }
    });
  });
}

function _solarizeProfile(file, cb) {
  fs.readFile(file, function (err, pic) {
    if (err) return cb(err);
    var img = new Canvas.Image();

    img.onload = function () {
      var canvas  = new Canvas(img.width, img.height);
      var ctx     = canvas.getContext('2d');
      var logo    = new Canvas.Image();
      logo.onload = function () {
        ctx.drawImage(img, 0, 0, img.width, img.height);
        ctx.drawImage(logo, img.width - (logo.width + 10), img.height - (logo.height + 10), logo.width, logo.height);
        _saveCanvas(canvas, file, function (err) {
          if (err) return cb (err);
          cb();
        });
      };

      logo.src = process.cwd() + '/solarized/logo.png';
    };

    img.src = pic;
  });
}

function _solarizeCover(file, offset, cb) {
  fs.readFile(file, function (err, pic) {
    if (err) return cb(err);
    var img = new Canvas.Image();

    img.onload = function () {
      var canvas  = new Canvas(851, 315);
      var ctx     = canvas.getContext('2d');
      var logo    = new Canvas.Image();
	  var newheight = 851 * img.height / img.width;
	  var newoffset = (offset * newheight / img.height);
      logo.onload = function () {
        ctx.drawImage(img, 0, -newoffset, 851, newheight);
        ctx.drawImage(logo, 0, 210, 851, logo.height);
        _saveCanvas(canvas, file, function (err) {
          if (err) return cb (err);
          cb();
        });
      };

      logo.src = process.cwd() + '/solarized/cover-logo.png';
    };

    img.src = pic;
  });
}

function _saveCanvas(canvas, file, cb) {
  var out = fs.createWriteStream(file);
  var stream = canvas.jpegStream({
    quality : 100
  });

  stream.pipe(out);

  out.on('open', function () {
    cb(null);
  });
}
<|endoftext|>


<commit_before>
require('babel/register');

var _ = require('lodash');

var gulp = require('gulp');
var del = require('del');
var source = require('vinyl-source-stream');
var vinylPaths = require('vinyl-paths');
var browserify = require('browserify');
var babelify = require('babelify');
var errorify = require('errorify');
var watchify = require('watchify');
var fs = require('fs');
var execSync = require('child_process').execSync;

var git = require('gulp-git');
var util = require('gulp-util');
var open = require('gulp-open');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var minifyCss = require('gulp-minify-css');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var jade = require('gulp-jade');
var sourcemaps = require('gulp-sourcemaps');
var connect = require('gulp-connect');
var gulpif = require('gulp-if');
var ghPages = require('gulp-gh-pages');
var bump = require('gulp-bump');
var tagVersion = require('gulp-tag-version');
var filter = require('gulp-filter');
var ngAnnotate = require('gulp-ng-annotate');
var uncss = require('gulp-uncss');
var eslint = require('gulp-eslint');
var autoprefixer = require('gulp-autoprefixer');
var cached = require('gulp-cached');
var remember = require('gulp-remember');
var mocha = require('gulp-mocha');
var changelog = require('conventional-changelog');
var nwBuilder = require('gulp-nw-builder');
var zip = require('gulp-zip');
var folders = require('gulp-folders');
var release = require('gulp-github-release');
var packageJson = require('./package.json');

var watching = false;

var getPaths = function() {
  return JSON.parse(fs.readFileSync('./package.json')).gulp;
};

gulp.task('deploy', function() {
  var paths = getPaths();

  return gulp.src(paths.dist + '/(css|js|favicon.ico|index.html)')
    .pipe(ghPages());
});

gulp.task('clean', function() {
  var paths = getPaths();

  return gulp.src(paths.dist)
    .pipe(vinylPaths(del))
    .on('error', util.log);
});

gulp.task('copy:favicon', ['clean'], function() {
  var paths = getPaths();

  return gulp.src(paths.favicon)
    .pipe(gulp.dest(paths.dist))
    .on('error', util.log);
});

gulp.task('build:libcss', ['clean', 'compile:jade', 'compile:sass'], function() {
  var paths = getPaths();

  return gulp.src(paths.libcss)
    //.pipe(cached('libcss'))
    //.pipe(remember('libcss'))
    .pipe(concat('lib.min.css'))
    /*.pipe(uncss({
      html: paths.dist + 'index.html'
    }))*/
    .pipe(minifyCss({
      keepSpecialComments: false,
      removeEmpty: true
    }))
    .pipe(gulp.dest(paths.dist + 'css'))
    .on('error', util.log);
});

gulp.task('build:libjs', ['clean'], function() {
  var paths = getPaths();

  return gulp.src(paths.libjs)
    //.pipe(cached('libjs'))
    //.pipe(remember('libjs'))
    //.pipe(gulpif(!watching, uglify({ outSourceMaps: false })))
    .pipe(concat('lib.min.js'))
    .pipe(gulp.dest(paths.dist + 'js'))
    .on('error', util.log);
});

gulp.task('compile:js', ['eslint', 'clean'], function() {
  var paths = getPaths();

  var bundler = browserify({
    cache: {}, packageCache: {}, fullPaths: true,
    entries: [paths.entry],
    debug: watching
  })
    .transform(babelify);

  if(watching) {
    bundler.plugin(errorify);
  }

  var bundlee = function() {
    return bundler
      .bundle()
      .pipe(source('js/main.min.js'))
      //.pipe(gulpif(!watching, uglify({ outSourceMaps: false })))
      .pipe(ngAnnotate())
      .pipe(gulp.dest(paths.dist))
      .on('error', util.log);
  };

  if (watching) {
    bundler = watchify(bundler);
    bundler.on('update', bundlee);
  }

  return bundlee();
});

gulp.task('eslint', function() {
  var paths = getPaths();

  return gulp.src(paths.js)
    .pipe(eslint({ useEslintrc: true }))
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('compile:sass', ['clean', 'compile:jade'], function() {
  var paths = getPaths();

  return gulp.src(paths.sass)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('css/main.css'))
    /*.pipe(uncss({
      html: paths.dist + 'index.html'
    }))*/
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gulpif(!watching, minifyCss({
      keepSpecialComments: false,
      removeEmpty: true
    })))
    .pipe(rename({ suffix: '.min' }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.dist))
    .on('error', util.log);
});

gulp.task('compile:jade', ['clean'], function() {
  var paths = getPaths();

  return gulp.src(paths.jade)
    .pipe(concat('index.html'))
    .pipe(jade({
      pretty: watching
    }))
    .pipe(gulp.dest(paths.dist))
    .on('error', util.log);
});

gulp.task('reload', ['build'], function() {
  return gulp.src('dist/*.html')
    .pipe(connect.reload())
    .on('error', util.log);
});

gulp.task('connect', function() {
  connect.server({
    root: ['./dist'],
    port: 8000,
    livereload: true
  });
});

gulp.task('open', ['build'], function() {
  gulp.src('./dist/index.html')
    .pipe(open({
      uri: 'http://127.0.0.1:8000'
    }));
});

gulp.task('watch', function() {
  var paths = getPaths();

  watching = true;
  return gulp.watch([paths.sass, paths.jade, paths.js, 'package.json'], ['reload']);
});

var versionSources = ['./bower.json', './package.json'];

var versionStream = function(type) {
  return gulp.src(versionSources)
    .pipe(bump({ type: type }))
    .pipe(gulp.dest('./'))
    .pipe(filter('package.json'))
    .pipe(tagVersion({ prefix: 'v' }));
};

var commitStream = function(type) {
  var tag = execSync('git describe --abbrev=0').toString().trim();
  return gulp.src(versionSources)
    .pipe(git.commit('chore(version): release '+type+ ' version ' +tag, { args: '-a' }, function() {
      git.push();
      git.push('origin', 'master', { args: '--tags' });
    }));
};

var pushStream = function() {
  git.push();
  git.push('origin', 'master', { args: '--tags' });
};

gulp.task('bump:patch:tag', function() {
  return versionStream('patch');
});

gulp.task('bump:minor:tag', function() {
  return versionStream('minor');
});

gulp.task('bump:major:tag', function() {
  return versionStream('major');
});

gulp.task('bump:patch:commit', ['bump:patch:tag', 'generate:changelog'], function() {
  return commitStream('patch') && pushStream();
});

gulp.task('bump:minor:commit', ['bump:minor:tag', 'generate:changelog'], function() {
  return commitStream('minor') && pushStream();
});

gulp.task('bump:major:commit', ['bump:major:tag', 'generate:changelog'], function() {
  return commitStream('major') && pushStream();
});

gulp.task('generate:changelog', function() {
  return changelog({
    releaseCount: 0,
    preset: 'angular' /*,
    transform: function(commit, cb) {
      console.log(commit);
      if(_.contains(commit.header, ['bump'])) return cb(null);
      return cb(null, commit);
    }*/
  })
    .pipe(fs.createWriteStream('CHANGELOG.md'));
});

gulp.task('copy:nw', function() {
  var paths = getPaths();

  return gulp.src(['./package.json', 'nw-setup/**/*'])
    .pipe(gulp.dest(paths.dist))
    .on('error', util.log);
});

gulp.task('generate:binaries', ['clean:binaries', 'copy:nw'], function() {
  execSync('npm install --prefix ./dist/ express');
  var paths = getPaths();

  return gulp.src(paths.dist+'/**/*')
    .pipe(nwBuilder({
      version: 'v0.12.2',
      platforms: ['osx64', 'win64', 'linux64'],
      appName: packageJson.name,
      appVersion: packageJson.version,
      buildDir: './bin-build',
      cacheDir: './bin-cache',
      macIcns: './favicon.icns',
      winIco: './favicon.ico'
    }));
});

gulp.task('clean:binaries', function() {
  return gulp.src(['./bin-build', './bin-release'])
    .pipe(vinylPaths(del))
    .on('error', util.log);
});

var binaryPath = './bin-build/OpenChallenge';
gulp.task('package:binaries', ['generate:binaries'], folders(binaryPath, function(folder) {
  return gulp.src(binaryPath + '/' + folder + '/**/*')
    .pipe(zip(folder + '.zip'))
    .pipe(gulp.dest('./bin-release'));
}));

gulp.task('upload:binaries', ['package:binaries'], function() {
  return gulp.src('./bin-release/*.zip')
    .pipe(release({
      repo: 'openchallenge',
      owner: 'seiyria',
      manifest: packageJson
    }));
});

gulp.task('test', function() {
  var paths = getPaths();

  gulp.src(paths.testjs)
    .pipe(mocha());
});

gulp.task('bump:patch', ['bump:patch:tag', 'bump:patch:commit']);
gulp.task('bump:minor', ['bump:minor:tag', 'bump:minor:commit']);
gulp.task('bump:major', ['bump:major:tag', 'bump:major:commit']);

gulp.task('release:patch', ['bump:patch', 'upload:binaries']);
gulp.task('release:minor', ['bump:minor', 'upload:binaries']);
gulp.task('release:major', ['bump:major', 'upload:binaries']);

gulp.task('default', ['build', 'connect', 'open', 'watch']);
gulp.task('build', ['clean', 'copy:favicon', 'build:libjs', 'build:libcss', 'compile']);
gulp.task('compile', ['compile:js', 'compile:sass', 'compile:jade']);
gulp.task('check', ['test', 'build']);
<commit_msg>updating gulpfile to commit changelog as part of release<commit_after>
require('babel/register');

var _ = require('lodash');

var gulp = require('gulp');
var del = require('del');
var source = require('vinyl-source-stream');
var vinylPaths = require('vinyl-paths');
var browserify = require('browserify');
var babelify = require('babelify');
var errorify = require('errorify');
var watchify = require('watchify');
var fs = require('fs');
var execSync = require('child_process').execSync;

var git = require('gulp-git');
var util = require('gulp-util');
var open = require('gulp-open');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var minifyCss = require('gulp-minify-css');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var jade = require('gulp-jade');
var sourcemaps = require('gulp-sourcemaps');
var connect = require('gulp-connect');
var gulpif = require('gulp-if');
var ghPages = require('gulp-gh-pages');
var bump = require('gulp-bump');
var tagVersion = require('gulp-tag-version');
var filter = require('gulp-filter');
var ngAnnotate = require('gulp-ng-annotate');
var uncss = require('gulp-uncss');
var eslint = require('gulp-eslint');
var autoprefixer = require('gulp-autoprefixer');
var cached = require('gulp-cached');
var remember = require('gulp-remember');
var mocha = require('gulp-mocha');
var changelog = require('conventional-changelog');
var nwBuilder = require('gulp-nw-builder');
var zip = require('gulp-zip');
var folders = require('gulp-folders');
var release = require('gulp-github-release');
var packageJson = require('./package.json');

var watching = false;

var getPaths = function() {
  return JSON.parse(fs.readFileSync('./package.json')).gulp;
};

gulp.task('deploy', function() {
  var paths = getPaths();

  return gulp.src(paths.dist + '/(css|js|favicon.ico|index.html)')
    .pipe(ghPages());
});

gulp.task('clean', function() {
  var paths = getPaths();

  return gulp.src(paths.dist)
    .pipe(vinylPaths(del))
    .on('error', util.log);
});

gulp.task('copy:favicon', ['clean'], function() {
  var paths = getPaths();

  return gulp.src(paths.favicon)
    .pipe(gulp.dest(paths.dist))
    .on('error', util.log);
});

gulp.task('build:libcss', ['clean', 'compile:jade', 'compile:sass'], function() {
  var paths = getPaths();

  return gulp.src(paths.libcss)
    //.pipe(cached('libcss'))
    //.pipe(remember('libcss'))
    .pipe(concat('lib.min.css'))
    /*.pipe(uncss({
      html: paths.dist + 'index.html'
    }))*/
    .pipe(minifyCss({
      keepSpecialComments: false,
      removeEmpty: true
    }))
    .pipe(gulp.dest(paths.dist + 'css'))
    .on('error', util.log);
});

gulp.task('build:libjs', ['clean'], function() {
  var paths = getPaths();

  return gulp.src(paths.libjs)
    //.pipe(cached('libjs'))
    //.pipe(remember('libjs'))
    //.pipe(gulpif(!watching, uglify({ outSourceMaps: false })))
    .pipe(concat('lib.min.js'))
    .pipe(gulp.dest(paths.dist + 'js'))
    .on('error', util.log);
});

gulp.task('compile:js', ['eslint', 'clean'], function() {
  var paths = getPaths();

  var bundler = browserify({
    cache: {}, packageCache: {}, fullPaths: true,
    entries: [paths.entry],
    debug: watching
  })
    .transform(babelify);

  if(watching) {
    bundler.plugin(errorify);
  }

  var bundlee = function() {
    return bundler
      .bundle()
      .pipe(source('js/main.min.js'))
      //.pipe(gulpif(!watching, uglify({ outSourceMaps: false })))
      .pipe(ngAnnotate())
      .pipe(gulp.dest(paths.dist))
      .on('error', util.log);
  };

  if (watching) {
    bundler = watchify(bundler);
    bundler.on('update', bundlee);
  }

  return bundlee();
});

gulp.task('eslint', function() {
  var paths = getPaths();

  return gulp.src(paths.js)
    .pipe(eslint({ useEslintrc: true }))
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('compile:sass', ['clean', 'compile:jade'], function() {
  var paths = getPaths();

  return gulp.src(paths.sass)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('css/main.css'))
    /*.pipe(uncss({
      html: paths.dist + 'index.html'
    }))*/
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gulpif(!watching, minifyCss({
      keepSpecialComments: false,
      removeEmpty: true
    })))
    .pipe(rename({ suffix: '.min' }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.dist))
    .on('error', util.log);
});

gulp.task('compile:jade', ['clean'], function() {
  var paths = getPaths();

  return gulp.src(paths.jade)
    .pipe(concat('index.html'))
    .pipe(jade({
      pretty: watching
    }))
    .pipe(gulp.dest(paths.dist))
    .on('error', util.log);
});

gulp.task('reload', ['build'], function() {
  return gulp.src('dist/*.html')
    .pipe(connect.reload())
    .on('error', util.log);
});

gulp.task('connect', function() {
  connect.server({
    root: ['./dist'],
    port: 8000,
    livereload: true
  });
});

gulp.task('open', ['build'], function() {
  gulp.src('./dist/index.html')
    .pipe(open({
      uri: 'http://127.0.0.1:8000'
    }));
});

gulp.task('watch', function() {
  var paths = getPaths();

  watching = true;
  return gulp.watch([paths.sass, paths.jade, paths.js, 'package.json'], ['reload']);
});

var versionSources = ['./bower.json', './package.json'];

var versionStream = function(type) {
  return gulp.src(versionSources)
    .pipe(bump({ type: type }))
    .pipe(gulp.dest('./'))
    .pipe(filter('package.json'))
    .pipe(tagVersion({ prefix: 'v' }));
};

var commitStream = function(type) {
  var tag = execSync('git describe --abbrev=0').toString().trim();
  return gulp.src(versionSources.concat('CHANGELOG.md'))
    .pipe(git.commit('chore(version): release '+type+ ' version ' +tag, function() {
      git.push();
      git.push('origin', 'master', { args: '--tags' });
    }));
};

var pushStream = function() {
  git.push();
  git.push('origin', 'master', { args: '--tags' });
};

gulp.task('bump:patch:tag', function() {
  return versionStream('patch');
});

gulp.task('bump:minor:tag', function() {
  return versionStream('minor');
});

gulp.task('bump:major:tag', function() {
  return versionStream('major');
});

gulp.task('bump:patch:commit', ['bump:patch:tag', 'generate:changelog'], function() {
  return commitStream('patch') && pushStream();
});

gulp.task('bump:minor:commit', ['bump:minor:tag', 'generate:changelog'], function() {
  return commitStream('minor') && pushStream();
});

gulp.task('bump:major:commit', ['bump:major:tag', 'generate:changelog'], function() {
  return commitStream('major') && pushStream();
});

gulp.task('generate:changelog', function() {
  return changelog({
    releaseCount: 0,
    preset: 'angular' /*,
    transform: function(commit, cb) {
      console.log(commit);
      if(_.contains(commit.header, ['bump'])) return cb(null);
      return cb(null, commit);
    }*/
  })
    .pipe(fs.createWriteStream('CHANGELOG.md'));
});

gulp.task('copy:nw', function() {
  var paths = getPaths();

  return gulp.src(['./package.json', 'nw-setup/**/*'])
    .pipe(gulp.dest(paths.dist))
    .on('error', util.log);
});

gulp.task('generate:binaries', ['clean:binaries', 'copy:nw'], function() {
  execSync('npm install --prefix ./dist/ express');
  var paths = getPaths();

  return gulp.src(paths.dist+'/**/*')
    .pipe(nwBuilder({
      version: 'v0.12.2',
      platforms: ['osx64', 'win64', 'linux64'],
      appName: packageJson.name,
      appVersion: packageJson.version,
      buildDir: './bin-build',
      cacheDir: './bin-cache',
      macIcns: './favicon.icns',
      winIco: './favicon.ico'
    }));
});

gulp.task('clean:binaries', function() {
  return gulp.src(['./bin-build', './bin-release'])
    .pipe(vinylPaths(del))
    .on('error', util.log);
});

var binaryPath = './bin-build/OpenChallenge';
gulp.task('package:binaries', ['generate:binaries'], folders(binaryPath, function(folder) {
  return gulp.src(binaryPath + '/' + folder + '/**/*')
    .pipe(zip(folder + '.zip'))
    .pipe(gulp.dest('./bin-release'));
}));

gulp.task('upload:binaries', ['package:binaries'], function() {
  return gulp.src('./bin-release/*.zip')
    .pipe(release({
      repo: 'openchallenge',
      owner: 'seiyria',
      manifest: packageJson
    }));
});

gulp.task('test', function() {
  var paths = getPaths();

  gulp.src(paths.testjs)
    .pipe(mocha());
});

gulp.task('bump:patch', ['bump:patch:tag', 'bump:patch:commit']);
gulp.task('bump:minor', ['bump:minor:tag', 'bump:minor:commit']);
gulp.task('bump:major', ['bump:major:tag', 'bump:major:commit']);

gulp.task('release:patch', ['bump:patch', 'upload:binaries']);
gulp.task('release:minor', ['bump:minor', 'upload:binaries']);
gulp.task('release:major', ['bump:major', 'upload:binaries']);

gulp.task('default', ['build', 'connect', 'open', 'watch']);
gulp.task('build', ['clean', 'copy:favicon', 'build:libjs', 'build:libcss', 'compile']);
gulp.task('compile', ['compile:js', 'compile:sass', 'compile:jade']);
gulp.task('check', ['test', 'build']);
<|endoftext|>


<commit_before>

var express = require('express');
var router = express.Router();

const config = require("./../config.js") || {}; // holds node specific settings, consider to use another file, e.g. config.js as option

var openwhiskHost = process.env.OPENWHISK_HOST || function() {
    throw "please set the OPENWHISK_HOST environmental variable pointing to openwhisk global, e.g. https://openwhisk.ng.bluemix.net";
}();

console.log("OPENWHISK_HOST: " + openwhiskHost);

//var stringify = require('json-stringify-safe');

var request = require('request');

router.use('/namespaces/:namespace*', function(req, res) {
  console.log("in /namespaces/:namespace*");
  console.log("METHOD: " + req.method);
  console.log("headers: " + JSON.stringify(req.headers));

  var url = openwhiskHost + req.originalUrl;
  console.log("url: " + url);

  var r = null;
  if(req.method === 'POST') {
     r = request.post({uri: url, json: req.body});
  } if(req.method === 'PUT'){
     r = request.put({uri: url, json: req.body});
  } else {
     r = request(url);
  }

  req.pipe(r, {end: false}).pipe(res);
});

module.exports = router;<commit_msg>bug fix<commit_after>

var express = require('express');
var router = express.Router();

const config = require("./../config.js") || {}; // holds node specific settings, consider to use another file, e.g. config.js as option

var openwhiskHost = process.env.OPENWHISK_HOST || function() {
    throw "please set the OPENWHISK_HOST environmental variable pointing to openwhisk global, e.g. https://openwhisk.ng.bluemix.net";
}();

console.log("OPENWHISK_HOST: " + openwhiskHost);

//var stringify = require('json-stringify-safe');

var request = require('request');

router.use('/namespaces/:namespace*', function(req, res) {
  console.log("in /namespaces/:namespace*");
  console.log("METHOD: " + req.method);
  console.log("headers: " + JSON.stringify(req.headers));

  var url = openwhiskHost + req.originalUrl;
  console.log("url: " + url);

  var r = null;
  if(req.method === 'POST') {
    req.pipe(request.post({uri: url, json: req.body}), {end: false}).pipe(res);
  } if(req.method === 'PUT'){
    req.pipe(request.put({uri: url, json: req.body}), {end: false}).pipe(res);
  } else {
    req.pipe(request(url)).pipe(res);
  }
});

module.exports = router;<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
  fs = require('fs'),
  defaultAssets = require('./config/assets/default'),
  testAssets = require('./config/assets/test'),
  testConfig = require('./config/env/test'),
  glob = require('glob'),
  gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  runSequence = require('run-sequence'),
  plugins = gulpLoadPlugins({
    rename: {
      'gulp-angular-templatecache': 'templateCache'
    }
  }),
  pngquant = require('imagemin-pngquant'),
  wiredep = require('wiredep').stream,
  path = require('path'),
  endOfLine = require('os').EOL,
  protractor = require('gulp-protractor').protractor,
  webdriver_update = require('gulp-protractor').webdriver_update,
  webdriver_standalone = require('gulp-protractor').webdriver_standalone,
  del = require('del'),
  KarmaServer = require('karma').Server,
  semver = require('semver');

// Local settings
var changedTestFiles = [];

// Set NODE_ENV to 'test'
gulp.task('env:test', function () {
  process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function () {
  process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function () {
  process.env.NODE_ENV = 'production';
});

// Nodemon task
gulp.task('nodemon', function () {

  // Node.js v7 and newer use different debug argument
  var debugArgument = semver.satisfies(process.versions.node, '>=7.0.0') ? '--inspect' : '--debug';

  return plugins.nodemon({
    script: 'server.js',
    nodeArgs: [debugArgument],
    ext: 'js,html',
    verbose: true,
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  });
});

// Nodemon task without verbosity or debugging
gulp.task('nodemon-nodebug', function () {
  return plugins.nodemon({
    script: 'server.js',
    ext: 'js,html',
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  });
});

// Watch Files For Changes
gulp.task('watch', function () {
  // Start livereload
  plugins.refresh.listen();

  // Add watch rules
  gulp.watch(defaultAssets.server.views).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.server.allJS, ['eslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.js, ['eslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.refresh.changed);

  if (process.env.NODE_ENV === 'production') {
    gulp.watch(defaultAssets.server.gulpConfig, ['templatecache', 'eslint']);
    gulp.watch(defaultAssets.client.views, ['templatecache']).on('change', plugins.refresh.changed);
  } else {
    gulp.watch(defaultAssets.server.gulpConfig, ['eslint']);
    gulp.watch(defaultAssets.client.views).on('change', plugins.refresh.changed);
  }
});

// Watch server test files
gulp.task('watch:server:run-tests', function () {
  // Start livereload
  plugins.refresh.listen();

  // Add Server Test file rules
  gulp.watch([testAssets.tests.server, defaultAssets.server.allJS], ['test:server']).on('change', function (file) {
    changedTestFiles = [];

    // iterate through server test glob patterns
    _.forEach(testAssets.tests.server, function (pattern) {
      // determine if the changed (watched) file is a server test
      _.forEach(glob.sync(pattern), function (f) {
        var filePath = path.resolve(f);

        if (filePath === path.resolve(file.path)) {
          changedTestFiles.push(f);
        }
      });
    });

    plugins.refresh.changed();
  });
});

// CSS linting task
gulp.task('csslint', function () {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csslint('.csslintrc'))
    .pipe(plugins.csslint.formatter());
    // Don't fail CSS issues yet
    // .pipe(plugins.csslint.failFormatter());
});

// ESLint JS linting task
gulp.task('eslint', function () {
  var assets = _.union(
    defaultAssets.server.gulpConfig,
    defaultAssets.server.allJS,
    defaultAssets.client.js,
    testAssets.tests.server,
    testAssets.tests.client,
    testAssets.tests.e2e
  );

  return gulp.src(assets)
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format());
});

// JS minifying task
gulp.task('uglify', function () {
  var assets = _.union(
    defaultAssets.client.js,
    defaultAssets.client.templates
  );
  del(['public/dist/*']);

  return gulp.src(assets)
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.uglify({
      mangle: false
    }))
    .pipe(plugins.concat('application.min.js'))
    .pipe(plugins.rev())
    .pipe(gulp.dest('public/dist'));
});

// CSS minifying task
gulp.task('cssmin', function () {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csso())
    .pipe(plugins.concat('application.min.css'))
    .pipe(plugins.rev())
    .pipe(gulp.dest('public/dist'));
});

// Sass task
gulp.task('sass', function () {
  return gulp.src(defaultAssets.client.sass)
    .pipe(plugins.sass())
    .pipe(plugins.autoprefixer())
    .pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function () {
  return gulp.src(defaultAssets.client.less)
    .pipe(plugins.less())
    .pipe(plugins.autoprefixer())
    .pipe(gulp.dest('./modules/'));
});

// Imagemin task
gulp.task('imagemin', function () {
  return gulp.src(defaultAssets.client.img)
    .pipe(plugins.imagemin({
      progressive: true,
      svgoPlugins: [{ removeViewBox: false }],
      use: [pngquant()]
    }))
    .pipe(gulp.dest('public/dist/img'));
});

// wiredep task to default
gulp.task('wiredep', function () {
  return gulp.src('config/assets/default.js')
    .pipe(wiredep({
      ignorePath: '../../'
    }))
    .pipe(gulp.dest('config/assets/'));
});

// wiredep task to production
gulp.task('wiredep:prod', function () {
  return gulp.src('config/assets/production.js')
    .pipe(wiredep({
      ignorePath: '../../',
      fileTypes: {
        js: {
          replace: {
            css: function (filePath) {
              var minFilePath = filePath.replace('.css', '.min.css');
              var fullPath = path.join(process.cwd(), minFilePath);
              if (!fs.existsSync(fullPath)) {
                return '\'' + filePath + '\',';
              } else {
                return '\'' + minFilePath + '\',';
              }
            },
            js: function (filePath) {
              var minFilePath = filePath.replace('.js', '.min.js');
              var fullPath = path.join(process.cwd(), minFilePath);
              if (!fs.existsSync(fullPath)) {
                return '\'' + filePath + '\',';
              } else {
                return '\'' + minFilePath + '\',';
              }
            }
          }
        }
      }
    }))
    .pipe(gulp.dest('config/assets/'));
});

// Copy local development environment config example
gulp.task('copyLocalEnvConfig', function () {
  var src = [];
  var renameTo = 'local-development.js';

  // only add the copy source if our destination file doesn't already exist
  if (!fs.existsSync('config/env/' + renameTo)) {
    src.push('config/env/local.example.js');
  }

  return gulp.src(src)
    .pipe(plugins.rename(renameTo))
    .pipe(gulp.dest('config/env'));
});

// Make sure upload directory exists
gulp.task('makeUploadsDir', function () {
  return fs.mkdir('modules/users/client/img/profile/uploads', function (err) {
    if (err && err.code !== 'EEXIST') {
      console.error(err);
    }
  });
});

// Angular template cache task
gulp.task('templatecache', function () {
  return gulp.src(defaultAssets.client.views)
    .pipe(plugins.templateCache('templates.js', {
      root: 'modules/',
      module: 'core',
      templateHeader: '(function () {' + endOfLine + '	\'use strict\';' + endOfLine + endOfLine + '	angular' + endOfLine + '		.module(\'<%= module %>\'<%= standalone %>)' + endOfLine + '		.run(templates);' + endOfLine + endOfLine + '	templates.$inject = [\'$templateCache\'];' + endOfLine + endOfLine + '	function templates($templateCache) {' + endOfLine,
      templateBody: '		$templateCache.put(\'<%= url %>\', \'<%= contents %>\');',
      templateFooter: '	}' + endOfLine + '})();' + endOfLine
    }))
    .pipe(gulp.dest('build'));
});

// Mocha tests task
gulp.task('mocha', function (done) {
  // Open mongoose connections
  var mongoose = require('./config/lib/mongoose.js');
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;
  var error;

  // Connect mongoose
  mongoose.connect(function () {
    mongoose.loadModels();
    // Run the tests
    gulp.src(testSuites)
      .pipe(plugins.mocha({
        reporter: 'spec',
        timeout: 10000
      }))
      .on('error', function (err) {
        // If an error occurs, save it
        error = err;
      })
      .on('end', function () {
        // When the tests are done, disconnect mongoose and pass the error state back to gulp
        mongoose.disconnect(function () {
          done(error);
        });
      });
  });
});

// Prepare istanbul coverage test
gulp.task('pre-test', function () {

  // Display coverage for all server JavaScript files
  return gulp.src(defaultAssets.server.allJS)
    // Covering files
    .pipe(plugins.istanbul())
    // Force `require` to return covered files
    .pipe(plugins.istanbul.hookRequire());
});

// Run istanbul test and write report
gulp.task('mocha:coverage', ['pre-test', 'mocha'], function () {
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;

  return gulp.src(testSuites)
    .pipe(plugins.istanbul.writeReports({
      reportOpts: { dir: './coverage/server' }
    }));
});

// Karma test runner task
gulp.task('karma', function (done) {
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js'
  }, done).start();
});

// Run karma with coverage options set and write report
gulp.task('karma:coverage', function(done) {
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    preprocessors: {
      'modules/*/client/views/**/*.html': ['ng-html2js'],
      'modules/core/client/app/config.js': ['coverage'],
      'modules/core/client/app/init.js': ['coverage'],
      'modules/*/client/*.js': ['coverage'],
      'modules/*/client/config/*.js': ['coverage'],
      'modules/*/client/controllers/*.js': ['coverage'],
      'modules/*/client/directives/*.js': ['coverage'],
      'modules/*/client/services/*.js': ['coverage']
    },
    reporters: ['progress', 'coverage'],
    coverageReporter: {
      dir: 'coverage/client',
      reporters: [
        { type: 'lcov', subdir: '.' }
        // printing summary to console currently weirdly causes gulp to hang so disabled for now
        // https://github.com/karma-runner/karma-coverage/issues/209
        // { type: 'text-summary' }
      ]
    }
  }, done).start();
});

// Drops the MongoDB database, used in e2e testing
gulp.task('dropdb', function (done) {
  // Use mongoose configuration
  var mongoose = require('./config/lib/mongoose.js');

  mongoose.connect(function (db) {
    db.connection.db.dropDatabase(function (err) {
      if (err) {
        console.error(err);
      } else {
        console.log('Successfully dropped db: ', db.connection.db.databaseName);
      }
      db.connection.db.close(done);
    });
  });
});

// Downloads the selenium webdriver if protractor version is compatible
gulp.task('webdriver_update', webdriver_update);

// Start the standalone selenium server
// NOTE: This is not needed if you reference the
// seleniumServerJar in your protractor.conf.js
gulp.task('webdriver_standalone', webdriver_standalone);

// Protractor test runner task
gulp.task('protractor', ['webdriver_update'], function () {
  gulp.src([])
    .pipe(protractor({
      configFile: 'protractor.conf.js'
    }))
    .on('end', function() {
      console.log('E2E Testing complete');
      // exit with success.
      process.exit(0);
    })
    .on('error', function(err) {
      console.error('E2E Tests failed:');
      console.error(err);
      process.exit(1);
    });
});

// Lint CSS and JavaScript files.
gulp.task('lint', function (done) {
  runSequence('less', 'sass', ['csslint', 'eslint'], done);
});

// Lint project files and minify them into two production files.
gulp.task('build', function (done) {
  runSequence('env:dev', 'wiredep:prod', 'lint', ['uglify', 'cssmin'], done);
});

// Run the project tests
gulp.task('test', function (done) {
  runSequence('env:test', 'test:server', 'karma', 'nodemon', 'protractor', done);
});

gulp.task('test:server', function (done) {
  runSequence('env:test', ['copyLocalEnvConfig', 'makeUploadsDir', 'dropdb'], 'lint', 'mocha', done);
});

// Watch all server files for changes & run server tests (test:server) task on changes
gulp.task('test:server:watch', function (done) {
  runSequence('test:server', 'watch:server:run-tests', done);
});

gulp.task('test:client', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'karma', done);
});

gulp.task('test:e2e', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'nodemon', 'protractor', done);
});

gulp.task('test:coverage', function (done) {
  runSequence('env:test', ['copyLocalEnvConfig', 'makeUploadsDir', 'dropdb'], 'lint', 'mocha:coverage', 'karma:coverage', done);
});

// Run the project in development mode with node debugger enabled
gulp.task('default', function (done) {
  runSequence('env:dev', ['copyLocalEnvConfig', 'makeUploadsDir'], 'lint', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function (done) {
  runSequence(['copyLocalEnvConfig', 'makeUploadsDir', 'templatecache'], 'build', 'env:prod', 'lint', ['nodemon-nodebug', 'watch'], done);
});
<commit_msg>Update templateCache root path<commit_after>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
  fs = require('fs'),
  defaultAssets = require('./config/assets/default'),
  testAssets = require('./config/assets/test'),
  testConfig = require('./config/env/test'),
  glob = require('glob'),
  gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  runSequence = require('run-sequence'),
  plugins = gulpLoadPlugins({
    rename: {
      'gulp-angular-templatecache': 'templateCache'
    }
  }),
  pngquant = require('imagemin-pngquant'),
  wiredep = require('wiredep').stream,
  path = require('path'),
  endOfLine = require('os').EOL,
  protractor = require('gulp-protractor').protractor,
  webdriver_update = require('gulp-protractor').webdriver_update,
  webdriver_standalone = require('gulp-protractor').webdriver_standalone,
  del = require('del'),
  KarmaServer = require('karma').Server,
  semver = require('semver');

// Local settings
var changedTestFiles = [];

// Set NODE_ENV to 'test'
gulp.task('env:test', function () {
  process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function () {
  process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function () {
  process.env.NODE_ENV = 'production';
});

// Nodemon task
gulp.task('nodemon', function () {

  // Node.js v7 and newer use different debug argument
  var debugArgument = semver.satisfies(process.versions.node, '>=7.0.0') ? '--inspect' : '--debug';

  return plugins.nodemon({
    script: 'server.js',
    nodeArgs: [debugArgument],
    ext: 'js,html',
    verbose: true,
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  });
});

// Nodemon task without verbosity or debugging
gulp.task('nodemon-nodebug', function () {
  return plugins.nodemon({
    script: 'server.js',
    ext: 'js,html',
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  });
});

// Watch Files For Changes
gulp.task('watch', function () {
  // Start livereload
  plugins.refresh.listen();

  // Add watch rules
  gulp.watch(defaultAssets.server.views).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.server.allJS, ['eslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.js, ['eslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.refresh.changed);

  if (process.env.NODE_ENV === 'production') {
    gulp.watch(defaultAssets.server.gulpConfig, ['templatecache', 'eslint']);
    gulp.watch(defaultAssets.client.views, ['templatecache']).on('change', plugins.refresh.changed);
  } else {
    gulp.watch(defaultAssets.server.gulpConfig, ['eslint']);
    gulp.watch(defaultAssets.client.views).on('change', plugins.refresh.changed);
  }
});

// Watch server test files
gulp.task('watch:server:run-tests', function () {
  // Start livereload
  plugins.refresh.listen();

  // Add Server Test file rules
  gulp.watch([testAssets.tests.server, defaultAssets.server.allJS], ['test:server']).on('change', function (file) {
    changedTestFiles = [];

    // iterate through server test glob patterns
    _.forEach(testAssets.tests.server, function (pattern) {
      // determine if the changed (watched) file is a server test
      _.forEach(glob.sync(pattern), function (f) {
        var filePath = path.resolve(f);

        if (filePath === path.resolve(file.path)) {
          changedTestFiles.push(f);
        }
      });
    });

    plugins.refresh.changed();
  });
});

// CSS linting task
gulp.task('csslint', function () {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csslint('.csslintrc'))
    .pipe(plugins.csslint.formatter());
    // Don't fail CSS issues yet
    // .pipe(plugins.csslint.failFormatter());
});

// ESLint JS linting task
gulp.task('eslint', function () {
  var assets = _.union(
    defaultAssets.server.gulpConfig,
    defaultAssets.server.allJS,
    defaultAssets.client.js,
    testAssets.tests.server,
    testAssets.tests.client,
    testAssets.tests.e2e
  );

  return gulp.src(assets)
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format());
});

// JS minifying task
gulp.task('uglify', function () {
  var assets = _.union(
    defaultAssets.client.js,
    defaultAssets.client.templates
  );
  del(['public/dist/*']);

  return gulp.src(assets)
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.uglify({
      mangle: false
    }))
    .pipe(plugins.concat('application.min.js'))
    .pipe(plugins.rev())
    .pipe(gulp.dest('public/dist'));
});

// CSS minifying task
gulp.task('cssmin', function () {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csso())
    .pipe(plugins.concat('application.min.css'))
    .pipe(plugins.rev())
    .pipe(gulp.dest('public/dist'));
});

// Sass task
gulp.task('sass', function () {
  return gulp.src(defaultAssets.client.sass)
    .pipe(plugins.sass())
    .pipe(plugins.autoprefixer())
    .pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function () {
  return gulp.src(defaultAssets.client.less)
    .pipe(plugins.less())
    .pipe(plugins.autoprefixer())
    .pipe(gulp.dest('./modules/'));
});

// Imagemin task
gulp.task('imagemin', function () {
  return gulp.src(defaultAssets.client.img)
    .pipe(plugins.imagemin({
      progressive: true,
      svgoPlugins: [{ removeViewBox: false }],
      use: [pngquant()]
    }))
    .pipe(gulp.dest('public/dist/img'));
});

// wiredep task to default
gulp.task('wiredep', function () {
  return gulp.src('config/assets/default.js')
    .pipe(wiredep({
      ignorePath: '../../'
    }))
    .pipe(gulp.dest('config/assets/'));
});

// wiredep task to production
gulp.task('wiredep:prod', function () {
  return gulp.src('config/assets/production.js')
    .pipe(wiredep({
      ignorePath: '../../',
      fileTypes: {
        js: {
          replace: {
            css: function (filePath) {
              var minFilePath = filePath.replace('.css', '.min.css');
              var fullPath = path.join(process.cwd(), minFilePath);
              if (!fs.existsSync(fullPath)) {
                return '\'' + filePath + '\',';
              } else {
                return '\'' + minFilePath + '\',';
              }
            },
            js: function (filePath) {
              var minFilePath = filePath.replace('.js', '.min.js');
              var fullPath = path.join(process.cwd(), minFilePath);
              if (!fs.existsSync(fullPath)) {
                return '\'' + filePath + '\',';
              } else {
                return '\'' + minFilePath + '\',';
              }
            }
          }
        }
      }
    }))
    .pipe(gulp.dest('config/assets/'));
});

// Copy local development environment config example
gulp.task('copyLocalEnvConfig', function () {
  var src = [];
  var renameTo = 'local-development.js';

  // only add the copy source if our destination file doesn't already exist
  if (!fs.existsSync('config/env/' + renameTo)) {
    src.push('config/env/local.example.js');
  }

  return gulp.src(src)
    .pipe(plugins.rename(renameTo))
    .pipe(gulp.dest('config/env'));
});

// Make sure upload directory exists
gulp.task('makeUploadsDir', function () {
  return fs.mkdir('modules/users/client/img/profile/uploads', function (err) {
    if (err && err.code !== 'EEXIST') {
      console.error(err);
    }
  });
});

// Angular template cache task
gulp.task('templatecache', function () {
  return gulp.src(defaultAssets.client.views)
    .pipe(plugins.templateCache('templates.js', {
      root: '/modules/',
      module: 'core',
      templateHeader: '(function () {' + endOfLine + '	\'use strict\';' + endOfLine + endOfLine + '	angular' + endOfLine + '		.module(\'<%= module %>\'<%= standalone %>)' + endOfLine + '		.run(templates);' + endOfLine + endOfLine + '	templates.$inject = [\'$templateCache\'];' + endOfLine + endOfLine + '	function templates($templateCache) {' + endOfLine,
      templateBody: '		$templateCache.put(\'<%= url %>\', \'<%= contents %>\');',
      templateFooter: '	}' + endOfLine + '})();' + endOfLine
    }))
    .pipe(gulp.dest('build'));
});

// Mocha tests task
gulp.task('mocha', function (done) {
  // Open mongoose connections
  var mongoose = require('./config/lib/mongoose.js');
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;
  var error;

  // Connect mongoose
  mongoose.connect(function () {
    mongoose.loadModels();
    // Run the tests
    gulp.src(testSuites)
      .pipe(plugins.mocha({
        reporter: 'spec',
        timeout: 10000
      }))
      .on('error', function (err) {
        // If an error occurs, save it
        error = err;
      })
      .on('end', function () {
        // When the tests are done, disconnect mongoose and pass the error state back to gulp
        mongoose.disconnect(function () {
          done(error);
        });
      });
  });
});

// Prepare istanbul coverage test
gulp.task('pre-test', function () {

  // Display coverage for all server JavaScript files
  return gulp.src(defaultAssets.server.allJS)
    // Covering files
    .pipe(plugins.istanbul())
    // Force `require` to return covered files
    .pipe(plugins.istanbul.hookRequire());
});

// Run istanbul test and write report
gulp.task('mocha:coverage', ['pre-test', 'mocha'], function () {
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;

  return gulp.src(testSuites)
    .pipe(plugins.istanbul.writeReports({
      reportOpts: { dir: './coverage/server' }
    }));
});

// Karma test runner task
gulp.task('karma', function (done) {
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js'
  }, done).start();
});

// Run karma with coverage options set and write report
gulp.task('karma:coverage', function(done) {
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    preprocessors: {
      'modules/*/client/views/**/*.html': ['ng-html2js'],
      'modules/core/client/app/config.js': ['coverage'],
      'modules/core/client/app/init.js': ['coverage'],
      'modules/*/client/*.js': ['coverage'],
      'modules/*/client/config/*.js': ['coverage'],
      'modules/*/client/controllers/*.js': ['coverage'],
      'modules/*/client/directives/*.js': ['coverage'],
      'modules/*/client/services/*.js': ['coverage']
    },
    reporters: ['progress', 'coverage'],
    coverageReporter: {
      dir: 'coverage/client',
      reporters: [
        { type: 'lcov', subdir: '.' }
        // printing summary to console currently weirdly causes gulp to hang so disabled for now
        // https://github.com/karma-runner/karma-coverage/issues/209
        // { type: 'text-summary' }
      ]
    }
  }, done).start();
});

// Drops the MongoDB database, used in e2e testing
gulp.task('dropdb', function (done) {
  // Use mongoose configuration
  var mongoose = require('./config/lib/mongoose.js');

  mongoose.connect(function (db) {
    db.connection.db.dropDatabase(function (err) {
      if (err) {
        console.error(err);
      } else {
        console.log('Successfully dropped db: ', db.connection.db.databaseName);
      }
      db.connection.db.close(done);
    });
  });
});

// Downloads the selenium webdriver if protractor version is compatible
gulp.task('webdriver_update', webdriver_update);

// Start the standalone selenium server
// NOTE: This is not needed if you reference the
// seleniumServerJar in your protractor.conf.js
gulp.task('webdriver_standalone', webdriver_standalone);

// Protractor test runner task
gulp.task('protractor', ['webdriver_update'], function () {
  gulp.src([])
    .pipe(protractor({
      configFile: 'protractor.conf.js'
    }))
    .on('end', function() {
      console.log('E2E Testing complete');
      // exit with success.
      process.exit(0);
    })
    .on('error', function(err) {
      console.error('E2E Tests failed:');
      console.error(err);
      process.exit(1);
    });
});

// Lint CSS and JavaScript files.
gulp.task('lint', function (done) {
  runSequence('less', 'sass', ['csslint', 'eslint'], done);
});

// Lint project files and minify them into two production files.
gulp.task('build', function (done) {
  runSequence('env:dev', 'wiredep:prod', 'lint', ['uglify', 'cssmin'], done);
});

// Run the project tests
gulp.task('test', function (done) {
  runSequence('env:test', 'test:server', 'karma', 'nodemon', 'protractor', done);
});

gulp.task('test:server', function (done) {
  runSequence('env:test', ['copyLocalEnvConfig', 'makeUploadsDir', 'dropdb'], 'lint', 'mocha', done);
});

// Watch all server files for changes & run server tests (test:server) task on changes
gulp.task('test:server:watch', function (done) {
  runSequence('test:server', 'watch:server:run-tests', done);
});

gulp.task('test:client', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'karma', done);
});

gulp.task('test:e2e', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'nodemon', 'protractor', done);
});

gulp.task('test:coverage', function (done) {
  runSequence('env:test', ['copyLocalEnvConfig', 'makeUploadsDir', 'dropdb'], 'lint', 'mocha:coverage', 'karma:coverage', done);
});

// Run the project in development mode with node debugger enabled
gulp.task('default', function (done) {
  runSequence('env:dev', ['copyLocalEnvConfig', 'makeUploadsDir'], 'lint', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function (done) {
  runSequence(['copyLocalEnvConfig', 'makeUploadsDir', 'templatecache'], 'build', 'env:prod', 'lint', ['nodemon-nodebug', 'watch'], done);
});
<|endoftext|>


<commit_before>var cacheKeys = {};
var express = require('express');
var router = express.Router();

(function () {
    "use strict";
    router.get('/', function (req, res, next) {
        res.send('usage: /write/uniqueKey && /read/uniqueKey');
    });

    router.all('/write/*', function (req, res, next) {
        let chunks = req.url.split("/");
        switch (chunks.length) {
            default:
                res.send('
usage: /write/channel/uniqueKey && /read/channel/uniqueKey
');
                return;
            case 4:
                let userId = getUserId(chunks);
                let channel = getChannel(chunks);
                let cacheKey = userId + channel;
                if (firstRequestToCache(userId, channel)) {
                    cacheKeys[cacheKey] = [];
                    cacheKeys[userId + channel + "pointer"] = 0;
                }

                if (isRequestPopulated(req.body)) {
                    cacheKeys[cacheKey].push(req.body);
                    if (cacheKeys[cacheKey].length > 1000) {
                        cacheKeys[cacheKey] = cacheKeys[cacheKey].splice(-100);
                        cacheKeys[userId + channel + "pointer"] = 0;
                    }
                    res.send(cacheKey);
                } else {
                    res.send("no request received");
                }
        }
    });

    router.get('/read-all(*)', function (req, res, next) {
        let chunks = req.url.split("/");
        let response = {};
        let channel;

        switch (chunks.length) {
            default:
                res.send(JSON.stringify(cacheKeys));
                return;
            case 3:
                channel = (chunks.length > 1) ? getChannel(chunks) : "";
                for (const key in cacheKeys) {
                    if (key.indexOf(channel) !== -1) {
                        response[key] = cacheKeys[key];
                    }
                }
                break;
            case 4:
                channel = (chunks.length > 1) ? getChannel(chunks) : "";
                let userId = (chunks.length > 2) ? getUserId(chunks) : "";
                for (const key in cacheKeys) {
                    if (key.indexOf(userId + channel) !== -1) {
                        response[key] = cacheKeys[key];
                    }
                }
        }
        res.send(JSON.stringify(response));
    });

    router.get('/read/*', function (req, res, next) {
        let chunks = req.url.split("/");
        switch (chunks.length) {
            default:
                res.send('
usage: /write/channel/uniqueKey && /read/channel/uniqueKey
');
                return;
            case 4:
                let userId = getUserId(chunks);
                let channel = getChannel(chunks);
                let actualUsersPointer = getActualUserPointer(userId + channel) || 0;
                let cacheKey = cacheKeys[userId + channel] || [];
                let response = cacheKey[actualUsersPointer] || null;
                if (response !== null) {
                    cacheKeys[userId + channel + "pointer"] = actualUsersPointer + 1;
                } else {
                    response = "";
                }

                res.send(response);
        }
    });

    module.exports = router;

    function getChannel(chunks) {
        return chunks[2] || "";
    }

    function getUserId(chunks) {
        return chunks[3] || "";
    }

    function getActualUserPointer(userIdWithChannel) {
        return cacheKeys[userIdWithChannel + "pointer"];
    }

    function firstRequestToCache(userId, channel) {
        return !cacheKeys[userId + channel];
    }

    function isRequestPopulated(body) {
        return Object.getOwnPropertyNames(body).length > 0;
    }
})();
<commit_msg>test git access<commit_after>var cacheKeys = {};
var express = require('express');
var router = express.Router();

(function () {
    "use strict";
    router.get('/', function (req, res, next) {
        res.send('usage: /write/uniqueKey && /read/uniqueKey');
    });

    router.all('/write/*', function (req, res, next) {
        let chunks = req.url.split("/");
        switch (chunks.length) {
            default:
                res.send('
usage: /write/channel/uniqueKey && /read/channel/uniqueKey
');
                return;
            case 4:
                let userId = getUserId(chunks);
                let channel = getChannel(chunks);
                let cacheKey = userId + channel;
                if (firstRequestToCache(userId, channel)) {
                    cacheKeys[cacheKey] = [];
                    cacheKeys[userId + channel + "pointer"] = 0;
                }

                if (isRequestPopulated(req.body)) {
                    cacheKeys[cacheKey].push(req.body);
                    if (cacheKeys[cacheKey].length > 1000) {
                        cacheKeys[cacheKey] = cacheKeys[cacheKey].splice(-100);
                        cacheKeys[userId + channel + "pointer"] = 0;
                    }
                    res.send(cacheKey);
                } else {
                    res.send("no request received");
                }
        }
    });

    router.get('/read-all(*)', function (req, res, next) {
        let chunks = req.url.split("/");
        let response = {};
        let channel;

        switch (chunks.length) {
            default:
                res.send(JSON.stringify(cacheKeys));
                return;
            case 3:
                channel = (chunks.length > 1) ? getChannel(chunks) : "";
                for (const key in cacheKeys) {
                    if (key.indexOf(channel) !== -1) {
                        response[key] = cacheKeys[key];
                    }
                }
                break;
            case 4:
                channel = (chunks.length > 1) ? getChannel(chunks) : "";
                let userId = (chunks.length > 2) ? getUserId(chunks) : "";
                for (const key in cacheKeys) {
                    if (key.indexOf(userId + channel) !== -1) {
                        response[key] = cacheKeys[key];
                    }
                }
        }
        res.send(JSON.stringify(response));
    });

    router.get('/read/*', function (req, res, next) {
        let chunks = req.url.split("/");
        switch (chunks.length) {
            default:
                res.send('
usage: /write/channel/uniqueKey && /read/channel/uniqueKey
');
                return;
            case 4:
                let userId = getUserId(chunks);
                let channel = getChannel(chunks);
                let actualUsersPointer = getActualUserPointer(userId + channel) || 0;
                let cacheKey = cacheKeys[userId + channel] || [];
                let response = cacheKey[actualUsersPointer] || null;
                if (response !== null) {
                    cacheKeys[userId + channel + "pointer"] = actualUsersPointer + 1;
                } else {
                    response = "";
                }

                res.send(response);
        }
    });

    module.exports = router;

    function getChannel(chunks) {
        return chunks[2] || "";
    }

    function getUserId(chunks) {
        return chunks[3] || "";
    }

    function getActualUserPointer(userIdWithChannel) {
        return cacheKeys[userIdWithChannel + "pointer"];
    }

    function firstRequestToCache(userId, channel) {
        return !cacheKeys[userId + channel];
    }

    function isRequestPopulated(body) {
        return Object.getOwnPropertyNames(body).length > 0;
    }
})();
<|endoftext|>


<commit_before>/*
 * bValidator bs3popover theme options
 */

bValidator.defaultOptions.themes.bs3popover = {

    popoverOptions : { // see: http://getbootstrap.com/javascript/#popovers-options
        html     : 'true',
        template : '

',
        viewport : null,
        trigger  : 'manual'
    },
    placement : 'right', // top | bottom | left | right
    content   : '
{message}
',
    contentClose : '
{message}

<button type="button" class="close" aria-label="Close">×</button>
',
    showClose : true,

    dataOptionNamespace : 'bvalidatorTheme', // data-bvalidator-theme- attributes
    presenter : 'Bs3PopoverTooltipPresenter' // or constructor function
}

// set as default theme
bValidator.defaultOptions.useTheme = 'bs3popover';
<commit_msg>true as bool not string<commit_after>/*
 * bValidator bs3popover theme options
 */

bValidator.defaultOptions.themes.bs3popover = {

    popoverOptions : {
        html     : true,
        template : '

',
        viewport : null,
        trigger  : 'manual'
    },
    placement : 'right', // top | bottom | left | right
    content   : '
{message}
',
    contentClose : '
{message}

<button type="button" class="close" aria-label="Close">×</button>
',
    showClose : true,

    dataOptionNamespace : 'bvalidatorTheme', // data-bvalidator-theme- attributes
    presenter : 'Bs3PopoverTooltipPresenter' // or constructor function
}

// set as default theme
bValidator.defaultOptions.useTheme = 'bs3popover';
<|endoftext|>