<commit_before>var gulp = require('gulp');
var loadPlugins = require('gulp-load-plugins');
var path = require('path');

/**
 * High Level Tasks
 */
gulp.task('lint', ['jshint', 'tslint']);
gulp.task('test', ['lint', 'spec']);
gulp.task('bundle', ['browser', 'browser-min']);
gulp.task('web-setup', ['scripts', 'bundle', 'public-files']);
gulp.task('default', ['web-setup', 'server', 'watch']);

/**
 * Gulpfile variables
 */
var _, env, globs, val;

/**
 * A gulp lazy loader for plugins
 * @type {Object}
 */
_ = loadPlugins({
  pattern: '{' + [
    'browser-sync',
    'browserify',
    'dts-bundle',
    'del',
    'event-stream',
    'glob',
    'gulp-*',
    'typescript-formatter',
    'vinyl-buffer',
    'vinyl-source-stream'
  ].join(',') + '}',
  scope: [
    'devDependencies'
  ]
});

/**
 * Runs a function once and caches the value
 * @param  {Function} fn The value constructor
 * @return {Function}    The value accessor
 */
val = function(fn) {
  var value;
  return function() {
    if (value === undefined) {
      value = fn();
    }
    return value;
  };
};

/**
 * Task environment
 * @type {Object}
 */
env = {
  isTest: val(function() {
    return env.task() === 'test';
  }),
  isTravis: val(function() {
    return process.env.TRAVIS !== undefined;
  }),
  project: val(function() {
    return _.typescript.createProject({
      declarationFiles: false,
      module: 'commonjs',
      noExternalResolve: true,
      noImplicitAny: true,
      noLib: false,
      removeComments: true,
      sortOutput: false,
      target: 'ES5'
    });
  }),
  task: val(function() {
    return gulp.seq[gulp.seq.length - 1];
  })
};

/**
 * File globs
 * @type {Object}
 */
globs = {
  build: val(function() {
    return '_build';
  }),
  dist: val(function() {
    return 'dist';
  }),
  dts: val(function() {
    return [
      globs.ts(),
      'lib/**/*.d.ts',
      'typings/**/*.d.ts',
      'node_modules/typed-react/dist/typed-react.d.ts'
    ];
  }),
  gulp: val(function() {
    return 'gulpfile.js';
  }),
  scripts: val(function() {
    return path.join(globs.build(), globs.src(), '**', '*.js');
  }),
  src: val(function() {
    return 'src';
  }),
  test: val(function() {
    return 'test';
  }),
  tests: val(function() {
    return path.join(globs.build(), globs.test(), '**', '*.js');
  }),
  ts: val(function() {
    return path.join(
        '{' + globs.src() + ',' + globs.test() + '}', '**', '*.ts');
  }),
  build_index: val(function() {
    return './' + path.join(globs.build(), globs.src(), 'index.js');
  }),
  pub: val(function() {
    return 'public';
  }),
  pubs: val(function() {
    return path.join(globs.pub(), '**', '*.{html,css}');
  })
};

/**
 * Bundles the code, full version to `asana.js` and minified to `asana-min.js`
 */
function browserTask(minify) {
    return function() {
        var task = _.browserify(
            {
                entries: [globs.build_index()],
                standalone: 'AsanaTester'
            })
            .bundle()
            .pipe(_.vinylSourceStream('asana-tester' + (minify ? '-min' : '') + '.js'));
        if (minify) {
            task = task
                .pipe(_.vinylBuffer())
                .pipe(_.uglify());
        }
        return task.pipe(gulp.dest(globs.dist()));
    };
}
gulp.task('browser', ['scripts'], browserTask(false));
gulp.task('browser-min', ['scripts'], browserTask(true));

/**
 * Set up files before running the web server.
 */
gulp.task('public-files', function() {
  gulp.src(globs.pubs()).pipe(gulp.dest(globs.dist()));
});

/**
 * Run a simple server for running the API tester.
 */
gulp.task('server', ['web-setup'], function() {
  _.browserSync({
    ghostMode: false,
    notify: false,
    online: false,
    port: process.env.PORT || 8338,
    server: {
      baseDir: globs.dist(),
    }
  });
});

/**
 * Watch for changes for live reloading.
 */
gulp.task('watch', function() {
  gulp.watch(globs.ts(), ['browser-min', _.browserSync.reload]);
  gulp.watch(globs.pubs(), ['public-files', _.browserSync.reload]);
});

/**
 * Cleans the build artifacts
 */
gulp.task('clean', function(callback) {
  _.del([
    globs.build(),
    globs.dist()
  ], callback);
});

/**
 * Auto format the TypeScript files
 */
gulp.task('format', function(callback) {
  _.glob(globs.ts(), function(err, files) {
    if (err) {
      return callback(err);
    }
    _.typescriptFormatter.processFiles(files, {
      editorconfig: false,
      replace: true,
      tsfmt: false,
      tslint: true
    });
    return callback(null);
  });
});

/**
 * Lint the JavaScript files
 */
gulp.task('jshint', function() {
  return gulp.src(globs.gulp())
      .pipe(_.jshint())
      .pipe(_.jshint.reporter('jshint-stylish'))
      .pipe(_.if(env.isTest(), _.jshint.reporter('fail')));
});

/**
 * Processes the TypeScript files
 */
gulp.task('scripts', ['tslint'], function() {
  var hasError = false;
  var compiler = gulp.src(globs.dts())
      .pipe(_.typescript(env.project()));
  var dts = compiler.dts
      .pipe(gulp.dest(globs.build()));
  var js = compiler.js
      .on('error', function() {
        hasError = true;
      })
      .on('end', function() {
        if (env.isTest() && hasError) {
          process.exit(8);
        }
      })
      .pipe(gulp.dest(globs.build()));
  return _.eventStream.merge(dts, js);
});

/**
 * Run the tests
 */
gulp.task('spec', ['scripts'], function(callback) {
  var reporters = ['text', 'text-summary'];
  if (!env.isTravis()) {
    reporters.push('html');
  }
  gulp.src(globs.scripts())
      .pipe(_.istanbul({
        includeUntested: true
      }))
      .pipe(_.istanbul.hookRequire())
      .on('finish', function() {
        gulp.src(globs.tests())
            .pipe(_.mocha())
            .pipe(_.istanbul.writeReports())
            .on('end', callback);
      });
});

/**
 * Lint the TypeScript files
 */
gulp.task('tslint', function() {
  return gulp.src(globs.ts())
      .pipe(_.tslint())
      .pipe(_.tslint.report({
        emitError: env.isTest()
      }));
});
<commit_msg>Don't clutter test output with react warnings<commit_after>var gulp = require('gulp');
var loadPlugins = require('gulp-load-plugins');
var path = require('path');

/**
 * High Level Tasks
 */
gulp.task('lint', ['jshint', 'tslint']);
gulp.task('test', ['lint', 'spec']);
gulp.task('bundle', ['browser', 'browser-min']);
gulp.task('web-setup', ['scripts', 'bundle', 'public-files']);
gulp.task('default', ['web-setup', 'server', 'watch']);

/**
 * Gulpfile variables
 */
var _, env, globs, val;

/**
 * A gulp lazy loader for plugins
 * @type {Object}
 */
_ = loadPlugins({
  pattern: '{' + [
    'browser-sync',
    'browserify',
    'dts-bundle',
    'del',
    'event-stream',
    'glob',
    'gulp-*',
    'typescript-formatter',
    'vinyl-buffer',
    'vinyl-source-stream'
  ].join(',') + '}',
  scope: [
    'devDependencies'
  ]
});

/**
 * Runs a function once and caches the value
 * @param  {Function} fn The value constructor
 * @return {Function}    The value accessor
 */
val = function(fn) {
  var value;
  return function() {
    if (value === undefined) {
      value = fn();
    }
    return value;
  };
};

/**
 * Task environment
 * @type {Object}
 */
env = {
  isTest: val(function() {
    return env.task() === 'test';
  }),
  isTravis: val(function() {
    return process.env.TRAVIS !== undefined;
  }),
  project: val(function() {
    return _.typescript.createProject({
      declarationFiles: false,
      module: 'commonjs',
      noExternalResolve: true,
      noImplicitAny: true,
      noLib: false,
      removeComments: true,
      sortOutput: false,
      target: 'ES5'
    });
  }),
  task: val(function() {
    return gulp.seq[gulp.seq.length - 1];
  })
};

/**
 * File globs
 * @type {Object}
 */
globs = {
  build: val(function() {
    return '_build';
  }),
  dist: val(function() {
    return 'dist';
  }),
  dts: val(function() {
    return [
      globs.ts(),
      'lib/**/*.d.ts',
      'typings/**/*.d.ts'
    ];
  }),
  gulp: val(function() {
    return 'gulpfile.js';
  }),
  scripts: val(function() {
    return path.join(globs.build(), globs.src(), '**', '*.js');
  }),
  src: val(function() {
    return 'src';
  }),
  test: val(function() {
    return 'test';
  }),
  tests: val(function() {
    return path.join(globs.build(), globs.test(), '**', '*.js');
  }),
  ts: val(function() {
    return path.join(
        '{' + globs.src() + ',' + globs.test() + '}', '**', '*.ts');
  }),
  build_index: val(function() {
    return './' + path.join(globs.build(), globs.src(), 'index.js');
  }),
  pub: val(function() {
    return 'public';
  }),
  pubs: val(function() {
    return path.join(globs.pub(), '**', '*.{html,css}');
  })
};

/**
 * Bundles the code, full version to `asana.js` and minified to `asana-min.js`
 */
function browserTask(minify) {
    return function() {
        var task = _.browserify(
            {
                entries: [globs.build_index()],
                standalone: 'AsanaTester'
            })
            .bundle()
            .pipe(_.vinylSourceStream('asana-tester' + (minify ? '-min' : '') + '.js'));
        if (minify) {
            task = task
                .pipe(_.vinylBuffer())
                .pipe(_.uglify());
        }
        return task.pipe(gulp.dest(globs.dist()));
    };
}
gulp.task('browser', ['scripts'], browserTask(false));
gulp.task('browser-min', ['scripts'], browserTask(true));

/**
 * Set up files before running the web server.
 */
gulp.task('public-files', function() {
  gulp.src(globs.pubs()).pipe(gulp.dest(globs.dist()));
});

/**
 * Run a simple server for running the API tester.
 */
gulp.task('server', ['web-setup'], function() {
  _.browserSync({
    ghostMode: false,
    notify: false,
    online: false,
    port: process.env.PORT || 8338,
    server: {
      baseDir: globs.dist(),
    }
  });
});

/**
 * Watch for changes for live reloading.
 */
gulp.task('watch', function() {
  gulp.watch(globs.ts(), ['browser-min', _.browserSync.reload]);
  gulp.watch(globs.pubs(), ['public-files', _.browserSync.reload]);
});

/**
 * Cleans the build artifacts
 */
gulp.task('clean', function(callback) {
  _.del([
    globs.build(),
    globs.dist()
  ], callback);
});

/**
 * Auto format the TypeScript files
 */
gulp.task('format', function(callback) {
  _.glob(globs.ts(), function(err, files) {
    if (err) {
      return callback(err);
    }
    _.typescriptFormatter.processFiles(files, {
      editorconfig: false,
      replace: true,
      tsfmt: false,
      tslint: true
    });
    return callback(null);
  });
});

