<commit_before>/*globals require, console*/

var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    shell = require('gulp-shell'),
    runSequence = require('run-sequence'),
    srcPattern = ['src/**/*.js', 'test/**/*.js'],
    clientSrcPattern = 'src/client/js/**/*.js';

gulp.task('lint', function () {
    'use strict';

    gulp.src(clientSrcPattern)
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('lint-all', function () {
    'use strict';

    gulp.src(srcPattern)
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'));
});

function changeNotification(event) {
    'use strict';

    console.log('File', event.path, 'was', event.type, ', running tasks...');
}

function build() {
    'use strict';

    var jsWatcher = gulp.watch(clientSrcPattern, [/*'js',*/ 'lint']);

    jsWatcher.on('change', changeNotification);
}

gulp.task('rjs-build', shell.task(['node ./node_modules/requirejs/bin/r.js -o ./utils/build/webgme.classes/cbuild.js']));

gulp.task('register-watchers', [], function (cb) {
    gulp.watch('src/**/*.js', ['rjs-build']);
    return cb;
});

gulp.task('dev', function (cb) {
    runSequence('rjs-build', 'register-watchers', cb);
});

gulp.task('compile-all', ['rjs-build'], function () { });

gulp.task('default', [/*'js',*/ 'lint'], build);
<commit_msg>Add error-handling for rj-build gulp task. This is currently not working, awaits https://github.com/joyent/node/issues/3584<commit_after>/*globals require, console*/
/*jshint node: true*/
'use strict';

var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    shell = require('gulp-shell'),
    runSequence = require('run-sequence'),
    srcPattern = ['src/**/*.js', 'test/**/*.js'],
    clientSrcPattern = 'src/client/js/**/*.js';

gulp.task('lint', function () {

    gulp.src(clientSrcPattern)
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('lint-all', function () {

    gulp.src(srcPattern)
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'));
});

function changeNotification(event) {

    console.log('File', event.path, 'was', event.type, ', running tasks...');
}

function build() {

    var jsWatcher = gulp.watch(clientSrcPattern, [/*'js',*/ 'lint']);

    jsWatcher.on('change', changeNotification);
}

gulp.task('rjs-build', function () {
    var stream = shell(['node ./node_modules/requirejs/bin/r.js -o ./utils/build/webgme.classes/cbuild.js'])
    .on('error', function (error) {
        // Currently this isn't entered.
        //
        // https://github.com/joyent/node/issues/3584
        // others have the same issue https://github.com/gruntjs/grunt/issues/792
        console.error('build failed with err', error);
        process.exit(1);
    });
    return gulp.src('', {read: false}).pipe(stream);
});

gulp.task('register-watchers', [], function (cb) {
    gulp.watch('src/**/*.js', ['rjs-build']);
    return cb;
});

gulp.task('dev', function (cb) {
    runSequence('rjs-build', 'register-watchers', cb);
});

gulp.task('compile-all', ['rjs-build'], function () { });

gulp.task('default', [/*'js',*/ 'lint'], build);
<|endoftext|>


<commit_before>// GULP DEPENDENCIES
// ----------------------------------------------------------------------------
var gulp         = require('gulp');
var sass         = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss    = require('gulp-minify-css');
var jshint       = require('gulp-jshint');
var concat       = require('gulp-concat');
var uglify       = require('gulp-uglify');
var imageMin     = require('gulp-imagemin');
var notify       = require('gulp-notify');
var rename       = require('gulp-rename');
var cache        = require('gulp-cache');
var del          = require('del');

// GULP TASKS.
// ----------------------------------------------------------------------------
gulp.task('styles', function() {
    return sass('./resources/assets/scss/*.scss', { style: 'expanded' })
        .pipe(autoprefixer('last 2 version'))
        .pipe(gulp.dest('./public/css'))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest('./public/css'))
        .pipe(notify({ message: 'Styles task complete' }));
});

gulp.task('watch', function() {
    // Watch .scss files.
    gulp.watch('./resources/assets/scss/*.scss', ['styles']);
});

<commit_msg>add default task<commit_after>// GULP DEPENDENCIES
// ----------------------------------------------------------------------------
var gulp         = require('gulp');
var sass         = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss    = require('gulp-minify-css');
var jshint       = require('gulp-jshint');
var concat       = require('gulp-concat');
var uglify       = require('gulp-uglify');
var imageMin     = require('gulp-imagemin');
var notify       = require('gulp-notify');
var rename       = require('gulp-rename');
var cache        = require('gulp-cache');
var del          = require('del');

// GULP TASKS.
// ----------------------------------------------------------------------------
gulp.task('styles', function() {
    return sass('./resources/assets/scss/*.scss', { style: 'expanded' })
        .pipe(autoprefixer('last 2 version'))
        .pipe(gulp.dest('./public/css'))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest('./public/css'))
        .pipe(notify({ message: 'Styles task complete' }));
});

// Gulp default task.
// You can simply run it with `gulp`
gulp.task('default', ['clean'], function() {
    gulp.start('styles');
});

gulp.task('watch', function() {
    // Watch .scss files.
    gulp.watch('./resources/assets/scss/*.scss', ['styles']);
});

<|endoftext|>


<commit_before>'use strict';

/* Usage:
 *
 *   gulp [watch]
 *     For development with live reload (default task).
 *
 *   gulp build
 *     Development build.
 *
 *   gulp build --production
 *     TODO: Production-ready build (asset concatenation, minification, ...).
 */

var path = require('path');
var gulp = require('gulp');
var runSequence = require('run-sequence');
var gutil = require('gulp-util');
var del = require('del');
var gulpif = require('gulp-if');
var exec = require('child_process').exec;

var notify = require('gulp-notify');
var plumber = require('gulp-plumber');

var buffer = require('vinyl-buffer');
var argv = require('yargs').argv;

// sass
var sass = require('gulp-sass');
var bulkSass = require('gulp-sass-bulk-import');
var moduleImporter = require('sass-module-importer');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var minifyCSS = require('gulp-clean-css');
var concat = require('gulp-concat');
var imagemin = require('gulp-imagemin');

// BrowserSync
var browserSync = require('browser-sync');

var deploy = require('gulp-deploy-git');

/* Read the `production` env flag. */
var production = !!argv.production;

var sourcePaths = {
  stylesheets: "./stylesheets/",
};

var buildPath = "./hawkpost/static/";

// ----------------------------
// Error notification methods
// ----------------------------
var beep = function() {
  var os = require('os');
  var file = 'gulp/error.wav';
  if (os.platform() === 'linux') {
    // linux
    exec("aplay " + file);
  } else {
    // mac
    console.log("afplay " + file);
    exec("afplay " + file);
  }
};

var handleError = function (task) {
  return function (err) {
    beep();

    notify.onError({
      message: task + ' failed, check the logs..',
      sound: false
    })(err);

    gutil.log(gutil.colors.bgRed(task + ' error:'), gutil.colors.red(err));
    this.emit('end');
  };
};

var tasks = {};

tasks.browser_sync = function () {
  var config = {
      proxy: {
          target: "http://0.0.0.0:8000",
          ws: true
      },
      ghostMode: {
        clicks: false,
        location: false,
        forms: false,
        scroll: false
      }
  }
  //run TUNNEL=true gulp to start public tunnel url to share.
  if (process.env.TUNNEL === 'true') {
    config.tunnel = "qoldwebapp";
  }

  browserSync(config);
};

tasks.clean = function (cb) {
  return del([buildPath + "style.css"], cb);
};

// --------------------------
// SASS (libsass)
// --------------------------
tasks.sass = function() {
  return gulp.src(sourcePaths.stylesheets + '*.scss')
    // sourcemaps + sass + error handling
    .pipe(gulpif(!production, sourcemaps.init()))
    .pipe(bulkSass())
    .pipe(sass({
      importer: moduleImporter(),
      sourceComments: !production,
      outputStyle: production ? 'compressed' : 'nested'
    }))
    .on('error', handleError('SASS'))
    // generate .maps
    .pipe(gulpif(!production, sourcemaps.write({
      includeContent: false,
      sourceRoot: '.'
    })))
    // autoprefixer
    .pipe(gulpif(!production, sourcemaps.init({
      loadMaps: true
    })))
   .pipe(autoprefixer({
          browsers: ['last 2 versions'],
    }))
    /* We don't serve the source files
     * so include scss content inside the sourcemaps. */
    .pipe(sourcemaps.write({
      includeContent: true
    }))
    .pipe(gulp.dest(buildPath + 'css/'))
    .pipe(browserSync.reload({stream: true}));
};

tasks.fonts = function() {
  return gulp.src(sourcePaths.assets + 'fonts/**/*.*')
    .pipe(gulp.dest(buildPath + 'assets/fonts/'));
};

tasks.images = function() {
  return gulp.src(sourcePaths.assets + 'images/**/*.*')
  .pipe(gulpif(production, imagemin({progressive: true})))
  .pipe(gulp.dest(buildPath + 'assets/images/'))
};

/* Compilation tasks */
gulp.task('clean',         tasks.clean);

gulp.task('sass',          tasks.sass);
gulp.task('views',         tasks.views);
gulp.task('fonts',         tasks.fonts);
gulp.task('images',        tasks.images);

/* Assets compilation and reload. */
gulp.task('browser-sync', tasks.browser_sync);
var browserSyncRefresh = browserSync.reload.bind(browserSync);
var browserSyncStream  = function () { browserSync.reload({ stream: true }) };

gulp.task('reload-sass',      ['sass'],          browserSyncStream);
gulp.task('reload-vendor',    ['vendor-styles'], browserSyncStream);
gulp.task('reload-fonts',     ['fonts'],         browserSyncRefresh);
gulp.task('reload-images',    ['images'],        browserSyncRefresh);

gulp.task('reload-pages', function () {
  browserSyncRefresh();
});

/* Watch task */
gulp.task('watch', function (cb) {
  return runSequence(
    'build',
    'browser-sync',
    function () {
      /* Avoiding the compilation of the vendor styles on save, faster faster faster! */
      gulp.watch([
              sourcePaths.stylesheets + '**/*.scss',             ], ['reload-sass']);
      gulp.watch(sourcePaths.assets      + 'fonts/',                               ['reload-fonts']);
      gulp.watch(sourcePaths.assets      + 'images/',                              ['reload-images']);

      gutil.log(gutil.colors.bgGreen('Watching for changes...'));
      return cb();
    }
  );
});

/* Build task */
gulp.task('build', function (cb) {
  /* Clean first, build afterwards. */
  return runSequence(
    'clean', [
      'sass',
      'fonts',
      'images'
    ], cb);
});

/* Default task (`watch`) */
gulp.task('default', ['watch']);

/*
 * GH pages deploy
 * --------------- */

gulp.task('gh-pages', function() {
  return gulp.src(buildPath + '**/*')
    .pipe(deploy({
      prefix: 'dist',
      repository: 'github_repo_url',
      remoteBranch: ['gh-pages']
    }));
});

gulp.task('deploy', function(cb) {
  return runSequence(
    'build',
    'gh-pages',
  cb);
});
<commit_msg>Cleaning up Gulpfile and removing unused deps<commit_after>'use strict';

/* Usage:
 *
 *   gulp [watch]
 *     For development with live reload (default task).
 *
 *   gulp build
 *     Development build.
 *
 *   gulp build --production
 *     TODO: Production-ready build (asset concatenation, minification, ...).
 */

/* Gulp dependencies */
var gulp = require('gulp');
var runSequence = require('run-sequence');
var gutil = require('gulp-util');
var del = require('del');
var gulpif = require('gulp-if');

var notify = require('gulp-notify');

var argv = require('yargs').argv;

/* CSS */
var sass = require('gulp-sass');
var bulkSass = require('gulp-sass-bulk-import');
var moduleImporter = require('sass-module-importer');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');

/* Images */
var imagemin = require('gulp-imagemin');

/* Livereload */
var browserSync = require('browser-sync');

function handleError(task) {
  return function (err) {
    notify.onError({
      message: task + ' failed, check the logs..',
      sound: false
    })(err);

    gutil.log(gutil.colors.bgRed(task + ' error:'), gutil.colors.red(err));
    this.emit('end');
  };
}

/* Arguments: read the `production` env flag. */
var production = !!argv.production;

var sourcePaths = {
  stylesheets: "./stylesheets/",
};

var buildPath = "./hawkpost/static/";

var tasks = {};

tasks.browser_sync = function () {
  var config = {
      proxy: {
          target: "http://0.0.0.0:8000",
          ws: true
      },
      ghostMode: {
        clicks: false,
        location: false,
        forms: false,
        scroll: false
      }
  }

  browserSync(config);
};

tasks.clean = function (cb) {
  return del([buildPath + "style.css"], cb);
};

tasks.sass = function () {
  return gulp.src(sourcePaths.stylesheets + '*.scss')
    /* Sourcemaps + SASS */
    .pipe(gulpif(!production, sourcemaps.init()))
    .pipe(bulkSass())
    .pipe(sass({
      importer: moduleImporter(),
      sourceComments: !production,
      outputStyle: production ? 'compressed' : 'nested'
    }))
    .on('error', handleError('SASS'))
    /* Generate .maps */
    .pipe(gulpif(!production, sourcemaps.write({
      includeContent: false,
      sourceRoot: '.'
    })))
    .pipe(gulpif(!production, sourcemaps.init({
      loadMaps: true
    })))
    /* Autoprefixer */
   .pipe(autoprefixer({
      browsers: ['last 2 versions'],
    }))
    /* We don't serve the source files,
     * so include SCSS content inside the sourcemaps. */
    .pipe(sourcemaps.write({
      includeContent: true
    }))
    .pipe(gulp.dest(buildPath + 'css/'))
    .pipe(browserSync.reload({ stream: true }));
};

tasks.fonts = function() {
  return gulp.src(sourcePaths.assets + 'fonts/**/*.*')
    .pipe(gulp.dest(buildPath + 'assets/fonts/'));
};

tasks.images = function() {
  return gulp.src(sourcePaths.assets + 'images/**/*.*')
  .pipe(gulpif(production, imagemin({ progressive: true })))
  .pipe(gulp.dest(buildPath + 'assets/images/'));
};

/* Compilation tasks */
gulp.task('clean',  tasks.clean);

gulp.task('sass',   tasks.sass);
gulp.task('views',  tasks.views);
gulp.task('fonts',  tasks.fonts);
gulp.task('images', tasks.images);

/* Assets compilation and reload. */
gulp.task('browser-sync', tasks.browser_sync);
var browserSyncRefresh = browserSync.reload.bind(browserSync);
var browserSyncStream  = function () { browserSync.reload({ stream: true }); };

gulp.task('reload-sass',   ['sass'],          browserSyncStream);
gulp.task('reload-vendor', ['vendor-styles'], browserSyncStream);
gulp.task('reload-fonts',  ['fonts'],         browserSyncRefresh);
gulp.task('reload-images', ['images'],        browserSyncRefresh);

gulp.task('reload-pages', function () {
  browserSyncRefresh();
});

/* Watch task */
gulp.task('watch', function (cb) {
  return runSequence(
    'build',
    'browser-sync',
    function () {
      /* Avoiding the compilation of the vendor styles on save, faster faster faster! */
      gulp.watch(sourcePaths.stylesheets + '**/*.scss', ['reload-sass']);
      gulp.watch(sourcePaths.assets      + 'fonts/',    ['reload-fonts']);
      gulp.watch(sourcePaths.assets      + 'images/',   ['reload-images']);

      gutil.log(gutil.colors.bgGreen('Watching for changes...'));
      return cb();
    }
  );
});

/* Build task */
gulp.task('build', function (cb) {
  /* Clean first, build afterwards. */
  return runSequence(
    'clean', [
      'sass',
      'fonts',
      'images'
    ], cb);
});

/* Default task (`watch`) */
gulp.task('default', ['watch']);
<|endoftext|>


<commit_before>const gulp = require('gulp');
const { series, parallel } = gulp;
const glob = require('glob');
const shell = cmd => require('child_process').execSync(cmd, { stdio: [0, 1, 2] });
const del = require('del');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const $ = require('gulp-load-plugins')();
const browserify = require('browserify');
const tsify = require('tsify');
const minify = require('gulp-uglify/composer')(require('uglify-es'), console);
const Server = require('karma').Server;

const pkg = require('./package.json');
const config = {
  browsers: ['Chrome', 'Firefox'].concat((os => {
    switch (os) {
      case 'Windows_NT':
        return ['Edge'];
      case 'Darwin':
        return [];
     default:
        return [];
    }
  })(require('os').type())),
  ts: {
    dist: {
      src: [
        '*.ts'
      ],
      dest: 'dist'
    },
    test: {
      src: [
        '*.ts',
        'src/**/*.ts',
        'test/**/*.ts'
      ],
      dest: 'dist'
    }
  },
  site: {
    js: './gh-pages/assets/js/lib',
  },
  banner: [
    `/*! ${pkg.name} v${pkg.version} ${pkg.repository.url} | (c) 2016, ${pkg.author} | ${pkg.license} License */`,
    ''
  ].join('\n'),
  module: `
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
      define([], factory);
  } else if (typeof module === 'object' && module.exports) {
      module.exports = factory();
  } else {
      //root.returnExports = factory();
  }
}(typeof self !== 'undefined' ? self : this, function () {
  return require('${pkg.name}');
}));
`,
  clean: [
    'dist',
    'gh-pages/assets/*/**/lib',
  ]
};

function compile(src, watch = false) {
  let done = true;
  const b = browserify(Object.values(src).map(p => glob.sync(p)), {
    cache: {},
    packageCache: {},
  })
    .require(`./index.ts`, { expose: pkg.name })
    .plugin(tsify, { global: true, ...require('./tsconfig.json').compilerOptions });
  return bundle();

  function bundle() {
    console.time('bundle');
    return b
      .bundle()
      .on("error", err => done = console.log(err + '') || watch)
      .pipe(source(`${pkg.name}.js`))
      .pipe(buffer())
      .pipe($.derequire())
      .once('finish', () => console.timeEnd('bundle'))
      .once("finish", () => done || process.exit(1))
      .pipe($.footer(config.module));
  }
}

gulp.task('ts:dev', () =>
  gulp.watch(config.ts.test.src, { ignoreInitial: false }, () =>
    compile(config.ts.test.src, true)
      .pipe($.rename({ extname: '.test.js' }))
      .pipe(gulp.dest(config.ts.test.dest))));

gulp.task('ts:test', () =>
  compile(config.ts.test.src)
    .pipe($.rename({ extname: '.test.js' }))
    .pipe(gulp.dest(config.ts.test.dest)));

gulp.task('ts:dist', () =>
  compile(config.ts.dist.src)
    .pipe($.unassert())
    .pipe($.header(config.banner))
    .pipe(gulp.dest(config.ts.dist.dest))
    .pipe(gulp.dest(config.site.js))
    .pipe($.rename({ extname: '.min.js' }))
    .pipe(minify({ output: { comments: /^!/ } }))
    .pipe(gulp.dest(config.ts.dist.dest)));

gulp.task('ts:view', () =>
  gulp.watch(config.ts.dist.src, { ignoreInitial: false }, () =>
    compile(config.ts.dist.src, true)
      .pipe($.unassert())
      .pipe($.header(config.banner))
      .pipe(gulp.dest(config.site.js))));

gulp.task('karma:dev', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['espower']
    },
    singleRun: false
  }, done).start());