/**
 * Lint the JavaScript files
 */
gulp.task('jshint', function() {
  return gulp.src(globs.gulp())
      .pipe(_.jshint())
      .pipe(_.jshint.reporter('jshint-stylish'))
      .pipe(_.if(env.isTest(), _.jshint.reporter('fail')));
});

/**
 * Processes the TypeScript files
 */
gulp.task('scripts', ['tslint'], function() {
  var hasError = false;
  var compiler = gulp.src(globs.dts())
      .pipe(_.typescript(env.project()));
  var dts = compiler.dts
      .pipe(gulp.dest(globs.build()));
  var js = compiler.js
      .on('error', function() {
        hasError = true;
      })
      .on('end', function() {
        if (env.isTest() && hasError) {
          process.exit(8);
        }
      })
      .pipe(gulp.dest(globs.build()));
  return _.eventStream.merge(dts, js);
});

/**
 * Run the tests
 */
gulp.task('spec', ['scripts'], function(callback) {
  // Don't clutter test output for React isDOMNode warnings
  var consoleWarn = console.warn;
  console.warn = function(message) {
    if (message.indexOf("getDOMNode") === -1) {
      consoleWarn.apply(null, arguments);
    }
  };

  var reporters = ['text', 'text-summary'];
  if (!env.isTravis()) {
    reporters.push('html');
  }
  gulp.src(globs.scripts())
      .pipe(_.istanbul({
        includeUntested: true
      }))
      .pipe(_.istanbul.hookRequire())
      .on('finish', function() {
        gulp.src(globs.tests())
            .pipe(_.mocha())
            .pipe(_.istanbul.writeReports())
            .on('end', callback);
      });
});

/**
 * Lint the TypeScript files
 */
gulp.task('tslint', function() {
  return gulp.src(globs.ts())
      .pipe(_.tslint())
      .pipe(_.tslint.report({
        emitError: env.isTest()
      }));
});
<|endoftext|>


<commit_before>/* jshint -W079 */
var gulp   = require('gulp'),
    semver = require('semver'),
    $      = require('gulp-load-plugins')();

var inc = function (importance) {
  return gulp.src(['./package.json'])
    .pipe($.bump({type: importance}))
    .pipe(gulp.dest('./'))
    .pipe($.git.commit('Release v' + semver.inc(
      require(__dirname + '/package.json').version,
      importance)))
    .pipe($.tagVersion())
    .pipe($.git.push('origin', 'master', {args: '--tags'}));
};

/* JS linting ------------------------------------------------------------ */
gulp.task('lint', function () {
  return gulp.src('./index.js')
    .pipe($.jshint({
      lookup: true
    }))
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'))
    .pipe($.jsvalidate());
});

/* Version bumping ------------------------------------------------------- */
gulp.task('patch', ['lint'], function () { return inc('patch'); });
gulp.task('feature', ['lint'], function () { return inc('minor'); });
gulp.task('release', ['lint'], function () { return inc('major'); });
<commit_msg>altered gulpfile to remove erroneous testing.<commit_after>// Load plugins
var gulp     = require('gulp'),
    semver   = require('semver'),
    bump     = require('gulp-bump'),
    git      = require('gulp-git'),
    tag      = require('gulp-tag-version');

var inc = function (importance) {
  return gulp.src(['./package.json'])
    .pipe(bump({type: importance}))
    .pipe(gulp.dest('./'))
    .pipe(git.commit('Release v' + semver.inc(
      require(__dirname + '/package.json').version,
      importance)))
    .pipe(tag())
    .pipe(git.push('origin', 'master', {args: '--tags'}));
};

/* Version bumping ------------------------------------------------------- */
gulp.task('patch', ['lint'], function () { return inc('patch'); });
gulp.task('feature', ['lint'], function () { return inc('minor'); });
gulp.task('release', ['lint'], function () { return inc('major'); });
<|endoftext|>


<commit_before>/* jshint camelcase:false */
var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./gulp/common.js');
var plug = require('gulp-load-plugins')();
var env = plug.util.env;
var log = plug.util.log;

gulp.task('help', plug.taskListing);

/**
 * @desc Annotate only
 *  Mostly for show.
 *  See the output of each file?
 *      Uncomment rename, comment concat and uglify
 *  See min'd and concat'd output?
 *      Comment rename, uncomment concat and uglify,
 *      add to index.html, then run it with `gulp serve-dev`.
 */
gulp.task('ngAnnotateTest', function() {
    log('Annotating AngularJS dependencies');
    var source = [].concat(pkg.paths.js);
    return gulp
        // .src(source)
        .src(pkg.paths.client + '/app/avengers/avengers.js')
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.rename(function(path) {
            path.extname = '.annotated.js';
        }))
        // .pipe(plug.concat('all.min.js'))
        // .pipe(plug.uglify({mangle: true}))
        // .pipe(gulp.dest(pkg.paths.client + '/app'));
        .pipe(gulp.dest(pkg.paths.client + '/app/avengers'));
});

/**
 * @desc Lint the code
 */
gulp.task('analyze', function() {
    log('Linting the JavaScript');

    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp
        .src(sources)
        .pipe(plug.jshint('./.jshintrc'))
        .pipe(plug.jshint.reporter('jshint-stylish'))
        .pipe(plug.jscs('./.jscsrc'));
});

/**
 * @desc Create $templateCache from the html templates
 */
gulp.task('templatecache', function() {
    log('Creating an AngularJS $templateCache');

    return gulp
        .src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Minify and bundle the app's JavaScript
 */
gulp.task('js', ['analyze', 'templatecache'], function() {
    log('Bundling, minifying, and copying the app\'s JavaScript');

    var source = [].concat(pkg.paths.js, pkg.paths.stage + 'templates.js');
    return gulp
        .src(source)
       // .pipe(plug.sourcemaps.init()) // get screwed up in the file rev process
        .pipe(plug.concat('all.min.js'))
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        // .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function() {
    log('Bundling, minifying, and copying the Vendor JavaScript');
    return gulp.src(pkg.paths.vendorjs)
        .pipe(plug.concat('vendor.min.js'))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify())
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage)); // + 'vendor'));
});

/**
 * @desc Minify and bundle the CSS
 */
gulp.task('css', function() {
    log('Bundling, minifying, and copying the app\'s CSS');
    return gulp.src(pkg.paths.css)
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.autoprefixer('last 2 version', '> 5%'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function() {
    log('Compressing, bundling, copying vendor CSS');
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Copy fonts
 */
gulp.task('fonts', function() {
    var dest = pkg.paths.stage + 'fonts';
    log('Copying fonts');
    return gulp
        .src(pkg.paths.fonts)
        .pipe(gulp.dest(dest));
});

/**
 * @desc Compress images
 */
gulp.task('images', function() {
    var dest = pkg.paths.stage + 'content/images';
    log('Compressing, caching, and copying images');
    return gulp
        .src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(dest));
});

/**
 * @desc Inject all the files into the new index.html
 * rev, but no map
 */
gulp.task('rev-and-inject',
    ['js', 'vendorjs', 'css', 'vendorcss'], function() {
        log('Rev\'ing files and building index.html');

        var minified = pkg.paths.stage + '**/*.min.*';
        var index = pkg.paths.client + 'index.html';
        var minFilter = plug.filter(['**/*.min.*', '!**/*.map']);
        var indexFilter = plug.filter(['index.html']);

        var stream = gulp
            // Write the revisioned files
            .src([].concat(minified, index)) // add all staged min files and index.html
            .pipe(minFilter) // filter the stream to minified css and js
            .pipe(plug.rev()) // create files with rev's
            .pipe(gulp.dest(pkg.paths.stage)) // write the rev files
            .pipe(minFilter.restore()) // remove filter, back to original stream

            // inject the files into index.html
            .pipe(indexFilter) // filter to index.html
            .pipe(inject('content/vendor.min.css', 'inject-vendor'))
            .pipe(inject('content/all.min.css'))
            .pipe(inject('vendor.min.js', 'inject-vendor'))
            .pipe(inject('all.min.js'))
            .pipe(gulp.dest(pkg.paths.stage)) // write the rev files
            .pipe(indexFilter.restore()) // remove filter, back to original stream

            // replace the files referenced in index.html with the rev'd files
            .pipe(plug.revReplace())         // Substitute in new filenames
            .pipe(gulp.dest(pkg.paths.stage)) // write the index.html file changes
            .pipe(plug.rev.manifest()) // create the manifest (must happen last or we screw up the injection)
            .pipe(gulp.dest(pkg.paths.stage)); // write the manifest

        function inject(path, name) {
            var glob = pkg.paths.stage + path;
            var options = {
                ignorePath: pkg.paths.stage.substring(1),
                read: false
            };
            if (name) { options.name = name; }
            return plug.inject(gulp.src(glob), options);
        }
    });

/**
 * @desc Stage the optimized app
 */
gulp.task('stage',
    ['rev-and-inject', 'images', 'fonts'], function() {
        log('Staging the optimized app');

        return gulp.src('').pipe(plug.notify({
            onLast: true,
            message: 'Deployed code to stage!'
        }));
    });

/**
 * @desc Remove all files from the build folder
 * One way to run clean before all tasks is to run
 * from the cmd line: gulp clean && gulp stage
 */
gulp.task('clean', function() {
    var paths = pkg.paths.build;
    log('Cleaning: ' + plug.util.colors.blue(paths));

    return gulp
        .src(paths, {read: false})
        .pipe(plug.rimraf({force: true}));
});

/**
 * @desc Watch files and build
 */
gulp.task('watch', function() {
    log('Watching all files');

    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var images = ['gulpfile.js'].concat(pkg.paths.images);
    var js = ['gulpfile.js'].concat(pkg.paths.js);

    gulp
        .watch(js, ['js', 'vendorjs'])
        .on('change', logWatch);

    gulp
        .watch(css, ['css', 'vendorcss'])
        .on('change', logWatch);

    gulp
        .watch(images, ['images'])
        .on('change', logWatch);

    function logWatch(event) {
        log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    }
});

/**
 * @desc Run all tests
 */
gulp.task('test-serve-midway', function() {
    log('Pre test serve');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];
    var options = {
        script: pkg.paths.server + 'app.js',
        env: {'NODE_ENV': 'dev', 'PORT': 8888}
    };
    plug.nodemon(options);
});

gulp.task('test', ['test-serve-midway'], function() {
//gulp.task('test', function() {
    log('Running tests');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];
    // var options = {
    //     script: pkg.paths.server + 'app.js',
    //     env: {'NODE_ENV': 'dev', 'PORT': 8888}
    // };
    // plug.nodemon(options);

    return gulp
        .src('./wardThisIsNotRealSoDoNotLookForItInsteadUseKarmaConf')
        .pipe(plug.plumber())
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
//            singleRun: true,
            delay: 5,
            action: 'run'  // run or watch
        }))
        // .pipe(plug.plumber.stop())
        .on('error', function(err) {
            // failed tests cause gulp to exit
            log(err);
            throw err;
        });
});

/**
 * serve the dev environment, with debug,
 * and with node inspector
 */
gulp.task('serve-dev-debug', function() {
    serve({env: 'dev', debug: '--debug'});
    startLivereload('development');
});

/**
 * serve the dev environment, with debug-brk,
 * and with node inspector
 */