gulp.task('karma:test', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage'],
    concurrency: 1,
    singleRun: true
  }, done).start());

gulp.task('karma:ci', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage', 'coveralls'],
    concurrency: 1,
    singleRun: true
  }, done).start());

gulp.task('clean', () =>
  del(config.clean));

gulp.task('install', done => {
  shell('npm i --no-shrinkwrap');
  done();
});

gulp.task('update', done => {
  shell('bundle update');
  shell('ncu -ux del');
  shell('ncu -ut typescript');
  shell('npm i --no-shrinkwrap');
  done();
});

gulp.task('dev',
  series(
    'clean',
    parallel(
      'ts:dev',
      'karma:dev',
    )));

gulp.task('test',
  series(
    'clean',
    series(
      'ts:test',
      'karma:test',
      'ts:dist',
    )));

gulp.task('dist',
  series(
    'clean',
    series(
      'ts:dist',
    )));

gulp.task('view',
  series(
    'clean',
    () =>
      shell([
        'concurrently',
        '"gulp dev"',
        '"gulp ts:view"',
        '"bundle exec jekyll serve -s ./gh-pages -d ./gh-pages/_site --incremental"'
      ].join(' ')),
  ));

gulp.task('ci',
  series(
    'clean',
    series(
      'ts:test',
      'karma:ci',
      'karma:ci',
      'karma:ci',
      'dist',
    )));
<commit_msg>refactor: refactoring<commit_after>const gulp = require('gulp');
const { series, parallel } = gulp;
const glob = require('glob');
const shell = cmd => require('child_process').execSync(cmd, { stdio: [0, 1, 2] });
const del = require('del');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const $ = require('gulp-load-plugins')();
const browserify = require('browserify');
const tsify = require('tsify');
const minify = require('gulp-uglify/composer')(require('uglify-es'), console);
const Server = require('karma').Server;

const pkg = require('./package.json');
const config = {
  browsers: ['Chrome', 'Firefox'].concat((os => {
    switch (os) {
      case 'Windows_NT':
        return ['Edge'];
      case 'Darwin':
        return [];
     default:
        return [];
    }
  })(require('os').type())),
  ts: {
    dist: {
      src: [
        '*.ts'
      ],
      dest: 'dist'
    },
    test: {
      src: [
        '*.ts',
        'src/**/*.ts',
        'test/**/*.ts'
      ],
      dest: 'dist'
    }
  },
  site: {
    js: './gh-pages/assets/js/lib',
  },
  banner: [
    `/*! ${pkg.name} v${pkg.version} ${pkg.repository.url} | (c) 2016, ${pkg.author} | ${pkg.license} License */`,
    ''
  ].join('\n'),
  module: `
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
      define([], factory);
  } else if (typeof module === 'object' && module.exports) {
      module.exports = factory();
  } else {
      //root.returnExports = factory();
  }
}(typeof self !== 'undefined' ? self : this, function () {
  return require('${pkg.name}');
}));
`,
  clean: [
    'dist',
    'gh-pages/assets/*/**/lib',
  ]
};

function compile(src, watch = false) {
  let done = true;
  const b = browserify(Object.values(src).map(p => glob.sync(p)), {
    cache: {},
    packageCache: {},
  })
    .require(`./index.ts`, { expose: pkg.name })
    .plugin(tsify, { global: true, ...require('./tsconfig.json').compilerOptions });
  return bundle();

  function bundle() {
    console.time('bundle');
    return b
      .bundle()
      .on("error", err => done = console.log(err + '') || watch)
      .pipe(source(`${pkg.name}.js`))
      .pipe(buffer())
      .pipe($.derequire())
      .once('finish', () => console.timeEnd('bundle'))
      .once("finish", () => done || process.exit(1))
      .pipe($.footer(config.module));
  }
}

gulp.task('ts:dev', () =>
  gulp.watch(config.ts.test.src, { ignoreInitial: false }, () =>
    compile(config.ts.test.src, true)
      .pipe($.rename({ extname: '.test.js' }))
      .pipe(gulp.dest(config.ts.test.dest))));

gulp.task('ts:test', () =>
  compile(config.ts.test.src)
    .pipe($.rename({ extname: '.test.js' }))
    .pipe(gulp.dest(config.ts.test.dest)));

gulp.task('ts:dist', () =>
  compile(config.ts.dist.src)
    .pipe($.unassert())
    .pipe($.header(config.banner))
    .pipe(gulp.dest(config.ts.dist.dest))
    .pipe(gulp.dest(config.site.js))
    .pipe($.rename({ extname: '.min.js' }))
    .pipe(minify({ output: { comments: /^!/ } }))
    .pipe(gulp.dest(config.ts.dist.dest)));

gulp.task('ts:view', () =>
  gulp.watch(config.ts.dist.src, { ignoreInitial: false }, () =>
    compile(config.ts.dist.src, true)
      .pipe($.unassert())
      .pipe($.header(config.banner))
      .pipe(gulp.dest(config.site.js))));

gulp.task('karma:dev', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['espower']
    },
    singleRun: false
  }, done).start());

gulp.task('karma:test', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage'],
    concurrency: 1,
    singleRun: true
  }, done).start());

gulp.task('karma:ci', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage', 'coveralls'],
    concurrency: 1,
    singleRun: true
  }, done).start());

gulp.task('clean', () =>
  del(config.clean));

gulp.task('install', done => {
  shell('npm i --no-shrinkwrap');
  done();
});

gulp.task('update', done => {
  shell('bundle update');
  shell('ncu -ux del,karma-coverage');
  shell('ncu -ut typescript');
  shell('npm i --no-shrinkwrap');
  done();
});

gulp.task('dev',
  series(
    'clean',
    parallel(
      'ts:dev',
      'karma:dev',
    )));

gulp.task('test',
  series(
    'clean',
    series(
      'ts:test',
      'karma:test',
      'ts:dist',
    )));

gulp.task('dist',
  series(
    'clean',
    series(
      'ts:dist',
    )));

gulp.task('view',
  series(
    'clean',
    () =>
      shell([
        'concurrently',
        '"gulp dev"',
        '"gulp ts:view"',
        '"bundle exec jekyll serve -s ./gh-pages -d ./gh-pages/_site --incremental"'
      ].join(' ')),
  ));

gulp.task('ci',
  series(
    'clean',
    series(
      'ts:test',
      'karma:ci',
      'karma:ci',
      'karma:ci',
      'dist',
    )));
<|endoftext|>


<commit_before>const gulp = require('gulp');
const glob = require('glob');
const shell = cmd => require('child_process').execSync(cmd, { stdio: [0, 1, 2] });
const del = require('del');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const $ = require('gulp-load-plugins')();
const seq = require('run-sequence');
const browserify = require('browserify');
const watchify = require('watchify');
const tsify = require('tsify');
const minify = require('gulp-uglify/composer')(require('uglify-es'), console);
const Server = require('karma').Server;

const pkg = require('./package.json');
const config = {
  browsers: ['Chrome', 'Firefox'].concat((os => {
    switch (os) {
      case 'Windows_NT':
        return ['Edge'];
      case 'Darwin':
        return [];
     default:
        return [];
    }
  })(require('os').type())),
  ts: {
    dist: {
      src: [
        '*.ts'
      ],
      dest: 'dist'
    },
    test: {
      src: [
        '*.ts',
        'src/**/*.ts',
        'test/**/*.ts'
      ],
      dest: 'dist'
    }
  },
  banner: [
    `/*! ${pkg.name} v${pkg.version} ${pkg.repository.url} | (c) 2016, ${pkg.author} | ${pkg.license} License */`,
    ''
  ].join('\n'),
};

function compile({ src, dest }, opts = {}) {
  let done = true;
  const force = !!opts.plugin && opts.plugin.includes(watchify);
  const b = browserify(Object.values(src).map(p => glob.sync(p)), {
    cache: {},
    packageCache: {},
    ...opts,
  })
    .require(`./index.ts`, { expose: pkg.name })
    .plugin(tsify, { global: true, ...require('./tsconfig.json').compilerOptions })
    .on('update', () => void bundle());
  return bundle();

  function bundle() {
    console.time('bundle');
    return b
      .bundle()
      .on("error", err => done = console.log(err + ''))
      .pipe(source(`${pkg.name}.js`))
      .pipe(buffer())
      .once('finish', () => console.timeEnd('bundle'))
      .once("finish", () => done || force || process.exit(1))
      .pipe(gulp.dest(dest));
  }
}

gulp.task('ts:watch', function () {
  return compile(config.ts.test, {
    plugin: [watchify],
  });
});

gulp.task('ts:test', function () {
  return compile(config.ts.test);
});

gulp.task('ts:dist', function () {
  return compile(config.ts.dist)
    .pipe($.unassert())
    .pipe($.header(config.banner))
    .pipe(gulp.dest(config.ts.dist.dest))
    .pipe($.rename({ extname: '.min.js' }))
    .pipe(minify({ output: { comments: /^!/ } }))
    .pipe(gulp.dest(config.ts.dist.dest));
});

gulp.task('karma:watch', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['espower']
    },
  }, done).start();
});

gulp.task('karma:test', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage'],
    singleRun: true
  }, done).start();
});

gulp.task('karma:ci', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage', 'coveralls'],
    singleRun: true
  }, done).start();
});

gulp.task('clean', function () {
  return del([config.ts.dist.dest, './gh-pages/assets/**/lib']);
});

gulp.task('install', function () {
  shell('npm i --no-shrinkwrap');
});

gulp.task('update', function () {
  shell('bundle update');
  shell('ncu -ua');
  shell('npm i -DE typescript@next --no-shrinkwrap');
  shell('npm i --no-shrinkwrap');
});

gulp.task('watch', ['clean'], function (done) {
  seq(
    'ts:test',
    [
      'ts:watch',
      'karma:watch'
    ],
    done
  );
});

gulp.task('test', ['clean'], function (done) {
  seq(
    'ts:test',
    'karma:test',
    'ts:dist',
    done
  );
});

gulp.task('site', ['dist'], function () {
  return gulp.src([
    `dist/${pkg.name}.js`,
  ])
    .pipe(gulp.dest('./gh-pages/assets/js/lib'));
});

gulp.task('view', ['site'], function () {
  shell('bundle exec jekyll serve -s ./gh-pages -d ./gh-pages/_site --incremental');
});

gulp.task('dist', ['clean'], function (done) {
  seq(
    'ts:dist',
    done
  );
});

gulp.task('ci', ['clean'], function (done) {
  seq(
    'ts:test',
    'karma:ci',
    'karma:ci',
    'karma:ci',
    'dist',
    'site',
    done
  );
});
<commit_msg>chore: update module exports<commit_after>const gulp = require('gulp');
const glob = require('glob');
const shell = cmd => require('child_process').execSync(cmd, { stdio: [0, 1, 2] });
const del = require('del');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const $ = require('gulp-load-plugins')();
const seq = require('run-sequence');
const browserify = require('browserify');
const watchify = require('watchify');
const tsify = require('tsify');
const minify = require('gulp-uglify/composer')(require('uglify-es'), console);
const Server = require('karma').Server;

const pkg = require('./package.json');
const config = {
  browsers: ['Chrome', 'Firefox'].concat((os => {
    switch (os) {
      case 'Windows_NT':
        return ['Edge'];
      case 'Darwin':
        return [];
     default:
        return [];
    }
  })(require('os').type())),
  ts: {
    dist: {
      src: [
        '*.ts'
      ],
      dest: 'dist'
    },
    test: {
      src: [
        '*.ts',
        'src/**/*.ts',
        'test/**/*.ts'
      ],
      dest: 'dist'
    }
  },
  banner: [
    `/*! ${pkg.name} v${pkg.version} ${pkg.repository.url} | (c) 2016, ${pkg.author} | ${pkg.license} License */`,
    ''
  ].join('\n'),
  module: `
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
      define([], factory);
  } else if (typeof module === 'object' && module.exports) {
      module.exports = factory();
  } else {
      root.returnExports = factory();
}
}(typeof self !== 'undefined' ? self : this, function () {
  return require('atomic-promise');
}));
`,
};

function compile({ src, dest }, opts = {}) {
  let done = true;
  const force = !!opts.plugin && opts.plugin.includes(watchify);
  const b = browserify(Object.values(src).map(p => glob.sync(p)), {
    cache: {},
    packageCache: {},
    ...opts,
  })
    .require(`./index.ts`, { expose: pkg.name })
    .plugin(tsify, { global: true, ...require('./tsconfig.json').compilerOptions })
    .on('update', () => void bundle());
  return bundle();

  function bundle() {
    console.time('bundle');
    return b
      .bundle()
      .on("error", err => done = console.log(err + ''))
      .pipe(source(`${pkg.name}.js`))
      .pipe(buffer())
      .once('finish', () => console.timeEnd('bundle'))
      .once("finish", () => done || force || process.exit(1))
      .pipe(gulp.dest(dest));
  }
}

gulp.task('ts:watch', function () {
  return compile(config.ts.test, {
    plugin: [watchify],
  });
});

gulp.task('ts:test', function () {
  return compile(config.ts.test);
});

gulp.task('ts:dist', function () {
  return compile(config.ts.dist)
    .pipe($.unassert())
    .pipe($.header(config.banner))
    .pipe($.footer(config.module))
    .pipe(gulp.dest(config.ts.dist.dest))
    .pipe($.rename({ extname: '.min.js' }))
    .pipe(minify({ output: { comments: /^!/ } }))
    .pipe(gulp.dest(config.ts.dist.dest));
});

gulp.task('karma:watch', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['espower']
    },
  }, done).start();
});