gulp.task('serve-dev-debug-brk', function() {
    serve({env: 'dev', debug: '--debug-brk'});
    startLivereload('development');
});

/**
 * serve the dev environment
 */
gulp.task('serve-dev', function() {
    serve({env: 'dev'});
    startLivereload('development');
});

/**
 * serve the staging environment
 */
gulp.task('serve-stage', function() {
    serve({env: 'stage'});
    startLivereload('stage');
});

function startLivereload(env) {

    //TODO: gulp-livereload is failing due to tiny-lr issue. Re-enable when fixed.

    // var path = (env === 'stage' ? [pkg.paths.stage, pkg.paths.client + '/**'] : [pkg.paths.client + '/**']);
    // var options = {auto: true};
    // plug.livereload.listen(options);
    // gulp
    //     .watch(path)
    //     .on('change', function(file) {
    //         plug.livereload.changed(file.path);
    //     });

    // log('Serving from ' + env);
}

function serve(args) {
    var options = {
        script: pkg.paths.server + 'app.js',
        delayTime: 1,
        ext: 'html js',
        env: {'NODE_ENV': args.env},
        watch: [
            'gulpfile.js',
            'package.json',
            pkg.paths.server,
            pkg.paths.client
        ]
    };

    if (args.debug) {
        gulp.src('', {read: false})
            .pipe(plug.shell(['node-inspector']));
        options.nodeArgs = [args.debug + '=5858'];
    }

    return plug.nodemon(options)
        //.on('change', tasks)
        .on('restart', function() {
            log('restarted!');
        });
}<commit_msg>Revert "modular: gulp testing tweaks"<commit_after>/* jshint camelcase:false */
var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./gulp/common.js');
var plug = require('gulp-load-plugins')();
var env = plug.util.env;
var log = plug.util.log;

gulp.task('help', plug.taskListing);

/**
 * @desc Annotate only
 *  Mostly for show.
 *  See the output of each file?
 *      Uncomment rename, comment concat and uglify
 *  See min'd and concat'd output?
 *      Comment rename, uncomment concat and uglify,
 *      add to index.html, then run it with `gulp serve-dev`.
 */
gulp.task('ngAnnotateTest', function() {
    log('Annotating AngularJS dependencies');
    var source = [].concat(pkg.paths.js);
    return gulp
        // .src(source)
        .src(pkg.paths.client + '/app/avengers/avengers.js')
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.rename(function(path) {
            path.extname = '.annotated.js';
        }))
        // .pipe(plug.concat('all.min.js'))
        // .pipe(plug.uglify({mangle: true}))
        // .pipe(gulp.dest(pkg.paths.client + '/app'));
        .pipe(gulp.dest(pkg.paths.client + '/app/avengers'));
});

/**
 * @desc Lint the code
 */
gulp.task('analyze', function() {
    log('Linting the JavaScript');

    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp
        .src(sources)
        .pipe(plug.jshint('./.jshintrc'))
        .pipe(plug.jshint.reporter('jshint-stylish'))
        .pipe(plug.jscs('./.jscsrc'));
});

/**
 * @desc Create $templateCache from the html templates
 */
gulp.task('templatecache', function() {
    log('Creating an AngularJS $templateCache');

    return gulp
        .src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Minify and bundle the app's JavaScript
 */
gulp.task('js', ['analyze', 'templatecache'], function() {
    log('Bundling, minifying, and copying the app\'s JavaScript');

    var source = [].concat(pkg.paths.js, pkg.paths.stage + 'templates.js');
    return gulp
        .src(source)
       // .pipe(plug.sourcemaps.init()) // get screwed up in the file rev process
        .pipe(plug.concat('all.min.js'))
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        // .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function() {
    log('Bundling, minifying, and copying the Vendor JavaScript');
    return gulp.src(pkg.paths.vendorjs)
        .pipe(plug.concat('vendor.min.js'))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify())
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage)); // + 'vendor'));
});

/**
 * @desc Minify and bundle the CSS
 */
gulp.task('css', function() {
    log('Bundling, minifying, and copying the app\'s CSS');
    return gulp.src(pkg.paths.css)
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.autoprefixer('last 2 version', '> 5%'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function() {
    log('Compressing, bundling, copying vendor CSS');
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Copy fonts
 */
gulp.task('fonts', function() {
    var dest = pkg.paths.stage + 'fonts';
    log('Copying fonts');
    return gulp
        .src(pkg.paths.fonts)
        .pipe(gulp.dest(dest));
});

/**
 * @desc Compress images
 */
gulp.task('images', function() {
    var dest = pkg.paths.stage + 'content/images';
    log('Compressing, caching, and copying images');
    return gulp
        .src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(dest));
});

/**
 * @desc Inject all the files into the new index.html
 * rev, but no map
 */
gulp.task('rev-and-inject',
    ['js', 'vendorjs', 'css', 'vendorcss'], function() {
        log('Rev\'ing files and building index.html');

        var minified = pkg.paths.stage + '**/*.min.*';
        var index = pkg.paths.client + 'index.html';
        var minFilter = plug.filter(['**/*.min.*', '!**/*.map']);
        var indexFilter = plug.filter(['index.html']);

        var stream = gulp
            // Write the revisioned files
            .src([].concat(minified, index)) // add all staged min files and index.html
            .pipe(minFilter) // filter the stream to minified css and js
            .pipe(plug.rev()) // create files with rev's
            .pipe(gulp.dest(pkg.paths.stage)) // write the rev files
            .pipe(minFilter.restore()) // remove filter, back to original stream

            // inject the files into index.html
            .pipe(indexFilter) // filter to index.html
            .pipe(inject('content/vendor.min.css', 'inject-vendor'))
            .pipe(inject('content/all.min.css'))
            .pipe(inject('vendor.min.js', 'inject-vendor'))
            .pipe(inject('all.min.js'))
            .pipe(gulp.dest(pkg.paths.stage)) // write the rev files
            .pipe(indexFilter.restore()) // remove filter, back to original stream

            // replace the files referenced in index.html with the rev'd files
            .pipe(plug.revReplace())         // Substitute in new filenames
            .pipe(gulp.dest(pkg.paths.stage)) // write the index.html file changes
            .pipe(plug.rev.manifest()) // create the manifest (must happen last or we screw up the injection)
            .pipe(gulp.dest(pkg.paths.stage)); // write the manifest

        function inject(path, name) {
            var glob = pkg.paths.stage + path;
            var options = {
                ignorePath: pkg.paths.stage.substring(1),
                read: false
            };
            if (name) { options.name = name; }
            return plug.inject(gulp.src(glob), options);
        }
    });

/**
 * @desc Stage the optimized app
 */
gulp.task('stage',
    ['rev-and-inject', 'images', 'fonts'], function() {
        log('Staging the optimized app');

        return gulp.src('').pipe(plug.notify({
            onLast: true,
            message: 'Deployed code to stage!'
        }));
    });

/**
 * @desc Remove all files from the build folder
 * One way to run clean before all tasks is to run
 * from the cmd line: gulp clean && gulp stage
 */
gulp.task('clean', function() {
    var paths = pkg.paths.build;
    log('Cleaning: ' + plug.util.colors.blue(paths));

    return gulp
        .src(paths, {read: false})
        .pipe(plug.rimraf({force: true}));
});

/**
 * @desc Watch files and build
 */
gulp.task('watch', function() {
    log('Watching all files');

    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var images = ['gulpfile.js'].concat(pkg.paths.images);
    var js = ['gulpfile.js'].concat(pkg.paths.js);

    gulp
        .watch(js, ['js', 'vendorjs'])
        .on('change', logWatch);

    gulp
        .watch(css, ['css', 'vendorcss'])
        .on('change', logWatch);

    gulp
        .watch(images, ['images'])
        .on('change', logWatch);

    function logWatch(event) {
        log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    }
});

/**
 * @desc Run all tests
 */
gulp.task('test-serve-midway', function() {
    log('Pre test serve');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];
    var options = {
        script: pkg.paths.server + 'app.js',
        env: {'NODE_ENV': 'dev', 'PORT': 8888}
    };
});

//gulp.task('test', ['test-serve-midway'], function() {
gulp.task('test', function() {
    log('Running tests');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];
    // var options = {
    //     script: pkg.paths.server + 'app.js',
    //     env: {'NODE_ENV': 'dev', 'PORT': 8888}
    // };
    // plug.nodemon(options);

    return gulp
        .src('./useKarmaConfAndNotThis')
        .pipe(plug.plumber())
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
//            singleRun: true,
            delay: 5,
            action: 'run'  // run or watch
        }))
        // .pipe(plug.plumber.stop())
        .on('error', function(err) {
            // failed tests cause gulp to exit
            log(err);
            throw err;
        });
});

/**
 * serve the dev environment, with debug,
 * and with node inspector
 */
gulp.task('serve-dev-debug', function() {
    serve({env: 'dev', debug: '--debug'});
    startLivereload('development');
});

/**
 * serve the dev environment, with debug-brk,
 * and with node inspector
 */
gulp.task('serve-dev-debug-brk', function() {
    serve({env: 'dev', debug: '--debug-brk'});
    startLivereload('development');
});

/**
 * serve the dev environment
 */
gulp.task('serve-dev', function() {
    serve({env: 'dev'});
    startLivereload('development');
});

/**
 * serve the staging environment
 */
gulp.task('serve-stage', function() {
    serve({env: 'stage'});
    startLivereload('stage');
});

function startLivereload(env) {

    //TODO: gulp-livereload is failing due to tiny-lr issue. Re-enable when fixed.

    // var path = (env === 'stage' ? [pkg.paths.stage, pkg.paths.client + '/**'] : [pkg.paths.client + '/**']);
    // var options = {auto: true};
    // plug.livereload.listen(options);
    // gulp
    //     .watch(path)
    //     .on('change', function(file) {
    //         plug.livereload.changed(file.path);
    //     });

    // log('Serving from ' + env);
}

function serve(args) {
    var options = {
        script: pkg.paths.server + 'app.js',
        delayTime: 1,
        ext: 'html js',
        env: {'NODE_ENV': args.env},
        watch: [
            'gulpfile.js',
            'package.json',
            pkg.paths.server,
            pkg.paths.client
        ]
    };

    if (args.debug) {
        gulp.src('', {read: false})
            .pipe(plug.shell(['node-inspector']));
        options.nodeArgs = [args.debug + '=5858'];
    }

    return plug.nodemon(options)
        //.on('change', tasks)
        .on('restart', function() {
            log('restarted!');
        });
}<|endoftext|>


<commit_before>var assert = require('assert');
var _ = require('lodash');
var Subscriber = require("rabbitmq-pubsub").Subscriber;
var Publisher = require("rabbitmq-pubsub").Publisher;

describe('PublisherSubscriber', function() {
  "use strict";
  this.timeout(15e3);
  var TestManager = require('../testManager');
  var testMngr = new TestManager();

  var publisher;

  before(function(done) {
      testMngr.start().then(done, done);
  });
  after(function(done) {
      testMngr.stop().then(done, done);
  });

  describe('StartStop', function() {
    it.skip('should start and stop the publisher', function(done) {
      publisher = new Publisher({exchange:"user.new"});
      publisher.start().delay(1e3).then(publisher.stop).then(done, done);
    });
  });
});
<commit_msg>use es6 for testSubscriber.js<commit_after>
import {Subscriber, Publisher} from 'rabbitmq-pubsub';