gulp.task('karma:test', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage'],
    singleRun: true
  }, done).start();
});

gulp.task('karma:ci', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage', 'coveralls'],
    singleRun: true
  }, done).start();
});

gulp.task('clean', function () {
  return del([config.ts.dist.dest, './gh-pages/assets/**/lib']);
});

gulp.task('install', function () {
  shell('npm i --no-shrinkwrap');
});

gulp.task('update', function () {
  shell('bundle update');
  shell('ncu -ua');
  shell('npm i -DE typescript@next --no-shrinkwrap');
  shell('npm i --no-shrinkwrap');
});

gulp.task('watch', ['clean'], function (done) {
  seq(
    'ts:test',
    [
      'ts:watch',
      'karma:watch'
    ],
    done
  );
});

gulp.task('test', ['clean'], function (done) {
  seq(
    'ts:test',
    'karma:test',
    'ts:dist',
    done
  );
});

gulp.task('site', ['dist'], function () {
  return gulp.src([
    `dist/${pkg.name}.js`,
  ])
    .pipe(gulp.dest('./gh-pages/assets/js/lib'));
});

gulp.task('view', ['site'], function () {
  shell('bundle exec jekyll serve -s ./gh-pages -d ./gh-pages/_site --incremental');
});

gulp.task('dist', ['clean'], function (done) {
  seq(
    'ts:dist',
    done
  );
});

gulp.task('ci', ['clean'], function (done) {
  seq(
    'ts:test',
    'karma:ci',
    'karma:ci',
    'karma:ci',
    'dist',
    'site',
    done
  );
});
<|endoftext|>


<commit_before>var concat = require('gulp-concat'),
    del = require('del'),
    eslint = require('gulp-eslint'),
    express = require('express'),
    extend = require('jquery-extend'),
    frontMatter = require('gulp-front-matter'),
    fs = require('fs'),
    gulp = require('gulp'),
    gulpif = require('gulp-if'),
    gzip = require('gulp-gzip'),
    hb = require('handlebars'),
    highlight = require('highlight.js'),
    layouts = require('handlebars-layouts'),
    less = require('gulp-less'),
    marked = require('gulp-marked'),
    minifyCSS = require('gulp-minify-css'),
    minifyHTML = require('gulp-minify-html'),
    minifyJS = require('gulp-uglify'),
    mocha = require('gulp-mocha'),
    moment = require('moment'),
    rename = require('gulp-rename'),
    tap = require('gulp-tap');

// Config HB
layouts.register(hb);

// Shared data object for passing between tasks
var data;

/* *
 * Build Step 0
 */

// Clean data and build dirs
gulp.task('clean', function(done) {
    data = {
        authors   : [], // Populated by 'authors' task
        posts     : [], // Populated by 'posts' task
        tags      : [], // Populated by 'posts' task
        pageTitle : 'Airware Makers',
        year      : moment().format('YYYY'),
        timestamp : moment().format('YYYY-MM-DD-HH-mm-ss')
    };

    del(['build/**', '!build'])
        .then(done());
});

/* *
 * Build Step 1
 */

// Copy static files to build dir
gulp.task('static', ['clean'], function() {
    return gulp.src('src/static/**')
        .pipe(gulpif(/robots\.txt/, tap(function(file) {
            // Clear robots.txt if we're building production
            if ( process.env.TRAVIS_BRANCH == 'master' ) file.contents = new Buffer('');
        })))
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

// Minify and combine all CSS
gulp.task('styles', ['clean'], function() {
    return gulp.src([
        'node_modules/bootstrap/dist/css/bootstrap.css',
        'node_modules/highlight.js/styles/default.css',
        'src/less/*.less'
    ])
    .pipe(gulpif(/[.]less$/, less()))
    .pipe(concat('all.min.css'))
    .pipe(minifyCSS())
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('build'));
});

// Minify and combine all JavaScript
gulp.task('scripts', ['clean'], function() {
    return gulp.src([
        'node_modules/jquery/dist/jquery.js',
        'node_modules/bootstrap/dist/js/bootstrap.js',
        'src/js/*.js'
    ])
    .pipe(concat('all.min.js'))
    .pipe(minifyJS({ preserveComments: 'some' }))
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('build'));
});

// Register HB partials
gulp.task('partials', ['clean'], function() {
    return gulp.src('src/partials/*.html')
        .pipe(rename({ extname: '' }))
        .pipe(tap(function(file) {
            var name = file.relative;
            var str = file.contents.toString();
            hb.registerPartial(name, str);
        }));
});

// Load authors
gulp.task('authors', ['clean'], function() {
    return gulp.src('src/authors/*.md')
        .pipe(frontMatter())
        .pipe(marked())
        .pipe(rename({ extname : '' }))
        .pipe(tap(function(file) {
            var author = {
                slug    : file.relative,
                bio     : file.contents.toString(),
                name    : file.frontMatter.name,
                title   : file.frontMatter.title,
                org     : file.frontMatter.org,
                email   : file.frontMatter.email,
                // Optional
                site    : file.frontMatter.site || null,
                twitter : file.frontMatter.twitter || null
            };
            data.authors.push(author);
        }));
});

/* *
 * Build Step 2
 */

// Generate posts
gulp.task('posts', ['static', 'styles', 'scripts', 'partials', 'authors'], function() {
    var template = hb.compile(fs.readFileSync('src/partials/post.html', 'utf-8'));
    data.posts = [];

    return gulp.src('src/posts/*.md')
        .pipe(frontMatter())
        .pipe(marked({
            highlight: function(code) {
                return highlight.highlightAuto(code).value;
            }
        }))
        .pipe(tap(function(file) {
            // Map everything into a single object
            var post = {
                slug        : file.relative.replace('.html', ''),
                title       : file.frontMatter.title,
                date        : file.frontMatter.date,
                link        : '/' + file.frontMatter.category + '/' + file.relative.replace('.html', '') + '/',
                displayDate : moment(file.frontMatter.date).format('MMMM DD, YYYY'),
                category    : file.frontMatter.category,
                tags        : file.frontMatter.tags.map(function(tag) {
                    return {
                        name : tag,
                        slug : tag.replace(' ', '-').toLowerCase()
                                .replace(/[^a-zA-Z0-9-_]/g, '')
                    };
                }),
                snippet     : file.contents.toString().match(/<p>(.*)<\/p>/)[1], // First paragraph contents
                post        : file.contents.toString(),
                author      : data.authors.find(function(author) {
                    return author.slug == file.frontMatter.author;
                }),
                pageTitle   : data.pageTitle,
                year        : data.year,
                timestamp   : data.timestamp
            };

            // Populate the posts object
            data.posts.push(post);

            // Change file and put back into stream
            file.path = file.path
                .replace(file.relative, file.frontMatter.category + '/' + file.relative) // Inject category
                .replace('.html', '/index.html'); // Convert to an index file
            file.contents = new Buffer(template(post), 'utf-8');
        }))
        .pipe(minifyHTML())
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'))
        .on('end', function() {
            data.posts.sort(function(a, b) {
                return moment(a.date).format('X') < moment(b.date).format('X');
            });
        });
});

/* *
 * Build Step 3
 */

// Generate posts
gulp.task('pages', ['posts'], function() {
    return gulp.src('src/pages/**/*.html')
        .pipe(frontMatter())
        .pipe(tap(function(file) {
            // Filter posts by category
            var posts = data.posts.filter(function(post) { // Reverse chron
                return [].concat(file.frontMatter.categories).indexOf(post.category) > -1 || null;
            });

            // Map data
            var page = {
                title     : file.frontMatter.title,
                tagline   : file.frontMatter.tagline || null,
                class     : file.frontMatter.class,
                year      : data.year,
                timestamp : data.timestamp,
                pageTitle : data.pageTitle,
                posts     : posts
            };

            // Homepage gets a featured post
            if (file.frontMatter.featured) page.featured = page.posts.shift();

            // Rewrite file for stream
            var template = hb.compile(file.contents.toString());
            file.contents = new Buffer(template(page));
        }))
        .pipe(gulpif(/^((?!index|error).)*$/, rename(function(path) {
            path.dirname = [ path.dirname, path.basename ].join('/');
            path.basename = 'index';
            path.extname = '.html';
        })))
        .pipe(minifyHTML())
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

/* *
 * Build Step 4
 */

// Run tests and product coverage
gulp.task('test', ['pages'], function () {
    return gulp.src('test/*.js')
        .pipe(mocha());
});

// Lint as JS files (including this one)
gulp.task('lint', ['pages'], function () {
    return gulp.src([
        'src/js/*.js',
        'gulpfile.js',
        'test/*.js',
        '!node_modules/**'
    ])
    .pipe(eslint())
    .pipe(eslint.format());
});

/* *
 * Helper Tasks
 */

// Serve files for local development
gulp.task('serve', function(done) {
    express()
        // Set compression header for all requests
        .use(function(req, res, next) {
            res.header('Content-Encoding', 'gzip');
            next();
        })
        // Static middleware
        .use(express.static('build'))
        // Serve error page
        .use(function(req, res) {
            res.status(404)
                .sendFile(__dirname + '/build/error.html');
        })
        .listen(3000, done);
});

// Watch certain files
gulp.task('watch', ['build'], function() {
    return gulp.watch([
        'src/**/*',
        'test/*'
    ], ['build']);
});

// Build Macro
gulp.task('build', [
    // 'clean'
    // 'static', 'styles', 'scripts', 'partials', 'authors'
    // 'posts'
    // 'pages'
    'test', 'lint'
]);

// What to do when you run `$ gulp`
gulp.task('default', ['watch', 'serve']);<commit_msg>No need to reset posts collection since clean task does it<commit_after>var concat = require('gulp-concat'),
    del = require('del'),
    eslint = require('gulp-eslint'),
    express = require('express'),
    extend = require('jquery-extend'),
    frontMatter = require('gulp-front-matter'),
    fs = require('fs'),
    gulp = require('gulp'),
    gulpif = require('gulp-if'),
    gzip = require('gulp-gzip'),
    hb = require('handlebars'),
    highlight = require('highlight.js'),
    layouts = require('handlebars-layouts'),
    less = require('gulp-less'),
    marked = require('gulp-marked'),
    minifyCSS = require('gulp-minify-css'),
    minifyHTML = require('gulp-minify-html'),
    minifyJS = require('gulp-uglify'),
    mocha = require('gulp-mocha'),
    moment = require('moment'),
    rename = require('gulp-rename'),
    tap = require('gulp-tap');

// Config HB
layouts.register(hb);

// Shared data object for passing between tasks
var data;

/* *
 * Build Step 0
 */

// Clean data and build dirs
gulp.task('clean', function(done) {
    data = {
        authors   : [], // Populated by 'authors' task
        posts     : [], // Populated by 'posts' task
        tags      : [], // Populated by 'posts' task
        pageTitle : 'Airware Makers',
        year      : moment().format('YYYY'),
        timestamp : moment().format('YYYY-MM-DD-HH-mm-ss')
    };

    del(['build/**', '!build'])
        .then(done());
});

/* *
 * Build Step 1
 */

// Copy static files to build dir
gulp.task('static', ['clean'], function() {
    return gulp.src('src/static/**')
        .pipe(gulpif(/robots\.txt/, tap(function(file) {
            // Clear robots.txt if we're building production
            if ( process.env.TRAVIS_BRANCH == 'master' ) file.contents = new Buffer('');
        })))
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

// Minify and combine all CSS
gulp.task('styles', ['clean'], function() {
    return gulp.src([
        'node_modules/bootstrap/dist/css/bootstrap.css',
        'node_modules/highlight.js/styles/default.css',
        'src/less/*.less'
    ])
    .pipe(gulpif(/[.]less$/, less()))
    .pipe(concat('all.min.css'))
    .pipe(minifyCSS())
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('build'));
});

// Minify and combine all JavaScript
gulp.task('scripts', ['clean'], function() {
    return gulp.src([
        'node_modules/jquery/dist/jquery.js',
        'node_modules/bootstrap/dist/js/bootstrap.js',
        'src/js/*.js'
    ])
    .pipe(concat('all.min.js'))
    .pipe(minifyJS({ preserveComments: 'some' }))
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('build'));
});

// Register HB partials
gulp.task('partials', ['clean'], function() {
    return gulp.src('src/partials/*.html')
        .pipe(rename({ extname: '' }))
        .pipe(tap(function(file) {
            var name = file.relative;
            var str = file.contents.toString();
            hb.registerPartial(name, str);
        }));
});

// Load authors
gulp.task('authors', ['clean'], function() {
    return gulp.src('src/authors/*.md')
        .pipe(frontMatter())
        .pipe(marked())
        .pipe(rename({ extname : '' }))
        .pipe(tap(function(file) {
            var author = {
                slug    : file.relative,
                bio     : file.contents.toString(),
                name    : file.frontMatter.name,
                title   : file.frontMatter.title,
                org     : file.frontMatter.org,
                email   : file.frontMatter.email,
                // Optional
                site    : file.frontMatter.site || null,
                twitter : file.frontMatter.twitter || null
            };
            data.authors.push(author);
        }));
});

/* *
 * Build Step 2
 */

// Generate posts
gulp.task('posts', ['static', 'styles', 'scripts', 'partials', 'authors'], function() {
    var template = hb.compile(fs.readFileSync('src/partials/post.html', 'utf-8'));

    return gulp.src('src/posts/*.md')
        .pipe(frontMatter())
        .pipe(marked({
            highlight: function(code) {
                return highlight.highlightAuto(code).value;
            }
        }))
        .pipe(tap(function(file) {
            // Map everything into a single object
            var post = {
                slug        : file.relative.replace('.html', ''),
                title       : file.frontMatter.title,
                date        : file.frontMatter.date,
                link        : '/' + file.frontMatter.category + '/' + file.relative.replace('.html', '') + '/',
                displayDate : moment(file.frontMatter.date).format('MMMM DD, YYYY'),
                category    : file.frontMatter.category,
                tags        : file.frontMatter.tags.map(function(tag) {
                    return {
                        name : tag,
                        slug : tag.replace(' ', '-').toLowerCase()
                                .replace(/[^a-zA-Z0-9-_]/g, '')
                    };
                }),
                snippet     : file.contents.toString().match(/<p>(.*)<\/p>/)[1], // First paragraph contents
                post        : file.contents.toString(),
                author      : data.authors.find(function(author) {
                    return author.slug == file.frontMatter.author;
                }),
                pageTitle   : data.pageTitle,
                year        : data.year,
                timestamp   : data.timestamp
            };

            // Populate the posts object
            data.posts.push(post);

            // Change file and put back into stream
            file.path = file.path
                .replace(file.relative, file.frontMatter.category + '/' + file.relative) // Inject category
                .replace('.html', '/index.html'); // Convert to an index file
            file.contents = new Buffer(template(post), 'utf-8');
        }))
        .pipe(minifyHTML())
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'))
        .on('end', function() {
            data.posts.sort(function(a, b) {
                return moment(a.date).format('X') < moment(b.date).format('X');
            });
        });
});

/* *
 * Build Step 3
 */

// Generate posts
gulp.task('pages', ['posts'], function() {
    return gulp.src('src/pages/**/*.html')
        .pipe(frontMatter())
        .pipe(tap(function(file) {
            // Filter posts by category
            var posts = data.posts.filter(function(post) { // Reverse chron
                return [].concat(file.frontMatter.categories).indexOf(post.category) > -1 || null;
            });

            // Map data
            var page = {
                title     : file.frontMatter.title,
                tagline   : file.frontMatter.tagline || null,
                class     : file.frontMatter.class,
                year      : data.year,
                timestamp : data.timestamp,
                pageTitle : data.pageTitle,
                posts     : posts
            };

            // Homepage gets a featured post
            if (file.frontMatter.featured) page.featured = page.posts.shift();

            // Rewrite file for stream
            var template = hb.compile(file.contents.toString());
            file.contents = new Buffer(template(page));
        }))
        .pipe(gulpif(/^((?!index|error).)*$/, rename(function(path) {
            path.dirname = [ path.dirname, path.basename ].join('/');
            path.basename = 'index';
            path.extname = '.html';
        })))
        .pipe(minifyHTML())
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

/* *
 * Build Step 4
 */

// Run tests and product coverage
gulp.task('test', ['pages'], function () {
    return gulp.src('test/*.js')
        .pipe(mocha());
});

// Lint as JS files (including this one)
gulp.task('lint', ['pages'], function () {
    return gulp.src([
        'src/js/*.js',
        'gulpfile.js',
        'test/*.js',
        '!node_modules/**'
    ])
    .pipe(eslint())
    .pipe(eslint.format());
});

/* *
 * Helper Tasks
 */

// Serve files for local development
gulp.task('serve', function(done) {
    express()
        // Set compression header for all requests
        .use(function(req, res, next) {
            res.header('Content-Encoding', 'gzip');
            next();
        })
        // Static middleware
        .use(express.static('build'))
        // Serve error page
        .use(function(req, res) {
            res.status(404)
                .sendFile(__dirname + '/build/error.html');
        })
        .listen(3000, done);
});

// Watch certain files
gulp.task('watch', ['build'], function() {
    return gulp.watch([
        'src/**/*',
        'test/*'
    ], ['build']);
});

// Build Macro
gulp.task('build', [
    // 'clean'
    // 'static', 'styles', 'scripts', 'partials', 'authors'
    // 'posts'
    // 'pages'
    'test', 'lint'
]);

// What to do when you run `$ gulp`
gulp.task('default', ['watch', 'serve']);<|endoftext|>


<commit_before>var fs           = require('fs')

var autoprefixer = require('gulp-autoprefixer')
var bump         = require('gulp-bump')
var babelify     = require('babelify')
var browserify   = require('browserify')
var buffer       = require('vinyl-buffer')
var clean        = require('gulp-clean')
var concat       = require('gulp-concat')
var cssnano      = require('gulp-cssnano')
var fileinclude  = require('gulp-file-include')
var git          = require('gulp-git')
var gulp         = require('gulp')
var less         = require('gulp-less')
var notify       = require('gulp-notify')
var plumber      = require('gulp-plumber' )
var rename       = require('gulp-rename')
var shell        = require('gulp-shell')
var source       = require('vinyl-source-stream')
var uglify       = require('gulp-uglify')
var zip          = require('gulp-zip')

var app          = './app/'
var dist         = './dist/'
var dist_CX      = './chrome-extension/'

function onError( error ){
  notify.onError( {
    title:    'Gulp',
    subtitle: 'Error',
    message:  '<%= error.message %>',
    sound:    'Beep'
  } )( error )
  this.emit('end')
}

//html Pages
var htmlFiles = app + 'layouts/*.html'
var tplFiles  = app + 'includes/*.tpl'

gulp.task('html', function () {
 gulp.src(htmlFiles)
     .pipe( plumber     ({ errorHandler: onError                }))
     .pipe( fileinclude ({ prefix: '@@', basepath: '@file'      }))
     .pipe( gulp.dest   (  dist                                  ))
     .pipe( gulp.dest   (  dist_CX                               ))
     .pipe( notify      ({ message:'HTML Complete', onLast:true }))
})

// styles: Compile and Minify Less / CSS Files
var less_watchFolder   = app     + 'styles/**/*.less'
var less_srcFile       = app     + 'styles/etherwallet-master.less'
var less_destFolder    = dist    + 'css'
var less_destFolder_CX = dist_CX + 'css'
var less_destFile      =           'etherwallet-master.css'
var less_destFileMin   =           'etherwallet-master.min.css'

gulp.task( 'styles', function () {
 gulp.src( less_srcFile )
     .pipe( plumber     ({ errorHandler: onError                                   }))
     .pipe( less        ({ compress: false                                         }))
     .pipe( autoprefixer({ browsers: ['last 2 versions', 'iOS > 8'], remove: false }))
     .pipe( rename      (  less_destFile                                           ))
   //.pipe( gulp.dest   (  less_destFolder                                         )) // unminified css
   //.pipe( gulp.dest   (  less_destFolder_CX                                      )) // unminified css
     .pipe( cssnano     ({ autoprefixer: false, safe: true                         }))
     .pipe( rename      (  less_destFileMin                                        ))
     .pipe( gulp.dest   (  less_destFolder                                         ))
     .pipe( gulp.dest   (  less_destFolder_CX                                      ))
     .pipe( notify      ({ message:'Styles Complete', onLast:true                  }))
})

// js: Browserify
var js_watchFolder   = app     + 'scripts/**/*.js'
var js_srcFile       = app     + 'scripts/main.js'
var js_destFolder    = dist    + 'js/'
var js_destFolder_CX = dist_CX + 'js/'
var js_destFile      =           'etherwallet-master.js'
var browseOpts       = { debug: true } // generates inline source maps - not in use bc it makes file huuuuge
var babelOpts        = { presets: ['es2015'], compact: false }

function bundle_js(bundler) {
  return bundler.bundle()
    .pipe( plumber   ({ errorHandler: onError }))
    .pipe( source    ( 'main.js'               ))
    .pipe( buffer    (                         ))
    .pipe( rename    ( js_destFile             ))
    .pipe( gulp.dest ( js_destFolder           ))
    .pipe( gulp.dest ( js_destFolder_CX        ))
    .pipe( notify    ({ message:'JS Complete', onLast:true }))
}

gulp.task('js', function () {
  var bundler = browserify( js_srcFile ).transform( babelify, babelOpts )
  bundle_js( bundler )
})

// Rebuild Static JS
var js_srcFilesStatic   = app + 'scripts/staticJS/to-compile-to-static/*.js'
var js_destFolderStatic = app + 'scripts/staticJS/'
var js_destFileStatic   =       'etherwallet-static.min.js'

gulp.task( 'staticJS', function () {
  gulp.src ( js_srcFilesStatic )
     .pipe( plumber   ({ errorHandler: onError }))
     .pipe( concat    (  js_destFileStatic      ))
     .pipe( uglify    (                         ))
     .pipe( gulp.dest (  js_destFolderStatic    ))
     .pipe( notify    ({ message:'Static JS Complete', onLast:true }))
})

// Copy
var imgSrcFolder          = app                 + 'images/**/*'
var fontSrcFolder         = app                 + 'fonts/*.*'
var cxSrcFiles            = app                 + 'includes/browser_action/*.*'
var cxDestFolder          = dist_CX             + 'browser_action'
var staticJSSrcFile       = js_destFolderStatic + js_destFileStatic
var jQueryFile            = './app/scripts/staticJS/jquery-1.12.3.min.js'
var readMe                = './README.md'

gulp.task('copy', function() {
 gulp.src ( imgSrcFolder )
     .pipe( gulp.dest( dist    + 'images' ))
     .pipe( gulp.dest( dist_CX + 'images' ))

 gulp.src ( fontSrcFolder )
     .pipe( gulp.dest( dist    + 'fonts'  ))
     .pipe( gulp.dest( dist_CX + 'fonts'  ))

 gulp.src ( staticJSSrcFile )
     .pipe( gulp.dest( dist    + 'js'     ))
     .pipe( gulp.dest( dist_CX + 'js'     ))

 gulp.src ( jQueryFile )
     .pipe( gulp.dest( dist    + 'js'     ))
     .pipe( gulp.dest( dist_CX + 'js'     ))

 gulp.src ( readMe )
     .pipe( gulp.dest( dist ))

 return gulp.src ( cxSrcFiles )
     .pipe( gulp.dest( cxDestFolder       ))

 .pipe( notify({ message:'Copy Complete', onLast:true }))
})

// Clean files that get compiled but shouldn't
gulp.task('clean', function () {
  return gulp.src([
      dist_CX + 'images/fav',
      dist_CX + 'embedded.html',
      dist_CX + 'index.html',
      dist    + 'cx-wallet.html',
      dist    + 'images/icons',
      './releases/dist-OOPS_TRY_AGAIN.zip',
      './releases/chrome-extension-OOPS_TRY_AGAIN.zip'
    ], {read: false})
    .pipe( plumber ({ errorHandler: onError }))
    .pipe( clean   (                         ))
    .pipe( notify  ({ message:'Clean Complete', onLast:true }))
})

// Bumps Version Number
function bumpFunc(t) {
  return gulp.src([dist_CX + 'manifest.json'])
    .pipe( plumber   ({ errorHandler: onError      }))
    .pipe( bump      ({ type: t                    }))
    .pipe( gulp.dest (  './chrome-extension'       ))
}

// Get Version Number
var versionNum
var versionMsg
gulp.task('getVersion', function() {
  manifest = JSON.parse(fs.readFileSync(dist_CX + 'manifest.json'))
  versionNum = 'v' + manifest.version
  versionMsg    = 'Release: ' + versionNum
  return gulp.src( './' )
  .pipe( notify    ({ message:'Got Version Number: ' + versionNum }))
})

// zips dist folder
gulp.task('zip', ['getVersion','clean'], function() {
 return gulp.src( dist + '*' )
    .pipe( plumber   ({ errorHandler: onError                      }))
    .pipe( zip       (  './dist-' + versionNum + '.zip'             ))
    .pipe( gulp.dest (  './releases/'                               ))
    .pipe( notify    ({ message:'Zip Dist Complete: ' + versionNum }))

})
// zips cx folder
gulp.task('zipCX', ['getVersion','clean'], function() {
  return gulp.src( dist_CX + '*' )
    .pipe( plumber   ({ errorHandler: onError                       }))
    .pipe( zip       (  './chrome-extension-' + versionNum + '.zip'  ))
    .pipe( gulp.dest (  './releases/'                                ))
    .pipe( notify    ({ message:'Zip CX Complete: ' + versionNum    }))

})

// add all
gulp.task('add', ['getVersion'], function() {
  return gulp.src( './' )
    .pipe( git.add() )
    .pipe( notify ({ message:'Added: ' + versionNum }))
})
// commit with current v# in manifest
gulp.task('commit', ['add'], function() {
  return gulp.src( './' )
    .pipe( git.commit(versionMsg) )
    .pipe( notify ({ message:'Committed: ' + versionNum }))
})
// tag with current v# in manifest
gulp.task('tag', ['commit'], function() {
  git.tag(versionNum, versionMsg, function (err) {
    if (err) throw err;
  });
  return gulp.src( './' ).pipe( notify ({ message:'Tagged: ' + versionNum }))
})
// Push Release to Mercury
gulp.task('push', ['tag'], function() {
  git.push('origin', 'mercury', {args: " --tags"}, function (err) {
    if (err) throw err;
  });
  return gulp.src( './' ).pipe( notify ({ message:'Pushed: ' + versionNum }))
})

// Push Live
gulp.task('pushLive', ['push'], shell.task([
  'git subtree push --prefix dist origin gh-pages'
]))

// Watch Tasks
gulp.task('watchJS',    function() { gulp.watch( js_watchFolder,   ['js'    ]) })
gulp.task('watchLess',  function() { gulp.watch( less_watchFolder, ['styles']) })
gulp.task('watchPAGES', function() { gulp.watch( htmlFiles,        ['html'  ]) })
gulp.task('watchTPL',   function() { gulp.watch( tplFiles,         ['html'  ]) })
gulp.task('watchCX',    function() { gulp.watch( cxSrcFiles,       ['copy'  ]) })

gulp.task('watch',      ['watchJS' , 'watchLess', 'watchPAGES', 'watchTPL', 'watchCX'])

// Build
gulp.task('build',      ['html', 'styles', 'js', 'copy'])

// Bump Version
gulp.task('bump-patch', function() { return bumpFunc( 'patch' ) })
gulp.task('bump-minor', function() { return bumpFunc( 'minor' ) })

// Prep for Release
gulp.task('prep',       ['clean', 'getVersion', 'zip', 'zipCX'])

gulp.task('default',      ['build', 'watch'])
<commit_msg>added git pushLive to gulp<commit_after>var fs           = require('fs')

var autoprefixer = require('gulp-autoprefixer')
var bump         = require('gulp-bump')
var babelify     = require('babelify')
var browserify   = require('browserify')
var buffer       = require('vinyl-buffer')
var clean        = require('gulp-clean')
var concat       = require('gulp-concat')
var cssnano      = require('gulp-cssnano')
var fileinclude  = require('gulp-file-include')
var git          = require('gulp-git')
var gulp         = require('gulp')
var less         = require('gulp-less')
var notify       = require('gulp-notify')
var plumber      = require('gulp-plumber' )
var rename       = require('gulp-rename')
var shell        = require('gulp-shell')
var source       = require('vinyl-source-stream')
var uglify       = require('gulp-uglify')
var zip          = require('gulp-zip')

var app          = './app/'
var dist         = './dist/'
var dist_CX      = './chrome-extension/'

function onError( error ){
  notify.onError( {
    title:    'Gulp',
    subtitle: 'Error',
    message:  '<%= error.message %>',
    sound:    'Beep'
  } )( error )
  this.emit('end')
}

//html Pages
var htmlFiles = app + 'layouts/*.html'
var tplFiles  = app + 'includes/*.tpl'

gulp.task('html', function () {
 gulp.src(htmlFiles)
     .pipe( plumber     ({ errorHandler: onError                }))
     .pipe( fileinclude ({ prefix: '@@', basepath: '@file'      }))
     .pipe( gulp.dest   (  dist                                  ))
     .pipe( gulp.dest   (  dist_CX                               ))
     .pipe( notify      ({ message:'HTML Complete', onLast:true }))
})

// styles: Compile and Minify Less / CSS Files
var less_watchFolder   = app     + 'styles/**/*.less'
var less_srcFile       = app     + 'styles/etherwallet-master.less'
var less_destFolder    = dist    + 'css'
var less_destFolder_CX = dist_CX + 'css'
var less_destFile      =           'etherwallet-master.css'
var less_destFileMin   =           'etherwallet-master.min.css'

gulp.task( 'styles', function () {
 gulp.src( less_srcFile )
     .pipe( plumber     ({ errorHandler: onError                                   }))
     .pipe( less        ({ compress: false                                         }))
     .pipe( autoprefixer({ browsers: ['last 2 versions', 'iOS > 8'], remove: false }))
     .pipe( rename      (  less_destFile                                           ))
   //.pipe( gulp.dest   (  less_destFolder                                         )) // unminified css
   //.pipe( gulp.dest   (  less_destFolder_CX                                      )) // unminified css
     .pipe( cssnano     ({ autoprefixer: false, safe: true                         }))
     .pipe( rename      (  less_destFileMin                                        ))
     .pipe( gulp.dest   (  less_destFolder                                         ))
     .pipe( gulp.dest   (  less_destFolder_CX                                      ))
     .pipe( notify      ({ message:'Styles Complete', onLast:true                  }))
})

// js: Browserify
var js_watchFolder   = app     + 'scripts/**/*.js'
var js_srcFile       = app     + 'scripts/main.js'
var js_destFolder    = dist    + 'js/'
var js_destFolder_CX = dist_CX + 'js/'
var js_destFile      =           'etherwallet-master.js'
var browseOpts       = { debug: true } // generates inline source maps - not in use bc it makes file huuuuge
var babelOpts        = { presets: ['es2015'], compact: false }

function bundle_js(bundler) {
  return bundler.bundle()
    .pipe( plumber   ({ errorHandler: onError }))
    .pipe( source    ( 'main.js'               ))
    .pipe( buffer    (                         ))
    .pipe( rename    ( js_destFile             ))
    .pipe( gulp.dest ( js_destFolder           ))
    .pipe( gulp.dest ( js_destFolder_CX        ))
    .pipe( notify    ({ message:'JS Complete', onLast:true }))
}

gulp.task('js', function () {
  var bundler = browserify( js_srcFile ).transform( babelify, babelOpts )
  bundle_js( bundler )
})

// Rebuild Static JS
var js_srcFilesStatic   = app + 'scripts/staticJS/to-compile-to-static/*.js'
var js_destFolderStatic = app + 'scripts/staticJS/'
var js_destFileStatic   =       'etherwallet-static.min.js'

gulp.task( 'staticJS', function () {
  gulp.src ( js_srcFilesStatic )
     .pipe( plumber   ({ errorHandler: onError }))
     .pipe( concat    (  js_destFileStatic      ))
     .pipe( uglify    (                         ))
     .pipe( gulp.dest (  js_destFolderStatic    ))
     .pipe( notify    ({ message:'Static JS Complete', onLast:true }))
})

// Copy
var imgSrcFolder          = app                 + 'images/**/*'
var fontSrcFolder         = app                 + 'fonts/*.*'
var cxSrcFiles            = app                 + 'includes/browser_action/*.*'
var cxDestFolder          = dist_CX             + 'browser_action'
var staticJSSrcFile       = js_destFolderStatic + js_destFileStatic
var jQueryFile            = './app/scripts/staticJS/jquery-1.12.3.min.js'
var readMe                = './README.md'

gulp.task('copy', function() {
 gulp.src ( imgSrcFolder )
     .pipe( gulp.dest( dist    + 'images' ))
     .pipe( gulp.dest( dist_CX + 'images' ))

 gulp.src ( fontSrcFolder )
     .pipe( gulp.dest( dist    + 'fonts'  ))
     .pipe( gulp.dest( dist_CX + 'fonts'  ))

 gulp.src ( staticJSSrcFile )
     .pipe( gulp.dest( dist    + 'js'     ))
     .pipe( gulp.dest( dist_CX + 'js'     ))

 gulp.src ( jQueryFile )
     .pipe( gulp.dest( dist    + 'js'     ))
     .pipe( gulp.dest( dist_CX + 'js'     ))

 gulp.src ( readMe )
     .pipe( gulp.dest( dist ))

 return gulp.src ( cxSrcFiles )
     .pipe( gulp.dest( cxDestFolder       ))

 .pipe( notify({ message:'Copy Complete', onLast:true }))
})

// Clean files that get compiled but shouldn't
gulp.task('clean', function () {
  return gulp.src([
      dist_CX + 'images/fav',
      dist_CX + 'embedded.html',
      dist_CX + 'index.html',
      dist    + 'cx-wallet.html',
      dist    + 'images/icons',
      './releases/dist-OOPS_TRY_AGAIN.zip',
      './releases/chrome-extension-OOPS_TRY_AGAIN.zip'
    ], {read: false})
    .pipe( plumber ({ errorHandler: onError }))
    .pipe( clean   (                         ))
    .pipe( notify  ({ message:'Clean Complete', onLast:true }))
})

// Bumps Version Number
function bumpFunc(t) {
  return gulp.src([dist_CX + 'manifest.json'])
    .pipe( plumber   ({ errorHandler: onError      }))
    .pipe( bump      ({ type: t                    }))
    .pipe( gulp.dest (  './chrome-extension'       ))
}

// Get Version Number
var versionNum
var versionMsg
gulp.task('getVersion', function() {
  manifest = JSON.parse(fs.readFileSync(dist_CX + 'manifest.json'))
  versionNum = 'v' + manifest.version
  versionMsg    = 'Release: ' + versionNum
  return gulp.src( './' )
  .pipe( notify    ({ message:'Got Version Number: ' + versionNum }))
})

// zips dist folder
gulp.task('zip', ['getVersion','clean'], function() {
 return gulp.src( dist + '*' )
    .pipe( plumber   ({ errorHandler: onError                      }))
    .pipe( zip       (  './dist-' + versionNum + '.zip'             ))
    .pipe( gulp.dest (  './releases/'                               ))
    .pipe( notify    ({ message:'Zip Dist Complete: ' + versionNum }))

})
// zips cx folder
gulp.task('zipCX', ['getVersion','clean'], function() {
  return gulp.src( dist_CX + '*' )
    .pipe( plumber   ({ errorHandler: onError                       }))
    .pipe( zip       (  './chrome-extension-' + versionNum + '.zip'  ))
    .pipe( gulp.dest (  './releases/'                                ))
    .pipe( notify    ({ message:'Zip CX Complete: ' + versionNum    }))

})

// add all
gulp.task('add', ['getVersion'], function() {
  return gulp.src( './' )
    .pipe( git.add() )
    .pipe( notify ({ message:'Added: ' + versionNum }))
})
// commit with current v# in manifest
gulp.task('commit', ['add'], function() {
  return gulp.src( './' )
    .pipe( git.commit(versionMsg) )
    .pipe( notify ({ message:'Committed: ' + versionNum }))
})
// tag with current v# in manifest
gulp.task('tag', ['commit'], function() {
  git.tag(versionNum, versionMsg, function (err) {
    if (err) throw err;
  });
  return gulp.src( './' ).pipe( notify ({ message:'Tagged: ' + versionNum }))
})
// Push Release to Mercury
gulp.task('push', ['tag'], function() {
  git.push('origin', 'mercury', {args: " --tags"}, function (err) {
    if (err) throw err;
  });
  return gulp.src( './' ).pipe( notify ({ message:'Pushed: ' + versionNum }))
})

// Push Live
gulp.task('pushLive', shell.task([
  'git subtree push --prefix dist origin gh-pages'
]))

// Watch Tasks
gulp.task('watchJS',    function() { gulp.watch( js_watchFolder,   ['js'    ]) })
gulp.task('watchLess',  function() { gulp.watch( less_watchFolder, ['styles']) })
gulp.task('watchPAGES', function() { gulp.watch( htmlFiles,        ['html'  ]) })
gulp.task('watchTPL',   function() { gulp.watch( tplFiles,         ['html'  ]) })
gulp.task('watchCX',    function() { gulp.watch( cxSrcFiles,       ['copy'  ]) })

gulp.task('watch',      ['watchJS' , 'watchLess', 'watchPAGES', 'watchTPL', 'watchCX'])

// Build
gulp.task('build',      ['html', 'styles', 'js', 'copy'])

// Bump Version
gulp.task('bump-patch', function() { return bumpFunc( 'patch' ) })
gulp.task('bump-minor', function() { return bumpFunc( 'minor' ) })

// Prep for Release
gulp.task('prep',       ['clean', 'getVersion', 'zip', 'zipCX'])

gulp.task('default',      ['build', 'watch'])
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync').create();
var config = {
	'src': './',
	'dest': 'dist/',
	'minify': true,
	'sourcemaps': false
};

// HTML
gulp.task('html', function() {
	return gulp.src('*.html')
		.pipe(browserSync.stream());
});

// Compile and autoprefix stylesheets
gulp.task('styles', function() {
	return gulp.src(config.src + 'scss/*.scss')
		.pipe($.if(config.sourcemaps, $.sourcemaps.init()))
		.pipe($.sass({
			precision: 8,
			outputStyle: 'expanded'
		}).on('error', function(error) {
			$.util.log($.util.colors.red(error.message));
			this.emit('end');
		}))
		.pipe($.postcss([
			autoprefixer()
		]))
		.pipe($.if(config.sourcemaps, $.sourcemaps.write()))
		.pipe(gulp.dest(config.dest + 'css'))
		.pipe(browserSync.stream())
		.pipe($.cleanCss({compatibility: 'ie9'}))
		.pipe($.if(config.sourcemaps, $.sourcemaps.write()))
		.pipe($.rename({suffix: '.min'}))
		.pipe($.if(config.minify, gulp.dest(config.dest + 'css')))
		.pipe(browserSync.stream());
});

// Lint stylesheets
gulp.task('stylelint', function() {
	return gulp.src(config.src + 'scss/**/*.scss')
		.pipe($.postcss([
			require('stylelint')
		], {
			syntax: require('postcss-scss')
		}));
});

// Compile javascript
gulp.task('scripts', function() {
	return gulp.src(config.src + 'js/*.js')
		.pipe($.include().on('error', function(error) {
			$.util.log($.util.colors.red(error.message));
			this.emit('end');
		}))
		.pipe(gulp.dest(config.dest + 'js'))
		.pipe(browserSync.stream())
		.pipe($.if(config.sourcemaps, $.sourcemaps.init()))
		.pipe($.uglify().on('error', function(error) {
			$.util.log($.util.colors.red(error.message));
			this.emit('end');
		}))
		.pipe($.if(config.sourcemaps, $.sourcemaps.write()))
		.pipe($.rename({suffix: '.min'}))
		.pipe($.if(config.minify, gulp.dest(config.dest + 'js')))
		.pipe(browserSync.stream());
});

// Lint javascript
gulp.task('eslint', function() {
	return gulp.src(config.src + 'js/**/*.js')
		.pipe($.eslint())
		.pipe($.eslint.format())
		.pipe($.eslint.failAfterError());
});

// Optimize images
gulp.task('images', function() {
	return gulp.src(config.src + 'img/**/*.{gif,jpg,png,svg}')
		.pipe($.cache($.imagemin()))
		.pipe(gulp.dest(config.dest + 'img'))
		.pipe(browserSync.stream());
});

// Build production files
gulp.task('build', ['html', 'styles', 'scripts', 'images']);

// Serve compiled files
gulp.task('serve', ['build'], function() {
	browserSync.init({
		server: true,
		notify: false,
		snippetOptions: {
			rule: {
				match: /<\/body>/i
			}
		}
		/*
		proxy: 'example.com',
		files: config.dest,
		serveStatic: [{
			route: '', // remote path
			dir: config.dest // local path
		}],
		*/
	});
});

// Watch files for changes
gulp.task('watch', function() {
	gulp.watch('*.html', ['html']);
	gulp.watch(config.src + 'scss/**/*.scss', ['styles']);
	gulp.watch(config.src + 'js/**/*.js', ['scripts']);
	gulp.watch(config.src + 'img/**/*.{gif,jpg,png,svg}', ['images']);
});

// Run all tasks
gulp.task('default', ['serve', 'watch']);
<commit_msg>Indent gulpfile using spaces<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync').create();
var config = {
  'src': './',
  'dest': 'dist/',
  'minify': true,
  'sourcemaps': false
};

// HTML
gulp.task('html', function() {
  return gulp.src('*.html')
    .pipe(browserSync.stream());
});

// Compile and autoprefix stylesheets
gulp.task('styles', function() {
  return gulp.src(config.src + 'scss/*.scss')
    .pipe($.if(config.sourcemaps, $.sourcemaps.init()))
    .pipe($.sass({
      precision: 8,
      outputStyle: 'expanded'
    }).on('error', function(error) {
      $.util.log($.util.colors.red(error.message));
      this.emit('end');
    }))
    .pipe($.postcss([
      autoprefixer()
    ]))
    .pipe($.if(config.sourcemaps, $.sourcemaps.write()))
    .pipe(gulp.dest(config.dest + 'css'))
    .pipe(browserSync.stream())
    .pipe($.cleanCss({compatibility: 'ie9'}))
    .pipe($.if(config.sourcemaps, $.sourcemaps.write()))
    .pipe($.rename({suffix: '.min'}))
    .pipe($.if(config.minify, gulp.dest(config.dest + 'css')))
    .pipe(browserSync.stream());
});

// Lint stylesheets
gulp.task('stylelint', function() {
  return gulp.src(config.src + 'scss/**/*.scss')
    .pipe($.postcss([
      require('stylelint')
    ], {
      syntax: require('postcss-scss')
    }));
});

// Compile javascript
gulp.task('scripts', function() {
  return gulp.src(config.src + 'js/*.js')
    .pipe($.include().on('error', function(error) {
      $.util.log($.util.colors.red(error.message));
      this.emit('end');
    }))
    .pipe(gulp.dest(config.dest + 'js'))
    .pipe(browserSync.stream())
    .pipe($.if(config.sourcemaps, $.sourcemaps.init()))
    .pipe($.uglify().on('error', function(error) {
      $.util.log($.util.colors.red(error.message));
      this.emit('end');
    }))
    .pipe($.if(config.sourcemaps, $.sourcemaps.write()))
    .pipe($.rename({suffix: '.min'}))
    .pipe($.if(config.minify, gulp.dest(config.dest + 'js')))
    .pipe(browserSync.stream());
});

// Lint javascript
gulp.task('eslint', function() {
  return gulp.src(config.src + 'js/**/*.js')
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError());
});

// Optimize images
gulp.task('images', function() {
  return gulp.src(config.src + 'img/**/*.{gif,jpg,png,svg}')
    .pipe($.cache($.imagemin()))
    .pipe(gulp.dest(config.dest + 'img'))
    .pipe(browserSync.stream());
});

// Build production files
gulp.task('build', ['html', 'styles', 'scripts', 'images']);

// Serve compiled files
gulp.task('serve', ['build'], function() {
  browserSync.init({
    server: true,
    notify: false,
    snippetOptions: {
      rule: {
        match: /<\/body>/i
      }
    }
    /*
    proxy: 'example.com',
    files: config.dest,
    serveStatic: [{
      route: '', // remote path
      dir: config.dest // local path
    }],
    */
  });
});

// Watch files for changes
gulp.task('watch', function() {
  gulp.watch('*.html', ['html']);
  gulp.watch(config.src + 'scss/**/*.scss', ['styles']);
  gulp.watch(config.src + 'js/**/*.js', ['scripts']);
  gulp.watch(config.src + 'img/**/*.{gif,jpg,png,svg}', ['images']);
});

// Run all tasks
gulp.task('default', ['serve', 'watch']);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');

var log = function( head, msg ) {
    gutil.log( '[' + gutil.colors.blue( head ) + ']', msg );
};
var logger = function( head ) {
    return function( msg ) {
        log( head, msg );
    };
};

// === IMAGES ===

var images = {
    src: 'resources/assets/images/*',
    dest: 'public/assets/images',

    build: function() {
        var files = gulp.src( images.src );
        return images.handle( files );
    },
    watch: function() {
        var watch = require( 'gulp-watch' );
        var plumber = require('gulp-plumber');

        var files = watch( images.src ).pipe( plumber() );
        return images.handle( files );
    },
    handle: function( source ) {
        var imagemin = require('gulp-imagemin');
        var changed = require('gulp-changed');

        var imageminConfig = {
            progressive: true,
            svgoPlugins: [{ removeViewBox: false }]
        };

        return source
            .pipe( changed( images.dest ))
            .pipe( imagemin( imageminConfig ))
            .pipe( gulp.dest( images.dest ));
    }
};

// === STYLES ===

var styles = {
    paths: {
        src: 'resources/assets/css/*.{scss,sass,css}',
        watch: 'resources/assets/css/**/*.{scss,sass,css}',
        dest: 'public/assets/css'
    },

    build: function() {
        var merge = require('merge-stream');

        return merge(
            styles.buildCss(),
            styles.normalizeCss()
        );
    },
    buildCss: function() {
        var sass = require('gulp-sass');
        var postcss = require('gulp-postcss');
        var autoprefixer = require('autoprefixer-core');
        var minify = require('gulp-minify-css');
        var sourcemaps = require('gulp-sourcemaps');

        log('css', 'build');

        return gulp.src( styles.paths.src )
            .pipe( sourcemaps.init() )
            .pipe( sass() )
            .pipe( postcss([autoprefixer]) )
            .pipe( minify() )
            .pipe( sourcemaps.write( '.' ))
            .pipe( gulp.dest( styles.paths.dest ))
    },
    normalizeCss: function () {
        var minify = require('gulp-minify-css');
        var changed = require('gulp-changed');
        return gulp.src('node_modules/normalize.css/normalize.css')
            .pipe( changed( styles.paths.dest ))
            .pipe( minify() )
            .pipe( gulp.dest( styles.paths.dest ));
    },
    watch: function() {
        var watch = require('gulp-watch');
        return watch( styles.paths.watch, styles.buildCss );
    }
};

// === JS ===

var js = {
    src: './resources/assets/js/*',
    dest: './public/assets/js',
    entry: './resources/assets/js/gw2heroes.js',

    config: {
        entries: './resources/assets/js/gw2heroes.js',
        dest: './public/assets/js',
        outputName: 'gw2heroes.js',
        paths: [ './node_modules', './resources/assets/js/' ],
        fullPaths: false,
        debug: true
    },

    build: function() {
        var browserify = require('browserify');
        var babelify = require('babelify');

        var bundle = browserify( js.config )
            .transform( babelify );

        return js.handle( bundle, js.config );
    },
    watch: function() {
        var browserify = require('browserify');
        var watchify = require('watchify');
        var babelify = require('babelify');
        var extend = require('lodash/object/extend');

        var config = extend( js.config, watchify.args );
        var bundle = watchify( browserify( config ))
            .transform( babelify );

        bundle.on('update', function() {
            js.handle( bundle, config );
        });
        bundle.on( 'log', logger('js') );

        return js.handle( bundle, config )
    },
    handle: function( bundle, config ) {
        var sourcemaps = require('gulp-sourcemaps');
        var uglify = require('gulp-uglify');
        var source = require('vinyl-source-stream');
        var buffer = require('gulp-buffer');

        return bundle
            .bundle()
            .on( 'error', function( err ) {
                log( 'js', gutil.colors.red('Error: ') + err );
            })
            .pipe( source( config.outputName ))
            .pipe( buffer() )
            .pipe( sourcemaps.init({ loadMaps: true }) )
            .pipe( uglify() )
            .pipe( sourcemaps.write( '.' ))
            .pipe( gulp.dest( config.dest ));
    }
};

// === GENERAL ===

var general = {
    src: 'resources/assets',
    dest: 'public/assets',

    build: function() {
        var merge = require('merge-stream');

        return merge(
            images.build(),
            styles.build(),
            js.build()
        );
    },
    clean: function( cb ) {
        var del = require('del');
        del( general.dest, cb );
    },
    watch: function() {
        styles.build();
        styles.watch();

        images.build();
        images.watch();

        js.watch();
    }
};

gulp.task( 'watch', general.watch );
gulp.task( 'clean', general.clean );
gulp.task( 'build', general.build );
gulp.task( 'build:js', js.build );
gulp.task( 'build:css', styles.build );
gulp.task( 'build:images', images.build );
gulp.task( 'build-clean', ['clean'], general.build );
// alias default = build
gulp.task( 'default', ['build'] );
<commit_msg>minify images in subdirectories<commit_after>'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');

var log = function( head, msg ) {
    gutil.log( '[' + gutil.colors.blue( head ) + ']', msg );
};
var logger = function( head ) {
    return function( msg ) {
        log( head, msg );
    };
};

// === IMAGES ===

var images = {
    src: 'resources/assets/images/*/**.{svg,png,jpg}',
    dest: 'public/assets/images',

    build: function() {
        var files = gulp.src( images.src );
        return images.handle( files );
    },
    watch: function() {
        var watch = require( 'gulp-watch' );
        var plumber = require('gulp-plumber');

        var files = watch( images.src ).pipe( plumber() );
        return images.handle( files );
    },
    handle: function( source ) {
        var imagemin = require('gulp-imagemin');
        var changed = require('gulp-changed');

        var imageminConfig = {
            progressive: true,
            svgoPlugins: [{ removeViewBox: false }]
        };

        return source
            .pipe( changed( images.dest ))
            .pipe( imagemin( imageminConfig ))
            .pipe( gulp.dest( images.dest ));
    }
};

// === STYLES ===

var styles = {
    paths: {
        src: 'resources/assets/css/*.{scss,sass,css}',
        watch: 'resources/assets/css/**/*.{scss,sass,css}',
        dest: 'public/assets/css'
    },

    build: function() {
        var merge = require('merge-stream');

        return merge(
            styles.buildCss(),
            styles.normalizeCss()
        );
    },
    buildCss: function() {
        var sass = require('gulp-sass');
        var postcss = require('gulp-postcss');
        var autoprefixer = require('autoprefixer-core');
        var minify = require('gulp-minify-css');
        var sourcemaps = require('gulp-sourcemaps');

        log('css', 'build');

        return gulp.src( styles.paths.src )
            .pipe( sourcemaps.init() )
            .pipe( sass() )
            .pipe( postcss([autoprefixer]) )
            .pipe( minify() )
            .pipe( sourcemaps.write( '.' ))
            .pipe( gulp.dest( styles.paths.dest ))
    },
    normalizeCss: function () {
        var minify = require('gulp-minify-css');
        var changed = require('gulp-changed');
        return gulp.src('node_modules/normalize.css/normalize.css')
            .pipe( changed( styles.paths.dest ))
            .pipe( minify() )
            .pipe( gulp.dest( styles.paths.dest ));
    },
    watch: function() {
        var watch = require('gulp-watch');
        return watch( styles.paths.watch, styles.buildCss );
    }
};

// === JS ===

var js = {
    src: './resources/assets/js/*',
    dest: './public/assets/js',
    entry: './resources/assets/js/gw2heroes.js',

    config: {
        entries: './resources/assets/js/gw2heroes.js',
        dest: './public/assets/js',
        outputName: 'gw2heroes.js',
        paths: [ './node_modules', './resources/assets/js/' ],
        fullPaths: false,
        debug: true
    },

    build: function() {
        var browserify = require('browserify');
        var babelify = require('babelify');

        var bundle = browserify( js.config )
            .transform( babelify );

        return js.handle( bundle, js.config );
    },
    watch: function() {
        var browserify = require('browserify');
        var watchify = require('watchify');
        var babelify = require('babelify');
        var extend = require('lodash/object/extend');

        var config = extend( js.config, watchify.args );
        var bundle = watchify( browserify( config ))
            .transform( babelify );

        bundle.on('update', function() {
            js.handle( bundle, config );
        });
        bundle.on( 'log', logger('js') );

        return js.handle( bundle, config )
    },
    handle: function( bundle, config ) {
        var sourcemaps = require('gulp-sourcemaps');
        var uglify = require('gulp-uglify');
        var source = require('vinyl-source-stream');
        var buffer = require('gulp-buffer');

        return bundle
            .bundle()
            .on( 'error', function( err ) {
                log( 'js', gutil.colors.red('Error: ') + err );
            })
            .pipe( source( config.outputName ))
            .pipe( buffer() )
            .pipe( sourcemaps.init({ loadMaps: true }) )
            .pipe( uglify() )
            .pipe( sourcemaps.write( '.' ))
            .pipe( gulp.dest( config.dest ));
    }
};

// === GENERAL ===

var general = {
    src: 'resources/assets',
    dest: 'public/assets',

    build: function() {
        var merge = require('merge-stream');

        return merge(
            images.build(),
            styles.build(),
            js.build()
        );
    },
    clean: function( cb ) {
        var del = require('del');
        del( general.dest, cb );
    },
    watch: function() {
        styles.build();
        styles.watch();

        images.build();
        images.watch();

        js.watch();
    }
};

gulp.task( 'watch', general.watch );
gulp.task( 'clean', general.clean );
gulp.task( 'build', general.build );
gulp.task( 'build:js', js.build );
gulp.task( 'build:css', styles.build );
gulp.task( 'build:images', images.build );
gulp.task( 'build-clean', ['clean'], general.build );
// alias default = build
gulp.task( 'default', ['build'] );
<|endoftext|>