describe('PublisherSubscriber', function() {
  this.timeout(15e3);
  var TestManager = require('../testManager');
  var testMngr = new TestManager();

  var publisher;

  before(function(done) {
      testMngr.start().then(done, done);
  });
  after(function(done) {
      testMngr.stop().then(done, done);
  });

  describe('StartStop', function() {
    it.skip('should start and stop the publisher', function(done) {
      publisher = new Publisher({exchange:"user.new"});
      publisher.start().delay(1e3).then(publisher.stop).then(done, done);
    });
  });
});
<|endoftext|>


<commit_before>// From http://knpuniversity.com/screencast/gulp/version-cache-busting

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

var config = {
    assetsDir: 'app/Resources/assets',
    sassPattern: 'sass/**/*.scss',
    production: !!plugins.util.env.production,
    sourceMaps: false,
    renameCss: false,
    renameJs: false,
    cleanCss: true,
    uglifyJs: false,
    dropConsole: false,
    vendorDir: 'vendor',
    bowerDir: 'vendor/bower-asset',
    npmDir: 'vendor/npm-asset'
};
var app = {};

app.addStyle = function(paths, outputFilename) {
    gulp.src(paths)
        .pipe(plugins.plumber())
        .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
        .pipe(plugins.sass().on('error', plugins.sass.logError))
        .pipe(plugins.concat('css/'+outputFilename))
        .pipe(config.cleanCss ? plugins.cleanCss({compatibility: ''}) : plugins.util.noop())
        .pipe(config.renameCss ? plugins.rename({extname: '.min.css'}) : plugins.util.noop())
        .pipe(gulp.dest('web'))
        .pipe(plugins.rev())
        .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
        .pipe(gulp.dest('web'))
        // write the rev-manifest.json file for gulp-rev
        .pipe(plugins.rev.manifest('app/Resources/assets/rev-manifest.json', {
            merge: true
        }))
        .pipe(gulp.dest('.'));
};

app.addScript = function(paths, outputFilename) {
    gulp.src(paths)
        .pipe(plugins.plumber())
        .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
        .pipe(plugins.concat('js/'+outputFilename))
        .pipe(config.uglifyJs ? plugins.uglify({compress: {drop_console:config.dropConsole,hoist_vars:false,hoist_funs:false,passes:2}}) : plugins.util.noop())
        .pipe(config.renameJs ? plugins.rename({extname: '.min.js'}) : plugins.util.noop())
        .pipe(gulp.dest('web'))
        .pipe(plugins.rev())
        .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
        .pipe(gulp.dest('web'))
        // write the rev-manifest.json file for gulp-rev
        .pipe(plugins.rev.manifest('app/Resources/assets/rev-manifest.json', {
            merge: true
        }))
        .pipe(gulp.dest('.'));
};

app.copy = function(srcFiles, outputDir) {
    gulp.src(srcFiles)
        .pipe(gulp.dest(outputDir));
};

gulp.task('styles', function() {
    app.addStyle([
        config.assetsDir+'/sass/application.scss',
        // - normalize and h5bp resets are part of custom _bootstrap.scss
        //config.bowerDir+'/normalize.css/normalize.css',
        //config.bowerDir+'/html5-boilerplate/dist/css/main.css',
        //  - bootstrap loaded via application.scss above
        //config.bowerDir+'/bootstrap-sass/assets/stylesheets/_bootstrap.scss',
        //config.bowerDir+'/bootstrap/dist/css/bootstrap.css',
        //config.bowerDir+'/font-awesome/css/font-awesome.css',
        // -- all below now loaded from application.scss
        //config.bowerDir+'/fancytree/dist/skin-lion/ui.fancytree.css',
        //config.assetsDir+'/sass/layout.scss',
        //config.assetsDir+'/sass/styles.scss',
        //config.assetsDir+'/sass/overrides.scss',
        //config.vendorDir+'/mervick/material-design-icons/scss/material-icons.scss'
    ], 'main.css');
});

gulp.task('scripts', function() {
    app.addScript([
        config.bowerDir+'/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min.js',
    ], 'modernizr.js');
    app.addScript([
        config.bowerDir+'/html5-boilerplate/dist/js/plugins.js',
        config.bowerDir+'/jquery/dist/jquery.js',
        config.bowerDir+'/jquery-ui/jquery-ui.js',
        config.bowerDir+'/bootstrap-sass/assets/javascripts/bootstrap.js',
        config.bowerDir+'/fancytree/dist/jquery.fancytree-all.js',
        config.bowerDir+'/ui-contextmenu/jquery.ui-contextmenu.js',
        config.bowerDir+'/bootstrap-multiselect/dist/js/bootstrap-multiselect.js',
        config.bowerDir+'/select2/dist/js/select2.full.js',
        config.vendorDir+'/tetranz/select2entity-bundle/Tetranz/Select2EntityBundle/Resources/public/js/select2entity.js',
        config.bowerDir+'/twbs-pagination/jquery.twbsPagination.js',
        config.assetsDir+'/js/application.js',
        config.assetsDir+'/js/lsdoc/index.js',
        config.assetsDir+'/js/cftree/view.js',
    ], 'site.js');
});

gulp.task('fonts', function() {
    app.copy([
            //config.bowerDir+'/font-awesome/fonts/*',
            config.bowerDir+'/bootstrap-sass/assets/fonts/bootstrap/glyphicons-halflings*',
            config.vendorDir+'/mervick/material-design-icons/fonts/MaterialIcons*'
        ],
        'web/fonts'
    );
});

gulp.task('images', function() {
    app.copy(
        //config.bowerDir+'/font-awesome/fonts/*',
        config.bowerDir+'/fancytree/dist/skin-lion/icons.gif',
        'web/img/fancytree/'
    );
});

gulp.task('watch', function() {
    gulp.watch(config.assetsDir+'/'+config.sassPattern, ['styles']);
    gulp.watch(config.assetsDir+'/js/**/*.js', ['scripts']);
});

//gulp.task('default', ['styles', 'scripts', 'fonts', 'watch']);
gulp.task('default', ['styles', 'scripts', 'fonts', 'images']);

<commit_msg>Gulp file for association table view<commit_after>// From http://knpuniversity.com/screencast/gulp/version-cache-busting

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

var config = {
    assetsDir: 'app/Resources/assets',
    sassPattern: 'sass/**/*.scss',
    production: !!plugins.util.env.production,
    sourceMaps: false,
    renameCss: false,
    renameJs: false,
    cleanCss: true,
    uglifyJs: false,
    dropConsole: false,
    vendorDir: 'vendor',
    bowerDir: 'vendor/bower-asset',
    npmDir: 'vendor/npm-asset'
};
var app = {};

app.addStyle = function(paths, outputFilename) {
    gulp.src(paths)
        .pipe(plugins.plumber())
        .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
        .pipe(plugins.sass().on('error', plugins.sass.logError))
        .pipe(plugins.concat('css/'+outputFilename))
        .pipe(config.cleanCss ? plugins.cleanCss({compatibility: ''}) : plugins.util.noop())
        .pipe(config.renameCss ? plugins.rename({extname: '.min.css'}) : plugins.util.noop())
        .pipe(gulp.dest('web'))
        .pipe(plugins.rev())
        .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
        .pipe(gulp.dest('web'))
        // write the rev-manifest.json file for gulp-rev
        .pipe(plugins.rev.manifest('app/Resources/assets/rev-manifest.json', {
            merge: true
        }))
        .pipe(gulp.dest('.'));
};

app.addScript = function(paths, outputFilename) {
    gulp.src(paths)
        .pipe(plugins.plumber())
        .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.init()))
        .pipe(plugins.concat('js/'+outputFilename))
        .pipe(config.uglifyJs ? plugins.uglify({compress: {drop_console:config.dropConsole,hoist_vars:false,hoist_funs:false,passes:2}}) : plugins.util.noop())
        .pipe(config.renameJs ? plugins.rename({extname: '.min.js'}) : plugins.util.noop())
        .pipe(gulp.dest('web'))
        .pipe(plugins.rev())
        .pipe(plugins.if(config.sourceMaps, plugins.sourcemaps.write('.')))
        .pipe(gulp.dest('web'))
        // write the rev-manifest.json file for gulp-rev
        .pipe(plugins.rev.manifest('app/Resources/assets/rev-manifest.json', {
            merge: true
        }))
        .pipe(gulp.dest('.'));
};

app.copy = function(srcFiles, outputDir) {
    gulp.src(srcFiles)
        .pipe(gulp.dest(outputDir));
};

gulp.task('styles', function() {
    app.addStyle([
        config.assetsDir+'/sass/application.scss',
        // - normalize and h5bp resets are part of custom _bootstrap.scss
        //config.bowerDir+'/normalize.css/normalize.css',
        //config.bowerDir+'/html5-boilerplate/dist/css/main.css',
        //  - bootstrap loaded via application.scss above
        //config.bowerDir+'/bootstrap-sass/assets/stylesheets/_bootstrap.scss',
        //config.bowerDir+'/bootstrap/dist/css/bootstrap.css',
        //config.bowerDir+'/font-awesome/css/font-awesome.css',
        // -- all below now loaded from application.scss
        //config.bowerDir+'/fancytree/dist/skin-lion/ui.fancytree.css',
        //config.assetsDir+'/sass/layout.scss',
        //config.assetsDir+'/sass/styles.scss',
        //config.assetsDir+'/sass/overrides.scss',
        //config.vendorDir+'/mervick/material-design-icons/scss/material-icons.scss'
    ], 'main.css');
});

gulp.task('scripts', function() {
    app.addScript([
        config.bowerDir+'/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min.js',
    ], 'modernizr.js');
    app.addScript([
        config.bowerDir+'/html5-boilerplate/dist/js/plugins.js',
        config.bowerDir+'/jquery/dist/jquery.js',
        config.bowerDir+'/jquery-ui/jquery-ui.js',
        config.bowerDir+'/bootstrap-sass/assets/javascripts/bootstrap.js',
        config.bowerDir+'/fancytree/dist/jquery.fancytree-all.js',
        config.bowerDir+'/datatables.net/js/jquery.dataTables.js',
        config.bowerDir+'/datatables.net-bs/js/dataTables.bootstrap.js',
        config.bowerDir+'/datatables.net-fixedheader/js/dataTables.fixedHeader.js',
        config.bowerDir+'/datatables.net-scroller/js/dataTables.scroller.js',
        config.bowerDir+'/datatables.net-select/js/dataTables.select.js',
        config.bowerDir+'/ui-contextmenu/jquery.ui-contextmenu.js',
        config.bowerDir+'/bootstrap-multiselect/dist/js/bootstrap-multiselect.js',
        config.bowerDir+'/select2/dist/js/select2.full.js',
        config.vendorDir+'/tetranz/select2entity-bundle/Tetranz/Select2EntityBundle/Resources/public/js/select2entity.js',
        config.bowerDir+'/twbs-pagination/jquery.twbsPagination.js',
        config.assetsDir+'/js/application.js',
        config.assetsDir+'/js/lsdoc/index.js',
        config.assetsDir+'/js/cftree/view.js',
    ], 'site.js');
});

gulp.task('fonts', function() {
    app.copy([
            //config.bowerDir+'/font-awesome/fonts/*',
            config.bowerDir+'/bootstrap-sass/assets/fonts/bootstrap/glyphicons-halflings*',
            config.vendorDir+'/mervick/material-design-icons/fonts/MaterialIcons*'
        ],
        'web/fonts'
    );
});

gulp.task('images', function() {
    app.copy(
        //config.bowerDir+'/font-awesome/fonts/*',
        config.bowerDir+'/fancytree/dist/skin-lion/icons.gif',
        'web/img/fancytree/'
    );
});

gulp.task('watch', function() {
    gulp.watch(config.assetsDir+'/'+config.sassPattern, ['styles']);
    gulp.watch(config.assetsDir+'/js/**/*.js', ['scripts']);
});

//gulp.task('default', ['styles', 'scripts', 'fonts', 'watch']);
gulp.task('default', ['styles', 'scripts', 'fonts', 'images']);

<|endoftext|>


<commit_before>"use strict";

/*global nodeca, _*/
var NLib = require('nlib');
var Async = NLib.Vendor.Async;
var ReCaptcha = NLib.ReCaptcha;
var AuthLink = nodeca.models.users.AuthLink;
var User = nodeca.models.users.User;

// Validate input parameters
//
var params_schema = {
  email: {
    type: "string",
    format: "email",
    required: true
  },
  pass: {
    type: "string",
    minLength: 8,
    required: true
  },
  nick: {
    type: "string",
    minLength: 1,
    required: true
  },
  recaptcha_challenge_field: {
    type: "string",
  },
  recaptcha_response_field: {
    type: "string",
  }
};
nodeca.validate(params_schema);

/**
 * users.auth.register.exec(params, callback) -> Void
 *
 * ##### Params
 * - email(String):       Email
 * - pass(String):        Password
 * - nick(String):        Nickname
 *
 * Register new user
 *
 **/
module.exports = function (params, next) {
  var env = this;
  var user;

  var errors = {};

  // FIXME get real back url
  var back_url = nodeca.runtime.router.linkTo('forum.index');

  Async.series([
    // recaptcha validation
    function(callback) {
      var private_key = nodeca.config.recaptcha.private_key;
      var user_ip = env.request.ip;
      var challenge = params.recaptcha_challenge_field;
      var response = params.recaptcha_response_field;

      ReCaptcha.verify(private_key, user_ip, challenge, response, function(err, result){
        if (err) {
          callback(err);
          return;
        }

        // user send wrong captcha code
        if (!result) {
          errors['recaptcha'] = env.helpers.t('common.recaptcha.fail');
        }
        callback();
      });
    },
    // is email uniq?
    function(callback) {
      AuthLink.findOne({ 'providers.email': params.email }).setOptions({ lean: true })
          .exec(function(err, doc){
        if (err) {
          callback(err);
          return;
        }
        if (_.isEmpty(doc)) {
          errors['email'] = env.helpers.t('users.auth.reg_form.errors.email_exists');
        }
        callback();
      });
    },
    // is nick unque?
    function(callback) {
      User.findOne({ 'nick': params.nick}).setOptions({ lean: true })
          .exec(function(err, doc){
        if (err) {
          callback(err);
          return;
        }
        if (_.isEmpty(doc)) {
          errors['nick'] = env.helpers.t('users.auth.reg_form.errors.nick_exists');
        }

        callback();
      });
    }

  ], function(err) {
    if (err) {
      next(err);
    }
    if (!_.isEmpty(errors)) {
      next({
        statusCode: 401,
        body: errors
      });
      return;
    }

    user = new User(params);
    user._last_visit_ts = user.joined_ts = new Date();
    user._last_visit_ip = env.request.ip;
    user.locale = nodeca.config.locales['default'];
    // FIXME set groups

    user.save(function(err, user) {
      var link,
          provider;

      if (err) {
        next(err);
        return;
      }

      link = new AuthLink({ 'user_id': user._id });
      provider = link.providers.create({
        'provider': 'email',
        'email': params.email
      });
      provider.setPass(params.pass);
      link.providers.push(provider);

      link.save(function(err, link){
        if (err) {
          next(err);
          return;
        }
        next();
      });
    });
  });
};
<commit_msg>Fixed last commit<commit_after>"use strict";

/*global nodeca, _*/
var NLib = require('nlib');
var Async = NLib.Vendor.Async;
var ReCaptcha = NLib.ReCaptcha;
var AuthLink = nodeca.models.users.AuthLink;
var User = nodeca.models.users.User;

// Validate input parameters
//
var params_schema = {
  email: {
    type: "string",
    format: "email",
    required: true
  },
  pass: {
    type: "string",
    minLength: 8,
    required: true
  },
  nick: {
    type: "string",
    minLength: 1,
    required: true
  },
  recaptcha_challenge_field: {
    type: "string",
  },
  recaptcha_response_field: {
    type: "string",
  }
};
nodeca.validate(params_schema);

/**
 * users.auth.register.exec(params, callback) -> Void
 *
 * ##### Params
 * - email(String):       Email
 * - pass(String):        Password
 * - nick(String):        Nickname
 *
 * Register new user
 *
 **/
module.exports = function (params, next) {
  var env = this;
  var user;

  var errors = {};

  // FIXME get real back url
  var back_url = nodeca.runtime.router.linkTo('forum.index');

  Async.series([
    // recaptcha validation
    function(callback) {
      var private_key = nodeca.config.recaptcha.private_key;
      var user_ip = env.request.ip;
      var challenge = params.recaptcha_challenge_field;
      var response = params.recaptcha_response_field;

      ReCaptcha.verify(private_key, user_ip, challenge, response, function(err, result){
        if (err) {
          callback(err);
          return;
        }

        // user send wrong captcha code
        if (!result) {
          errors['recaptcha'] = env.helpers.t('common.recaptcha.fail');
        }
        callback();
      });
    },
    // is email uniq?
    function(callback) {
      AuthLink.findOne({ 'providers.email': params.email }).setOptions({ lean: true })
          .exec(function(err, doc){
        if (err) {
          callback(err);
          return;
        }
        if (!_.isEmpty(doc)) {
          errors['email'] = env.helpers.t('users.auth.reg_form.errors.email_exists');
        }
        callback();
      });
    },
    // is nick unque?
    function(callback) {
      User.findOne({ 'nick': params.nick}).setOptions({ lean: true })
          .exec(function(err, doc){
        if (err) {
          callback(err);
          return;
        }
        if (!_.isEmpty(doc)) {
          errors['nick'] = env.helpers.t('users.auth.reg_form.errors.nick_exists');
        }

        callback();
      });
    }

  ], function(err) {
    if (err) {
      next(err);
    }
    if (!_.isEmpty(errors)) {
      next({
        statusCode: 401,
        body: errors
      });
      return;
    }

    user = new User(params);
    user._last_visit_ts = user.joined_ts = new Date();
    user._last_visit_ip = env.request.ip;
    user.locale = nodeca.config.locales['default'];
    // FIXME set groups

    user.save(function(err, user) {
      var link,
          provider;

      if (err) {
        next(err);
        return;
      }

      link = new AuthLink({ 'user_id': user._id });
      provider = link.providers.create({
        'provider': 'email',
        'email': params.email
      });
      provider.setPass(params.pass);
      link.providers.push(provider);

      link.save(function(err, link){
        if (err) {
          next(err);
          return;
        }
        next();
      });
    });
  });
};
<|endoftext|>


<commit_before>var gulp = require("gulp");
var plugins = require("gulp-load-plugins")();
plugins.del = require("del");

require("../gulp-ps-tasks/tasks")(gulp, plugins);<commit_msg>Plugins should be defined in the gulp-ps-tasks tasks file so every plugin folder doesn't need to install its own gulp plugins. Use gulp-ps-tasks's gulp plugins instead.<commit_after>var gulp = require("gulp");

require("../gulp-ps-tasks/tasks")(gulp);<|endoftext|>


<commit_before>var gulp = require('gulp'),
    chug = require('gulp-chug'),
    http = require('http'),
    fs = require('fs');

gulp.task('spec', function(cb) {
    http.get({
        hostname: process.env.API_HOST || 'services.ci.reachmail.net',
        path: '/spec',
        headers: { accept: 'application/json' }
    },
    function(response) {
        response.pipe(fs.createWriteStream("./spec.json"));
        cb();
    });
});

gulp.task('ci', ['spec'], function() {
    return gulp.src('./*/gulpfile.js')
        .pipe(chug({ tasks: ['ci'].concat(process.argv.slice(2)) }));
});

gulp.task('deploy', ['spec'], function() {
    return gulp.src('./*/gulpfile.js')
        .pipe(chug({ tasks: ['deploy'].concat(process.argv.slice(2) }));
});<commit_msg>Migrated to CLI params for the .NET wrapper build.<commit_after>var gulp = require('gulp'),
    chug = require('gulp-chug'),
    http = require('http'),
    fs = require('fs');

gulp.task('spec', function(cb) {
    http.get({
        hostname: process.env.API_HOST || 'services.ci.reachmail.net',
        path: '/spec',
        headers: { accept: 'application/json' }
    },
    function(response) {
        response.pipe(fs.createWriteStream("./spec.json"));
        cb();
    });
});

gulp.task('ci', ['spec'], function() {
    return gulp.src('./*/gulpfile.js')
        .pipe(chug({ tasks: ['ci'].concat(process.argv.slice(2)) }));
});

gulp.task('deploy', ['spec'], function() {
    return gulp.src('./*/gulpfile.js')
        .pipe(chug({ tasks: ['deploy'].concat(process.argv.slice(2)) }));
});<|endoftext|>


<commit_before>const gulp = require('gulp');
const peg = require('gulp-peg');
const mocha = require('gulp-mocha');
const babel = require('gulp-babel');

const GRAMMAR_PATH = 'src/grammar/*.pegjs';
const HELPER_PATH = 'src/helper/**/*.js';

gulp.task('make:grammar', () => {
  gulp.src(GRAMMAR_PATH)
    .pipe(peg({ allowedStartRules: ['InitBlock'] }))
    .pipe(gulp.dest('build/grammar/'));
});

gulp.task('make:helpers', () => {
  gulp.src(HELPER_PATH)
    .pipe(babel())
    .pipe(gulp.dest('build/'));
});

gulp.task('default', [
  'make:grammar',
  'make:helpers',
]);

gulp.task('test:grammar', () => {
  gulp.src('test/grammar/*.test.js')
    .pipe(mocha());
});

gulp.task('test:parser', () => {
  gulp.src('test/grammar/parser.test.js')
    .pipe(mocha());
});

gulp.task('watch', () => {
  gulp.watch(GRAMMAR_PATH, ['make:grammar']);
  gulp.watch(HELPER_PATH, ['make:helpers']);
});
<commit_msg>adjust src path to new structure<commit_after>const gulp = require('gulp');
const peg = require('gulp-peg');
const mocha = require('gulp-mocha');
const babel = require('gulp-babel');

const GRAMMAR_PATH = 'src/grammar/*.pegjs';
const HELPER_PATH = 'src/**/*.js';

gulp.task('make:grammar', () => {
  gulp.src(GRAMMAR_PATH)
    .pipe(peg({ allowedStartRules: ['InitBlock'] }))
    .pipe(gulp.dest('build/grammar/'));
});

gulp.task('make:helpers', () => {
  gulp.src(HELPER_PATH)
    .pipe(babel())
    .pipe(gulp.dest('build/'));
});

gulp.task('default', [
  'make:grammar',
  'make:helpers',
]);

gulp.task('test:grammar', () => {
  gulp.src('test/grammar/*.test.js')
    .pipe(mocha());
});

gulp.task('test:parser', () => {
  gulp.src('test/grammar/parser.test.js')
    .pipe(mocha());
});

gulp.task('watch', () => {
  gulp.watch(GRAMMAR_PATH, ['make:grammar']);
  gulp.watch(HELPER_PATH, ['make:helpers']);
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');
var cssnano = require('gulp-cssnano');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');

gulp.task('workflow', function () {
  gulp.src('./src/scss/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(cssnano())
    .pipe(sourcemaps.write('./'))

  .pipe(gulp.dest('./dist/css/'))
});

//Watch task
gulp.task('default', function () {
  gulp.watch('./src/scss/**/*.scss', ['workflow']);
});<commit_msg>Remove pesky z-index optimizer<commit_after>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');
var cssnano = require('gulp-cssnano');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');

gulp.task('workflow', function () {
  gulp.src('./src/scss/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(cssnano({zindex: false}))
    .pipe(sourcemaps.write('./'))

  .pipe(gulp.dest('./dist/css/'))
});

//Watch task
gulp.task('default', function () {
  gulp.watch('./src/scss/**/*.scss', ['workflow']);
});<|endoftext|>


<commit_before>const gulp = require('gulp')
const browserSync = require('browser-sync').create()
const sass = require('gulp-sass')
const plumber = require('gulp-plumber')
const gutil = require('gulp-util')
const uncss = require('gulp-uncss')
const fs = require('fs')
const juice = require('juice')
const path = require('path')
const information = require(path.join(__dirname, 'working/information.json'))
const html2txt = require('gulp-html2txt')
const cheerio = require('cheerio')

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', () => {
  return gulp.src('working/scss/*.scss')
    // plumber is used so that the watch task does not break when there is some wrong code
    .pipe(plumber(function (error) {
      gutil.beep()
      console.log(error)
      this.emit('end')
    }))
    .pipe(sass())
    .pipe(gulp.dest('working/css'))
    .pipe(browserSync.stream())
})

// Compile sass into CSS, remove unneeded CSS and dump it into the working folder for use in build process
// it is not neccessary to create a build CSS file just for the purpose of building the final email
gulp.task('css', () => {
  return gulp.src('working/scss/*.scss')
    .pipe(plumber(function (error) {
      gutil.beep()
      console.log(error)
      this.emit('end')
    }))
    .pipe(sass())
    .pipe(uncss({
      html: ['working/index.html']
    }))
    .pipe(gulp.dest('working/css'))
})

/**
* replaces each instance of a replacelist key template in the string for the replacelist value
* @param {string}
* @param {object}
* @return {string}
*/
const replaceLinks = (str, replacelist = {}) => {
  // there has to be a string to pass through even if replacelist is empty
  if (str.length < 1) throw new Error('File is empty')
  // if there is no replacelist or it is empty, pass through the value
  let html = str
  if (Object.keys(replacelist).length !== 0) {
    for (const key of Object.keys(replacelist)) {
      let replacestring = new RegExp(`#{${key}}`, 'g')
      html = html.replace(replacestring, replacelist[key])
    }
    let basicReg = /#{(.*?)}/g
    let els = html.match(basicReg)
    if (els !== null) {
      // find all matches and filter out the fluff
      // TODO think about if a set would be more appropriate as it would only list the unique values
      /*
      let allElements = new Set(els.map(x => x.replace('#{','').replace('}', '')))
      console.log(`Warning: there are still ${allElements.size} elements not replaced: ${[...allElements]}'`)
      */
      let allElements = els.map(x => x.replace('#{', '').replace('}', ''))
      console.log(`Warning: there are still ${allElements.length} instances not replaced: ${allElements}`)
    }
    return html
  } else {
    console.log('Warning: no links are provided, html goes through as is.')
    return str
  }
}

/**
* creates a url parameter string from the links object given
* @param {object}
* @return {string}
*/
const createParameterString = (parameters) => {
  let availableUtmKeys = ['source', 'medium', 'name', 'term', 'content']
  let paramsArr = []

  // check if the parameters exist, otherwise don't bother
  if (parameters.utm || parameters.custom) {
    // loop through all the utm and custom keys
    for (const paramKeys of Object.keys(parameters)) {
      // loop through the inner keys of utm and custom
      for (const key of Object.keys(parameters[paramKeys])) {
        // don't add if it is empty or if it is not a string or number
        if (parameters[paramKeys][key] && (typeof parameters[paramKeys][key] === 'string' || typeof parameters[paramKeys][key] === 'number')) {
          // only add the keys that are valid utm keys, ignore the ones that are not correct
          // IGNORE OR ERROR?
          if (paramKeys === 'utm' && availableUtmKeys.indexOf(key) !== -1) {
            paramsArr.push(`utm_${key}=${parameters[paramKeys][key]}`)
          } else if (paramKeys !== 'utm') { // if the keys are not utm, you are free to add them
            paramsArr.push(`${key}=${parameters[paramKeys][key]}`)
          }
        }
      }
    }
  }
  // joining all parameters in a string
  // if there are no parameters, create an empty string
  let paramsString = paramsArr.length !== 0 ? `?${paramsArr.join('&')}` : ''
  return paramsString
}

/**
* replaces each instance of a href atrribute in the first argument for the values provided in the second argument
* @param {string}
* @param {string}
* @param {function}
* @return {string}
*/
const addParameters = (str, parameters = '', cheerio) => {
  // check if the createParameterString returns a non-empty string
  // to avoid all the work that is not needed
  if (parameters) {
    // load the cheerio instance for appending links
    const $ = cheerio.load(str, { decodeEntities: false })
    // create the parameter string that will be appended to each href

    // add the parameters to each href in the email
    $('a').each(function (i, el) {
      let origHref = $(this).attr('href')
      // if the split method returns an array that is longer than 1 element, it means that there is an existing parameter in it
      // append the parameters only if there is no existing parameters
      if (origHref.split('?').length === 1) {
        $(this).attr('href', origHref + parameters)
      }
    })
    return $.html()
  } else {
    // if there is nothing available, return as is
    return str
  }
}

gulp.task('premailer', (done) => {
  // read the html file
  return fs.readFile('working/index.html', 'utf-8', (err, html) => {
    if (err) throw (err)
    // read the css file
    fs.readFile('working/css/styles.css', 'utf-8', (err, css) => {
      if (err) throw (err)
      // replace the file path in the html file so that juice can find it, looking from the root of the project
      let email = html.replace('<link rel="stylesheet" href="css/styles.css">', '<link rel="stylesheet" href="working/css/styles.css">')
      juice.juiceResources(email, { preserveMediaQueries: true, applyStyleTags: true }, (err, html) => {
        if (err) throw (err)
        // replace the url placeholder and add url parameters
        let email = addParameters(replaceLinks(html, information.links), createParameterString(information.parameters), cheerio)
        fs.writeFile('build/index.html', email, (err) => {
          if (err) throw (err)
          done()
        })
      })
    })
  })
})

// convert html to txt
gulp.task('txt', () => {
  return gulp.src('build/index.html')
    .pipe(html2txt())
    .pipe(gulp.dest('build/'))
})

// start up browserSync
gulp.task('browserSync', () => {
  browserSync.init({
    server: 'working'
  })
})

// reload browserSync
gulp.task('reload', () => {
  browserSync.reload()
})

// watch scss and html files for changes
gulp.task('watchSassAndHtml', () => {
  gulp.watch('working/scss/*.scss', gulp.series('sass', 'reload'))
  gulp.watch('working/scss/*.scss', gulp.series('reload'))
})

gulp.task('build', gulp.series('css', 'premailer', 'txt'))
gulp.task('serve', gulp.series('sass', gulp.series('sass', 'browserSync', 'watchSassAndHtml')))

module.exports = {
  replaceLinks,
  addParameters,
  createParameterString
}
<commit_msg>add callbacks to the tasks so the watch function can finish and start up again<commit_after>const gulp = require('gulp')
const browserSync = require('browser-sync').create()
const sass = require('gulp-sass')
const plumber = require('gulp-plumber')
const gutil = require('gulp-util')
const uncss = require('gulp-uncss')
const fs = require('fs')
const juice = require('juice')
const path = require('path')
const information = require(path.join(__dirname, 'working/information.json'))
const html2txt = require('gulp-html2txt')
const cheerio = require('cheerio')

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', (done) => {
  return gulp.src('working/scss/*.scss')
    // plumber is used so that the watch task does not break when there is some wrong code
    .pipe(plumber(function (error) {
      gutil.beep()
      console.log(error)
      this.emit('end')
    }))
    .pipe(sass())
    .pipe(gulp.dest('working/css'))
    .pipe(browserSync.stream())
})

// Compile sass into CSS, remove unneeded CSS and dump it into the working folder for use in build process
// it is not neccessary to create a build CSS file just for the purpose of building the final email
gulp.task('css', () => {
  return gulp.src('working/scss/*.scss')
    .pipe(plumber(function (error) {
      gutil.beep()
      console.log(error)
      this.emit('end')
    }))
    .pipe(sass())
    .pipe(uncss({
      html: ['working/index.html']
    }))
    .pipe(gulp.dest('working/css'))
})

/**
* replaces each instance of a replacelist key template in the string for the replacelist value
* @param {string}
* @param {object}
* @return {string}
*/
const replaceLinks = (str, replacelist = {}) => {
  // there has to be a string to pass through even if replacelist is empty
  if (str.length < 1) throw new Error('File is empty')
  // if there is no replacelist or it is empty, pass through the value
  let html = str
  if (Object.keys(replacelist).length !== 0) {
    for (const key of Object.keys(replacelist)) {
      let replacestring = new RegExp(`#{${key}}`, 'g')
      html = html.replace(replacestring, replacelist[key])
    }
    let basicReg = /#{(.*?)}/g
    let els = html.match(basicReg)
    if (els !== null) {
      // find all matches and filter out the fluff
      // TODO think about if a set would be more appropriate as it would only list the unique values
      /*
      let allElements = new Set(els.map(x => x.replace('#{','').replace('}', '')))
      console.log(`Warning: there are still ${allElements.size} elements not replaced: ${[...allElements]}'`)
      */
      let allElements = els.map(x => x.replace('#{', '').replace('}', ''))
      console.log(`Warning: there are still ${allElements.length} instances not replaced: ${allElements}`)
    }
    return html
  } else {
    console.log('Warning: no links are provided, html goes through as is.')
    return str
  }
}

/**
* creates a url parameter string from the links object given
* @param {object}
* @return {string}
*/
const createParameterString = (parameters) => {
  let availableUtmKeys = ['source', 'medium', 'name', 'term', 'content']
  let paramsArr = []

  // check if the parameters exist, otherwise don't bother
  if (parameters.utm || parameters.custom) {
    // loop through all the utm and custom keys
    for (const paramKeys of Object.keys(parameters)) {
      // loop through the inner keys of utm and custom
      for (const key of Object.keys(parameters[paramKeys])) {
        // don't add if it is empty or if it is not a string or number
        if (parameters[paramKeys][key] && (typeof parameters[paramKeys][key] === 'string' || typeof parameters[paramKeys][key] === 'number')) {
          // only add the keys that are valid utm keys, ignore the ones that are not correct
          // IGNORE OR ERROR?
          if (paramKeys === 'utm' && availableUtmKeys.indexOf(key) !== -1) {
            paramsArr.push(`utm_${key}=${parameters[paramKeys][key]}`)
          } else if (paramKeys !== 'utm') { // if the keys are not utm, you are free to add them
            paramsArr.push(`${key}=${parameters[paramKeys][key]}`)
          }
        }
      }
    }
  }
  // joining all parameters in a string
  // if there are no parameters, create an empty string
  let paramsString = paramsArr.length !== 0 ? `?${paramsArr.join('&')}` : ''
  return paramsString
}

/**
* replaces each instance of a href atrribute in the first argument for the values provided in the second argument
* @param {string}
* @param {string}
* @param {function}
* @return {string}
*/
const addParameters = (str, parameters = '', cheerio) => {
  // check if the createParameterString returns a non-empty string
  // to avoid all the work that is not needed
  if (parameters) {
    // load the cheerio instance for appending links
    const $ = cheerio.load(str, { decodeEntities: false })
    // create the parameter string that will be appended to each href

    // add the parameters to each href in the email
    $('a').each(function (i, el) {
      let origHref = $(this).attr('href')
      // if the split method returns an array that is longer than 1 element, it means that there is an existing parameter in it
      // append the parameters only if there is no existing parameters
      if (origHref.split('?').length === 1) {
        $(this).attr('href', origHref + parameters)
      }
    })
    return $.html()
  } else {
    // if there is nothing available, return as is
    return str
  }
}

gulp.task('premailer', (done) => {
  // read the html file
  return fs.readFile('working/index.html', 'utf-8', (err, html) => {
    if (err) throw (err)
    // read the css file
    fs.readFile('working/css/styles.css', 'utf-8', (err, css) => {
      if (err) throw (err)
      // replace the file path in the html file so that juice can find it, looking from the root of the project
      let email = html.replace('<link rel="stylesheet" href="css/styles.css">', '<link rel="stylesheet" href="working/css/styles.css">')
      juice.juiceResources(email, { preserveMediaQueries: true, applyStyleTags: true }, (err, html) => {
        if (err) throw (err)
        // replace the url placeholder and add url parameters
        let email = addParameters(replaceLinks(html, information.links), createParameterString(information.parameters), cheerio)
        fs.writeFile('build/index.html', email, (err) => {
          if (err) throw (err)
          done()
        })
      })
    })
  })
})

// convert html to txt
gulp.task('txt', () => {
  return gulp.src('build/index.html')
    .pipe(html2txt())
    .pipe(gulp.dest('build/'))
})

// start up browserSync
gulp.task('browserSync', (done) => {
  browserSync.init({
    server: 'working'
  })
  done()
})

// reload browserSync
gulp.task('reload', (done) => {
  browserSync.reload()
  done()
})

// watch scss and html files for changes
gulp.task('watchSassAndHtml', () => {
  gulp.watch('working/scss/*.scss', gulp.parallel('sass', 'reload'))
  gulp.watch('working/*.html', gulp.series('reload'))
})

gulp.task('build', gulp.series('css', 'premailer', 'txt'))
gulp.task('serve', gulp.series('sass', gulp.parallel('browserSync', 'watchSassAndHtml')))

module.exports = {
  replaceLinks,
  addParameters,
  createParameterString
}
<|endoftext|>


<commit_before>global.root = __dirname;
require('./gulp/globals');

if (IS_RELEASE_BUILD) {
  console.log(gutil.colors.red('--release:'), 'Building release version (minified)...');
}

require('./docs/gulpfile')(gulp, IS_RELEASE_BUILD);

gulp.task('build-all-modules', function() {
  return series(
    gulp.src(['src/core/', 'src/components/*' ])
        .pipe(through2.obj(function(folder, enc, next) {
          var moduleId = folder.path.indexOf('components') > -1
              ? 'material.components.' + path.basename(folder.path)
              : 'material.' + path.basename(folder.path);
          var stream = (IS_RELEASE_BUILD && BUILD_MODE.useBower)
              ? series(buildModule(moduleId, true), buildModule(moduleId, false))
              : buildModule(moduleId, false);
          stream.on('end', function() { next(); });
        })),
    themeBuildStream()
      .pipe(BUILD_MODE.transform())
      .pipe(gulp.dest(path.join(BUILD_MODE.outputDir, 'core'))
  )).pipe(BUILD_MODE.transform());
});

function buildModule(module, isRelease) {
  if ( module.indexOf(".") < 0) {
    module = "material.components." + module;
  }
  gutil.log('Building ' + module + (isRelease && ' minified' || '') + ' ...');

  var name = module.split('.').pop();
  utils.copyDemoAssets(name, 'src/components/', 'dist/demos/');

  return utils.filesForModule(module)
        .pipe(filterNonCodeFiles())
        .pipe(gulpif('*.scss', buildModuleStyles(name)))
        .pipe(gulpif('*.js', buildModuleJs(name)))
        .pipe(BUILD_MODE.transform())
        .pipe(insert.prepend(config.banner))
        .pipe(gulpif(isRelease, buildMin()))
        .pipe(gulp.dest(BUILD_MODE.outputDir + name));

  function buildMin() {
    return lazypipe()
      .pipe(gulpif, /.css$/, minifyCss(),
        uglify({ preserveComments: 'some' })
          .on('error', function(e) {
            console.log('\x07',e.message);
            return this.end();
          }
        )
      )
      .pipe(rename, function(path) {
        path.extname = path.extname
          .replace(/.js$/, '.min.js')
          .replace(/.css$/, '.min.css');
      })
      .pipe(utils.buildModuleBower, name, VERSION)
      ();
  }

function buildModuleJs(name) {
  return lazypipe()
    .pipe(plumber())
    .pipe(ngAnnotate())
    .pipe(BUILD_MODE.transform())
    .pipe(concat, name + '.js')
    ();
}

function buildModuleStyles(name) {
  var files = [];
  config.themeBaseFiles.forEach(function(fileGlob) {
    files = files.concat(glob(fileGlob, { cwd: __dirname }));
  });
  var baseStyles = files.map(function(fileName) {
    return fs.readFileSync(fileName, 'utf8').toString();
  }).join('\n');

  return lazypipe()
    .pipe(insert.prepend, baseStyles)
    .pipe(gulpif, /theme.scss/,
      rename(name + '-default-theme.scss'), concat(name + '.scss')
    )
    .pipe(sass)
    .pipe(autoprefix)
    (); // invoke the returning fn to create our pipe
}

}

/** *****************************************
 *
 * Tasks for Watch features
 *
 * `gulp watch` - Watch, build and deploy all modules and css
 * `gulp watch-demo -c textfield` - Watch, build and deploy the 'textfield' demos
 * `gulp watch-demo -m material.components.textfield` - Watch, build and deploy the 'textfield' module's demos
 *
 ** ***************************************** */

gulp.task('watch', ['docs'], function() {
  gulp.watch(['docs/**/*', 'src/**/*'], ['build', 'docs']);
});

gulp.task('watch-demo', ['build-demo'], function() {
  var module = readModuleArg();
  var name = module.split('.').pop();
  var dir  = "/dist/demos/"+name.trim();
  gutil.log('\n',
    '-- Rebuilding', dir, 'when source files change...\n',
    '--', gutil.colors.green('Hint:'), 'Run',
    gutil.colors.cyan('`gulp server`'),
    'to start a livereload server in root, then navigate to\n',
    '--', gutil.colors.green('"dist/demos/' + name + '/"'), 'in your browser to develop.'
   );

  return gulp.watch('src/**/*', ['build-demo']);
});

gulp.task('site', function () {
  return gulp.src('dist/docs')
      .pipe(webserver({
        host: '0.0.0.0',
        livereload: true,
        port: LR_PORT,
        directoryListing: false
      }));
});

gulp.task('server', function() {
  return gulp.src('.')
    .pipe(webserver({
      host: '0.0.0.0',
      livereload: true,
      port: LR_PORT,
      directoryListing: true
    }));
});

/** *****************************************
 *
 * Tasks and functions for module Javascript
 *
 ** ***************************************** */

gulp.task('build-js', function() {
  return buildJs(IS_RELEASE_BUILD);
});

gulp.task('build-js-release', function() {
  return buildJs(true);
});

/**
 * Builds the entire component library javascript.
 * @param {boolean} isRelease Whether to build in release mode.
 */
global.buildJs = function buildJs(isRelease) {
  var jsFiles = config.jsBaseFiles.concat([path.join(config.paths, '*.js')]);

  gutil.log("building js files...");

  var jsBuildStream = gulp.src( jsFiles )
        .pipe(filterNonCodeFiles())
        .pipe(utils.buildNgMaterialDefinition())
        .pipe(plumber())
        .pipe(ngAnnotate())
        .pipe(utils.addJsWrapper(true));

  var jsProcess = series(jsBuildStream, themeBuildStream() )
        .pipe(concat('angular-material.js'))
        .pipe(BUILD_MODE.transform())
        .pipe(insert.prepend(config.banner))
        .pipe(gulp.dest(config.outputDir))
        .pipe(gulpif(isRelease, lazypipe()
          .pipe(uglify, { preserveComments: 'some' })
          .pipe(rename, { extname: '.min.js' })
          .pipe(gulp.dest, config.outputDir)
          ()
        ));

  return series(jsProcess, deployMaterialMocks())
};

// Deploy the `angular-material-mocks.js` file to the `dist` directory
global.deployMaterialMocks = function deployMaterialMocks() {

  return gulp.src(config.mockFiles)
    .pipe(gulp.dest(config.outputDir));

};

// builds the theming related css and provides it as a JS const for angular
global.themeBuildStream = function themeBuildStream() {
  return gulp.src( config.themeBaseFiles.concat(path.join(config.paths, '*-theme.scss')) )
    .pipe(concat('default-theme.scss'))
    .pipe(utils.hoistScssVariables())
    .pipe(sass())
    .pipe(utils.cssToNgConstant('material.core', '$MD_THEME_CSS'));
};

/** *****************************************
 *
 * Component Demos Tasks and commands
 *
 * Build and deploy demos for a module. This is
 * useful for debugging a specific module independent of
 * the docs build; which has all modules and all demos loaded.
 *
 * To build, watch for changes, and launch web server :
 *
 * ```sh
 *    gulp watch-demo -c button
 *    gulp server
 * ```
 *
 * To build demo files:
 *
 * ```sh
 *    gulp build-demo -c button
 * ```
 *
 ** ***************************************** */

gulp.task('build-demo', ['build', 'build-module-demo'], function() {
  return buildModule(readModuleArg(), false);
});

gulp.task('build-module-demo', function() {
  var mod = readModuleArg();
  var name = mod.split('.').pop();
  var demoIndexTemplate = fs.readFileSync(
    __dirname + '/docs/config/template/demo-index.template.html', 'utf8'
  ).toString();

  gutil.log('Building demos for', mod, '...');

  return utils.readModuleDemos(mod, function() {
    return lazypipe()
        .pipe(gulpif, /.css$/, sass())
        .pipe(gulpif, /.css$/, autoprefix())
        .pipe(gulp.dest, BUILD_MODE.outputDir + name)
        ();
  })
  .pipe(through2.obj(function(demo, enc, next) {
    fs.writeFileSync(
      path.resolve(BUILD_MODE.outputDir, name, demo.name, 'index.html'),
      _.template(demoIndexTemplate, demo)
    );
    next();
  }));

});

/** *****************************************
 *
 * Tasks and functions for Themes and CSS
 *
 ** ***************************************** */

/** *****************************************
 *
 * Internal helper functions
 *
 ** ***************************************** */

function readModuleArg() {
  var module = argv.c ? 'material.components.' + argv.c : (argv.module || argv.m);
  if (!module) {
    gutil.log('\nProvide a compnent argument via `-c`:',
      '\nExample: -c toast');
    gutil.log('\nOr provide a module argument via `--module` or `-m`.',
      '\nExample: --module=material.components.toast or -m material.components.dialog');
    process.exit(1);
  }
  return module;
}

global.filterNonCodeFiles = function filterNonCodeFiles() {
  return filter(function(file) {
    return !/demo|module\.json|\.spec.js|README/.test(file.path);
  });
};

global.autoprefix = function autoprefix() {
  return autoprefixer({browsers: [
    'last 2 versions', 'last 4 Android versions'
  ]});
};

//-- read in all files from gulp/tasks and create tasks for them
fs.readdirSync('./gulp/tasks')
    .filter(function (filename) {
      return filename.match(/\.js$/i);
    })
    .map(function (filename) {
      return {
        name: filename.substr(0, filename.length - 3),
        contents: require('./gulp/tasks/' + filename)
      };
    })
    .filter(function (file) {
      gulp.task(file.name, file.contents.dependencies, file.contents.task);
    });
<commit_msg>fix(build): enable build of component modules.<commit_after>global.root = __dirname;
require('./gulp/globals');

if (IS_RELEASE_BUILD) {
  console.log(gutil.colors.red('--release:'), 'Building release version (minified)...');
}

require('./docs/gulpfile')(gulp, IS_RELEASE_BUILD);

gulp.task('build-all-modules', function() {
  return series(
    gulp.src(['src/core/', 'src/components/*' ])
        .pipe(through2.obj(function(folder, enc, next) {
          var moduleId = folder.path.indexOf('components') > -1
              ? 'material.components.' + path.basename(folder.path)
              : 'material.' + path.basename(folder.path);
          var stream = (IS_RELEASE_BUILD && BUILD_MODE.useBower)
              ? series(buildModule(moduleId, true), buildModule(moduleId, false))
              : buildModule(moduleId, false);
          stream.on('end', function() { next(); });
        })),
    themeBuildStream()
      .pipe(BUILD_MODE.transform())
      .pipe(gulp.dest(path.join(BUILD_MODE.outputDir, 'core'))
  )).pipe(BUILD_MODE.transform());
});

function buildModule(module, isRelease) {
  if ( module.indexOf(".") < 0) {
    module = "material.components." + module;
  }
  gutil.log('Building ' + module + (isRelease && ' minified' || '') + ' ...');

  var name = module.split('.').pop();
  utils.copyDemoAssets(name, 'src/components/', 'dist/demos/');

  return utils.filesForModule(module)
        .pipe(filterNonCodeFiles())
        .pipe(gulpif('*.scss', buildModuleStyles(name)))
        .pipe(gulpif('*.js', buildModuleJs(name)))
        .pipe(BUILD_MODE.transform())
        .pipe(insert.prepend(config.banner))
        .pipe(gulpif(isRelease, buildMin()))
        .pipe(gulp.dest(BUILD_MODE.outputDir + name));

  function buildMin() {
    return lazypipe()
      .pipe(gulpif, /.css$/, minifyCss(),
        uglify({ preserveComments: 'some' })
          .on('error', function(e) {
            console.log('\x07',e.message);
            return this.end();
          }
        )
      )
      .pipe(rename, function(path) {
        path.extname = path.extname
          .replace(/.js$/, '.min.js')
          .replace(/.css$/, '.min.css');
      })
      .pipe(utils.buildModuleBower, name, VERSION)
      ();
  }

function buildModuleJs(name) {
  return lazypipe()
    .pipe(plumber)
    .pipe(ngAnnotate)
    .pipe(concat, name + '.js')
    ();
}

function buildModuleStyles(name) {
  var files = [];
  config.themeBaseFiles.forEach(function(fileGlob) {
    files = files.concat(glob(fileGlob, { cwd: __dirname }));
  });
  var baseStyles = files.map(function(fileName) {
    return fs.readFileSync(fileName, 'utf8').toString();
  }).join('\n');

  return lazypipe()
    .pipe(insert.prepend, baseStyles)
    .pipe(gulpif, /theme.scss/,
      rename(name + '-default-theme.scss'), concat(name + '.scss')
    )
    .pipe(sass)
    .pipe(autoprefix)
    (); // invoke the returning fn to create our pipe
}

}

/** *****************************************
 *
 * Tasks for Watch features
 *
 * `gulp watch` - Watch, build and deploy all modules and css
 * `gulp watch-demo -c textfield` - Watch, build and deploy the 'textfield' demos
 * `gulp watch-demo -m material.components.textfield` - Watch, build and deploy the 'textfield' module's demos
 *
 ** ***************************************** */

gulp.task('watch', ['docs'], function() {
  gulp.watch(['docs/**/*', 'src/**/*'], ['build', 'docs']);
});

gulp.task('watch-demo', ['build-demo'], function() {
  var module = readModuleArg();
  var name = module.split('.').pop();
  var dir  = "/dist/demos/"+name.trim();
  gutil.log('\n',
    '-- Rebuilding', dir, 'when source files change...\n',
    '--', gutil.colors.green('Hint:'), 'Run',
    gutil.colors.cyan('`gulp server`'),
    'to start a livereload server in root, then navigate to\n',
    '--', gutil.colors.green('"dist/demos/' + name + '/"'), 'in your browser to develop.'
   );

  return gulp.watch('src/**/*', ['build-demo']);
});

gulp.task('site', function () {
  return gulp.src('dist/docs')
      .pipe(webserver({
        host: '0.0.0.0',
        livereload: true,
        port: LR_PORT,
        directoryListing: false
      }));
});

gulp.task('server', function() {
  return gulp.src('.')
    .pipe(webserver({
      host: '0.0.0.0',
      livereload: true,
      port: LR_PORT,
      directoryListing: true
    }));
});

/** *****************************************
 *
 * Tasks and functions for module Javascript
 *
 ** ***************************************** */

gulp.task('build-js', function() {
  return buildJs(IS_RELEASE_BUILD);
});

gulp.task('build-js-release', function() {
  return buildJs(true);
});

/**
 * Builds the entire component library javascript.
 * @param {boolean} isRelease Whether to build in release mode.
 */
global.buildJs = function buildJs(isRelease) {
  var jsFiles = config.jsBaseFiles.concat([path.join(config.paths, '*.js')]);

  gutil.log("building js files...");

  var jsBuildStream = gulp.src( jsFiles )
        .pipe(filterNonCodeFiles())
        .pipe(utils.buildNgMaterialDefinition())
        .pipe(plumber())
        .pipe(ngAnnotate())
        .pipe(utils.addJsWrapper(true));

  var jsProcess = series(jsBuildStream, themeBuildStream() )
        .pipe(concat('angular-material.js'))
        .pipe(BUILD_MODE.transform())
        .pipe(insert.prepend(config.banner))
        .pipe(gulp.dest(config.outputDir))
        .pipe(gulpif(isRelease, lazypipe()
          .pipe(uglify, { preserveComments: 'some' })
          .pipe(rename, { extname: '.min.js' })
          .pipe(gulp.dest, config.outputDir)
          ()
        ));

  return series(jsProcess, deployMaterialMocks())
};

// Deploy the `angular-material-mocks.js` file to the `dist` directory
global.deployMaterialMocks = function deployMaterialMocks() {

  return gulp.src(config.mockFiles)
    .pipe(gulp.dest(config.outputDir));

};

// builds the theming related css and provides it as a JS const for angular
global.themeBuildStream = function themeBuildStream() {
  return gulp.src( config.themeBaseFiles.concat(path.join(config.paths, '*-theme.scss')) )
    .pipe(concat('default-theme.scss'))
    .pipe(utils.hoistScssVariables())
    .pipe(sass())
    .pipe(utils.cssToNgConstant('material.core', '$MD_THEME_CSS'));
};

/** *****************************************
 *
 * Component Demos Tasks and commands
 *
 * Build and deploy demos for a module. This is
 * useful for debugging a specific module independent of
 * the docs build; which has all modules and all demos loaded.
 *
 * To build, watch for changes, and launch web server :
 *
 * ```sh
 *    gulp watch-demo -c button
 *    gulp server
 * ```
 *
 * To build demo files:
 *
 * ```sh
 *    gulp build-demo -c button
 * ```
 *
 ** ***************************************** */

gulp.task('build-demo', ['build', 'build-module-demo'], function() {
  return buildModule(readModuleArg(), false);
});

gulp.task('build-module-demo', function() {
  var mod = readModuleArg();
  var name = mod.split('.').pop();
  var demoIndexTemplate = fs.readFileSync(
    __dirname + '/docs/config/template/demo-index.template.html', 'utf8'
  ).toString();

  gutil.log('Building demos for', mod, '...');

  return utils.readModuleDemos(mod, function() {
    return lazypipe()
        .pipe(gulpif, /.css$/, sass())
        .pipe(gulpif, /.css$/, autoprefix())
        .pipe(gulp.dest, BUILD_MODE.outputDir + name)
        ();
  })
  .pipe(through2.obj(function(demo, enc, next) {
    fs.writeFileSync(
      path.resolve(BUILD_MODE.outputDir, name, demo.name, 'index.html'),
      _.template(demoIndexTemplate, demo)
    );
    next();
  }));

});

/** *****************************************
 *
 * Tasks and functions for Themes and CSS
 *
 ** ***************************************** */

/** *****************************************
 *
 * Internal helper functions
 *
 ** ***************************************** */

function readModuleArg() {
  var module = argv.c ? 'material.components.' + argv.c : (argv.module || argv.m);
  if (!module) {
    gutil.log('\nProvide a compnent argument via `-c`:',
      '\nExample: -c toast');
    gutil.log('\nOr provide a module argument via `--module` or `-m`.',
      '\nExample: --module=material.components.toast or -m material.components.dialog');
    process.exit(1);
  }
  return module;
}

global.filterNonCodeFiles = function filterNonCodeFiles() {
  return filter(function(file) {
    return !/demo|module\.json|\.spec.js|README/.test(file.path);
  });
};

global.autoprefix = function autoprefix() {
  return autoprefixer({browsers: [
    'last 2 versions', 'last 4 Android versions'
  ]});
};

//-- read in all files from gulp/tasks and create tasks for them
fs.readdirSync('./gulp/tasks')
    .filter(function (filename) {
      return filename.match(/\.js$/i);
    })
    .map(function (filename) {
      return {
        name: filename.substr(0, filename.length - 3),
        contents: require('./gulp/tasks/' + filename)
      };
    })
    .filter(function (file) {
      gulp.task(file.name, file.contents.dependencies, file.contents.task);
    });
<|endoftext|>