<commit_before>'use strict';
// generated on 2017-03-03 using generator-gulp-bootstrap 0.0.4

var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gutil = require('gulp-util');
var sassJson = require('gulp-sass-json');

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

gulp.task('styles', ['sassvars'], function () {
    return gulp.src('app/styles/main.scss')
        .pipe($.sass({ errLogToConsole: true }))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('app/styles'))
        .pipe(reload({ stream: true }))
        .pipe($.size());
});

gulp.task('sassvars', function () {
    return gulp.src('app/styles/base/_variables.scss')
        .pipe(sassJson())
        .pipe(gulp.dest('app/styles'));
});

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

    gulp.src('app/scripts/main/**/*.html')
        .pipe($.angularTemplatecache('templates.js', {
            module: 'vbr-style-guide'
        }))
        .pipe(gulp.dest('app/scripts/main'));

    return gulp.src(['app/scripts/main/**/*.module.js', 'app/scripts/main/**/*.js'])
        .pipe($.jshint())
        .pipe($.ngAnnotate({
            remove: true,
            add: true,
            single_quotes: true
        }))
        .pipe($.uglify())
        .pipe($.concat('main.js'))
        .pipe(gulp.dest('app/scripts'))
        .pipe($.jshint.reporter(require('jshint-stylish')))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('styleguide'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('styleguide/images'))
        .pipe(reload({ stream: true, once: true }))
        .pipe($.size());
});

gulp.task('fonts', function () {
    var streamqueue = require('streamqueue');
    return streamqueue({ objectMode: true },
        $.bowerFiles(),
        gulp.src('app/fonts/**/*')
    )
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('styleguide/fonts'))
        .pipe($.size());
});

gulp.task('clean', function () {
    return gulp.src(['app/styles/main.css', 'app/styles/variables.json', 'styleguide', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('serve', ['aigis'], function () {
    browserSync.init(null, {
        server: {
            baseDir: 'styleguide',
            directory: true
        },
        debugInfo: false,
        open: false
    }, function (err, bs) {
        require('opn')(bs.options.url);
        console.log('Started connect web server on ' + bs.options.url);
    });
});

// inject bower components
gulp.task('wiredep', function () {
    var wiredep = require('wiredep').stream;
    gulp.src('app/styles/*.scss')
        .pipe(wiredep({
            directory: 'bower_components'
        }))
        .pipe(gulp.dest('app/styles'));
    gulp.src('template_ejs/scripts.ejs')
        .pipe(wiredep({
            directory: 'bower_components',
            fileTypes: {
                html: {
                    replace: {
                        js: '<script src="<%- root%>{{filePath}}"></script>'
                    }
                }
            }
        }))
        .pipe(gulp.dest('template_ejs'));
});

gulp.task('watch', ['serve'], function () {

    // watch for changes
    gulp.watch(['styleguide/*.html'], reload);
    gulp.watch(['aigis_config.yml', 'template_ejs/**/*', 'aigis_assets/**/*'], ['aigis', 'delayed-reload']);
    gulp.watch('app/styles/**/*.scss', ['styles', 'aigis']);
    gulp.watch(['app/scripts/**/*.js', 'app/scripts/**/*.html'], ['scripts', 'aigis']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('html/**/*', ['aigis']);
    gulp.watch('bower.json', ['wiredep', 'aigis']);
});

gulp.task("aigis", ['styles', 'scripts'], function () {
    gulp.src("./aigis_config.yml")
        .pipe($.aigis());
});

gulp.task('delayed-reload', function () {
    setTimeout(reload, 5000);
});

gulp.task('build', ['clean'], function () {
    gulp.src('app/styles/**/*.scss')
        .pipe($.size())
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['clean'], function () {
    gulp.start('watch');
});
<commit_msg>add build process for distributing<commit_after>'use strict';
// generated on 2017-03-03 using generator-gulp-bootstrap 0.0.4

var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gutil = require('gulp-util');
var sassJson = require('gulp-sass-json');

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

gulp.task('styles', ['sassvars'], function () {
    return gulp.src('app/styles/main.scss')
        .pipe($.sass({ errLogToConsole: true }))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('app/styles'))
        .pipe(reload({ stream: true }))
        .pipe($.size());
});

gulp.task('sassvars', function () {
    return gulp.src('app/styles/base/_variables.scss')
        .pipe(sassJson())
        .pipe(gulp.dest('app/styles'));
});

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

    gulp.src('app/scripts/main/**/*.html')
        .pipe($.angularTemplatecache('templates.js', {
            module: 'vbr-style-guide'
        }))
        .pipe(gulp.dest('app/scripts/main'));

    return gulp.src(['app/scripts/main/**/*.module.js', 'app/scripts/main/**/*.js'])
        .pipe($.jshint())
        .pipe($.ngAnnotate({
            remove: true,
            add: true,
            single_quotes: true
        }))
        .pipe($.uglify())
        .pipe($.concat('main.js'))
        .pipe(gulp.dest('app/scripts'))
        .pipe($.jshint.reporter(require('jshint-stylish')))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('styleguide'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('styleguide/images'))
        .pipe(reload({ stream: true, once: true }))
        .pipe($.size());
});

gulp.task('fonts', function () {
    var streamqueue = require('streamqueue');
    return streamqueue({ objectMode: true },
        $.bowerFiles(),
        gulp.src('app/fonts/**/*')
    )
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('styleguide/fonts'))
        .pipe($.size());
});

gulp.task('clean', function () {
    return gulp.src(['app/styles/main.css', 'app/styles/variables.json', 'styleguide', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('serve', ['aigis'], function () {
    browserSync.init(null, {
        server: {
            baseDir: 'styleguide',
            directory: true
        },
        debugInfo: false,
        open: false
    }, function (err, bs) {
        require('opn')(bs.options.url);
        console.log('Started connect web server on ' + bs.options.url);
    });
});

// inject bower components
gulp.task('wiredep', function () {
    var wiredep = require('wiredep').stream;
    gulp.src('app/styles/*.scss')
        .pipe(wiredep({
            directory: 'bower_components'
        }))
        .pipe(gulp.dest('app/styles'));
    gulp.src('template_ejs/scripts.ejs')
        .pipe(wiredep({
            directory: 'bower_components',
            fileTypes: {
                html: {
                    replace: {
                        js: '<script src="<%- root%>{{filePath}}"></script>'
                    }
                }
            }
        }))
        .pipe(gulp.dest('template_ejs'));
});

gulp.task('watch', ['serve'], function () {

    // watch for changes
    gulp.watch(['styleguide/*.html'], reload);
    gulp.watch(['aigis_config.yml', 'template_ejs/**/*', 'aigis_assets/**/*'], ['aigis', 'delayed-reload']);
    gulp.watch('app/styles/**/*.scss', ['styles', 'aigis']);
    gulp.watch(['app/scripts/**/*.js', 'app/scripts/**/*.html'], ['scripts', 'aigis']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('html/**/*', ['aigis']);
    gulp.watch('bower.json', ['wiredep', 'aigis']);
});

gulp.task("aigis", ['styles', 'scripts'], function () {
    gulp.src("./aigis_config.yml")
        .pipe($.aigis());
});

gulp.task('delayed-reload', function () {
    setTimeout(reload, 5000);
});

function buildStyles() {
    return gulp.src('app/styles/**/*.scss')
        .pipe($.size())
        .pipe(gulp.dest('dist/scss'));
}

function buildScripts() {
    return gulp.src(['app/scripts/main/components/**/*', 'app/scripts/main/styleguide.*.js'])
        .pipe($.size())
        .pipe(gulp.dest('dist/scripts'));
}

gulp.task('build', ['clean'], function () {
    buildStyles();
    buildScripts();
    return gulp.src('bower.json').pipe(gulp.dest('dist'));
});

gulp.task('default', ['clean'], function () {
    gulp.start('watch');
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp')
  , sass = require('gulp-sass')
  , autoprefixer = require('gulp-autoprefixer')
  , imagemin = require('gulp-imagemin')
  , util = require('gulp-util')
  , browserify = require('browserify')
  , es2040 = require('es2040')
  , buffer = require('vinyl-buffer')
  , source = require('vinyl-source-stream')
  , uglify = require('gulp-uglify')
  , http_server = require('http-server')
  , connect_logger = require('connect-logger')
  , spawn = require('child_process').spawn
  , mocha = require('gulp-mocha')
  ;

var SRC = {
  html:    './static/html',
  scss:    './static/scss',
  img:     './static/img',
  js:      './static/js',
  extra:   './static/rootExtra'
};

var DEST = {
  html:'./app/static',
  css: './app/static/css',
  img: './app/static/img',
  js:  './app/static/js'
};

gulp.task('html', function() {
  gulp.src(SRC.html + '/*.html')
    .pipe(gulp.dest(DEST.html));
});

gulp.task('html:watch', function() {
  gulp.watch(`${SRC.html}/*.html`, ['html']);
});

gulp.task('html:serve', function (cb) {
  var server = new http_server.HttpServer({
    root: 'app/static',
    before: [connect_logger()]
  });
  server.listen(8000, function () {
    util.log('HTTP server started on port 8000');
    cb();
  });
});

// Compile Sass into CSS
gulp.task('sass', function() {
  gulp.src(`${SRC.scss}/*.scss`)
    .pipe(sass({
      outputStyle: 'compressed'
    }).on('error', sass.logError))
    .pipe(autoprefixer('last 2 version'))
    .pipe(gulp.dest(DEST.css));
});

gulp.task('sass:watch', function() {
  gulp.watch(`${SRC.scss}/**/*.scss`, ['sass']);
});

// Copy/minify image assets
gulp.task('copy-images', function() {
  gulp.src(SRC.img + '/**/*.+(png|jpg|jpeg|gif|svg)')
    .pipe(imagemin())
    .pipe(gulp.dest(DEST.img));
});

gulp.task('copy-images:watch', function() {
  gulp.watch(SRC.img + '/**/*.+(png|jpg|jpeg|gif|svg)');
});

// Bundle and transpile javascript
gulp.task('scripts', function() {
  var b = browserify({
    entries: `${SRC.js}/main.js`,
    debug: true,
    transform: [es2040]
  });

  return b.bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(gulp.dest(DEST.js));
});

gulp.task('build-scripts', function() {
  var b = browserify({
    entries: `${SRC.js}/main.js`,
    debug: false,
    transform: [es2040]
  });

  return b.bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest(DEST.js));
});

gulp.task('scripts:watch', function() {
  gulp.watch(`${SRC.js}/**/*.js`, ['scripts']);
});

gulp.task('extra', function() {
  gulp.src(SRC.extra + '/*.+(ico|xml|json)')
    .pipe(gulp.dest(DEST.html));
});

function runKarmaTests ({singleRun, configFile} = {}) {
  return new Promise((resolve, reject) => {
    const karmaArguments = ['start'];

    if (configFile) {
      karmaArguments.push(configFile);
    }

    if (singleRun) {
      karmaArguments.push('--single-run');
    }

    // Karma has a nice public API, but has issues where it can hang when
    // trying to shut down after completing tests, so run it as a separate
    // process instead. See:
    // https://github.com/karma-runner/karma/issues/1693
    // https://github.com/karma-runner/karma/issues/1035
    const karma = spawn('./node_modules/.bin/karma', karmaArguments, {
      cwd: __dirname,
      stdio: 'inherit'
    });

    karma.on('close', code => {
      if (code) {
        reject(new util.PluginError('Karma', `JS unit tests failed (code ${code})`));
        return;
      }
      resolve();
    });
  });
}

gulp.task('test:js-unit', function() {
  return runKarmaTests({singleRun: true});
});

gulp.task('test:watch', function() {
  return runKarmaTests({singleRun: false});
});

gulp.task('test:e2e', function() {
  return gulp.src([
    './e2e-tests/support/setupEndToEndTests.js',
    './e2e-tests/{*,!(support)/*}.js'
  ])
    .pipe(mocha({
      reporter: 'spec',
      timeout: 6000
    }));
});

// Designed for running tests in continuous integration. The main difference
// here is that browser tests are run across a gamut of browsers/platforms via
// Sauce Labs instead of just a few locally.
gulp.task('test:ci', ['eslint'], function() {
  return runKarmaTests({configFile: 'karma.ci.conf.js'});
});

gulp.task('eslint', function() {
  const eslint = require('eslint');
  const linter = new eslint.CLIEngine();
  const report = linter.executeOnFiles(['./']);

  // customize messages to be a little more helpful/friendly
  report.results.forEach(result => {
    result.messages.forEach(message => {
      if (message.ruleId === 'no-console') {
        message.message = 'Please use the `loglevel` module for logging instead of the browser `console` object';
      }
    });
  });

  process.stdout.write(linter.getFormatter()(report.results));
  if (report.errorCount) {
    throw new util.PluginError('ESLint', 'Found problems with JS coding style.');
  }
});

gulp.task('test', ['eslint', 'test:js-unit']);

gulp.task('default', ['html', 'html:watch', 'html:serve', 'sass', 'sass:watch', 'copy-images', 'copy-images:watch', 'scripts', 'scripts:watch', 'extra']);
gulp.task('deploy', ['html', 'sass', 'build-scripts', 'extra', 'copy-images']);
<commit_msg>create middleware to treat any urls without a file extension as a top level request<commit_after>'use strict';

var gulp = require('gulp')
  , sass = require('gulp-sass')
  , autoprefixer = require('gulp-autoprefixer')
  , imagemin = require('gulp-imagemin')
  , util = require('gulp-util')
  , browserify = require('browserify')
  , es2040 = require('es2040')
  , buffer = require('vinyl-buffer')
  , source = require('vinyl-source-stream')
  , uglify = require('gulp-uglify')
  , http_server = require('http-server')
  , connect_logger = require('connect-logger')
  , spawn = require('child_process').spawn
  , mocha = require('gulp-mocha')
  , path = require('path')
  ;

var SRC = {
  html:    './static/html',
  scss:    './static/scss',
  img:     './static/img',
  js:      './static/js',
  extra:   './static/rootExtra'
};

var DEST = {
  html:'./app/static',
  css: './app/static/css',
  img: './app/static/img',
  js:  './app/static/js'
};

gulp.task('html', function() {
  gulp.src(SRC.html + '/*.html')
    .pipe(gulp.dest(DEST.html));
});

gulp.task('html:watch', function() {
  gulp.watch(`${SRC.html}/*.html`, ['html']);
});

gulp.task('html:serve', function (cb) {

  function alwaysServeIndex(req, res, next) {

    // Allow the development server to respond to URLs defined in the front end application.
    // Assume that any URL without a file extension can be handled by the client side code
    // and serve index.html (instead of 404).

    if(!(path.extname(req.url))) {
      req.url = "/";
    }
    next();
  }

  var server = new http_server.HttpServer({
    root: 'app/static',
    before: [connect_logger(), alwaysServeIndex]
  });
  server.listen(8000, function () {
    util.log('HTTP server started on port 8000');
    cb();
  });
});

// Compile Sass into CSS
gulp.task('sass', function() {
  gulp.src(`${SRC.scss}/*.scss`)
    .pipe(sass({
      outputStyle: 'compressed'
    }).on('error', sass.logError))
    .pipe(autoprefixer('last 2 version'))
    .pipe(gulp.dest(DEST.css));
});

gulp.task('sass:watch', function() {
  gulp.watch(`${SRC.scss}/**/*.scss`, ['sass']);
});

// Copy/minify image assets
gulp.task('copy-images', function() {
  gulp.src(SRC.img + '/**/*.+(png|jpg|jpeg|gif|svg)')
    .pipe(imagemin())
    .pipe(gulp.dest(DEST.img));
});

gulp.task('copy-images:watch', function() {
  gulp.watch(SRC.img + '/**/*.+(png|jpg|jpeg|gif|svg)');
});

// Bundle and transpile javascript
gulp.task('scripts', function() {
  var b = browserify({
    entries: `${SRC.js}/main.js`,
    debug: true,
    transform: [es2040]
  });

  return b.bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(gulp.dest(DEST.js));
});

gulp.task('build-scripts', function() {
  var b = browserify({
    entries: `${SRC.js}/main.js`,
    debug: false,
    transform: [es2040]
  });

  return b.bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest(DEST.js));
});

gulp.task('scripts:watch', function() {
  gulp.watch(`${SRC.js}/**/*.js`, ['scripts']);
});

gulp.task('extra', function() {
  gulp.src(SRC.extra + '/*.+(ico|xml|json)')
    .pipe(gulp.dest(DEST.html));
});

function runKarmaTests ({singleRun, configFile} = {}) {
  return new Promise((resolve, reject) => {
    const karmaArguments = ['start'];

    if (configFile) {
      karmaArguments.push(configFile);
    }

    if (singleRun) {
      karmaArguments.push('--single-run');
    }

    // Karma has a nice public API, but has issues where it can hang when
    // trying to shut down after completing tests, so run it as a separate
    // process instead. See:
    // https://github.com/karma-runner/karma/issues/1693
    // https://github.com/karma-runner/karma/issues/1035
    const karma = spawn('./node_modules/.bin/karma', karmaArguments, {
      cwd: __dirname,
      stdio: 'inherit'
    });

    karma.on('close', code => {
      if (code) {
        reject(new util.PluginError('Karma', `JS unit tests failed (code ${code})`));
        return;
      }
      resolve();
    });
  });
}

gulp.task('test:js-unit', function() {
  return runKarmaTests({singleRun: true});
});

gulp.task('test:watch', function() {
  return runKarmaTests({singleRun: false});
});

gulp.task('test:e2e', function() {
  return gulp.src([
    './e2e-tests/support/setupEndToEndTests.js',
    './e2e-tests/{*,!(support)/*}.js'
  ])
    .pipe(mocha({
      reporter: 'spec',
      timeout: 6000
    }));
});

// Designed for running tests in continuous integration. The main difference
// here is that browser tests are run across a gamut of browsers/platforms via
// Sauce Labs instead of just a few locally.
gulp.task('test:ci', ['eslint'], function() {
  return runKarmaTests({configFile: 'karma.ci.conf.js'});
});

gulp.task('eslint', function() {
  const eslint = require('eslint');
  const linter = new eslint.CLIEngine();
  const report = linter.executeOnFiles(['./']);

  // customize messages to be a little more helpful/friendly
  report.results.forEach(result => {
    result.messages.forEach(message => {
      if (message.ruleId === 'no-console') {
        message.message = 'Please use the `loglevel` module for logging instead of the browser `console` object';
      }
    });
  });

  process.stdout.write(linter.getFormatter()(report.results));
  if (report.errorCount) {
    throw new util.PluginError('ESLint', 'Found problems with JS coding style.');
  }
});

gulp.task('test', ['eslint', 'test:js-unit']);

gulp.task('default', ['html', 'html:watch', 'html:serve', 'sass', 'sass:watch', 'copy-images', 'copy-images:watch', 'scripts', 'scripts:watch', 'extra']);
gulp.task('deploy', ['html', 'sass', 'build-scripts', 'extra', 'copy-images']);
<|endoftext|>


<commit_before>/**
 * @version 1.4.0
 * @author bigfact
 * @date 2016.3.18
 */

/**
 * gulp
 */
var gulp = require('gulp');

/**
 * 开发服务器加载
 */
var browserSync = require('browser-sync').create();

/**
 * sass 编译器
 */
var compass = require('gulp-compass');

/**
 * 文件状态监听器
 */
var watch = require('gulp-watch');

/**
 * 根路径
 */
var root = './';

/**
 * 子项目路径
 */
var thing = '';
var argv = process.argv;
for (var i = 0; i < argv.length; i++) {
	argv[i].indexOf('--thing') >= 0 && (thing = argv[i].split('=')[1]);
}

/**
 * 开发任务
 */

/**
 * 源文件目录
 */
var src = root + (thing ? thing + '/src/' : '');

/**
 * 编译 sass 文件
 */
gulp.task('build-sass', function () {
	return gulp.src(src + 'sass/**/*.scss')
		.pipe(compass({
			css: src + 'css',
			sass: src + 'sass'
		})).on('error', (err) => {
			console.log('sass Error!', err.message);
		});
});

/**
 * 开发服务器任务、文件监听
 */
gulp.task('browser', function () {

	// 监听文件自动刷新
	watch([src + '**/**.js', src + '**/**.css', src + '**/**.html'], browserSync.reload);

	gulp.watch(src + 'sass/**/*.scss', gulp.parallel('build-sass'));

	// 开发服务器
	return browserSync.init({
		server: {
			baseDir: root,
			//开启目录浏览
			directory: true
		},
		port: 4001,
		startPath: src,
		// 禁用、启用每个单独的功能
		// ghostMode: {
		//     clicks: true,
		//     forms: true,
		//     scroll: false
		// },
		// 禁用操作同步
		ghostMode: false
	});
});

/**
 * 开启开发任务
 */
gulp.task('debug', gulp.series('build-sass', 'browser'), function (callback) {
	callback();
});

/**
 * 发布任务
 */

/**
 * 发布目录
 */
var dist = root + (thing ? thing + '/dist/' : '');

/**
 * 目录清空插件
 */
var clean = require('gulp-clean');

/**
 * css 压缩器
 */
var cleancss = require('gulp-clean-css');

/**
 * 文件重命名插件
 */
var rename = require('gulp-rename');

/**
 * js 压缩器
 */
var uglify = require('gulp-uglify');

/**
 * 清空 dist 目录
 */
gulp.task('clean', function () {
	return gulp.src(dist, { read: false })
		.pipe(clean());
});

/**
 * 图片文件处理
 */
gulp.task('img', function () {
	return gulp.src(src + '**/img/**/*.*')
		// .pipe(rev())
		.pipe(gulp.dest(dist))
		// .pipe(rev.manifest())
		// .pipe(gulp.dest(revd + imgs))
		;
});

/**
 * js 文件处理
 */
gulp.task('js', function () {
	return gulp.src(src + '**/*.js')
		.pipe(gulp.dest(dist))
		// 丑化
		.pipe(uglify())
		// 重命名
		.pipe(rename({ suffix: '.min' }))
		// 计算 hash
		// .pipe(rev())
		// 发布到 dist
		.pipe(gulp.dest(dist))
		// // 生成列表
		// .pipe(rev.manifest())
		// // 列表发布到 rev
		// .pipe(gulp.dest(revd + js))
		;
});

/**
 *  css 文件处理
 */
gulp.task('css', function () {
	return gulp.src(src + '**/*.css')
		.pipe(gulp.dest(dist))
		.pipe(cleancss())
		.pipe(rename({ suffix: '.min' }))
		// .pipe(rev())
		.pipe(gulp.dest(dist))
		// .pipe(rev.manifest())
		// .pipe(gulp.dest(revd + css))
		;
});

// // css 替换链接文件，并给 css 文件打版本号
// gulp.task('cssrevc', function() {
//     return gulp.src([rev + '**', dist + css + '**'])
//         .pipe(revCollector())
//         .pipe(rev())
//         .pipe(gulp.dest(dist + css))
//         .pipe(rev.manifest())
//         .pipe(gulp.dest(revd + css));
// });

/**
 * html 文件处理
 */
gulp.task('html', function () {
	return gulp.src(src + '**/*.html')
		.pipe(gulp.dest(dist));
});

/**
 * 发布任务
 */
gulp.task('build', gulp.series(
	'clean',
	'html',
	'img',
	'build-sass',
	'css',
	'js'
));<commit_msg>frontforge + 1.4.0 + gulp 任务更新<commit_after>/**
 * @version 1.4.0
 * @author bigfact
 * @date 2016.3.18
 */

/**
 * gulp
 */
var gulp = require('gulp');

/**
 * 开发服务器加载
 */
var browserSync = require('browser-sync').create();

/**
 * sass 编译器
 */
var compass = require('gulp-compass');

/**
 * 文件状态监听器
 */
var watch = require('gulp-watch');

/**
 * 根路径
 */
var root = './';

/**
 * 子项目路径
 */
var thing = '';
var argv = process.argv;
for (var i = 0; i < argv.length; i++) {
	argv[i].indexOf('--thing') >= 0 && (thing = argv[i].split('=')[1]);
}

// gulp debug --thing=things/fool2016
// gulp build --thing=things/fool2016

/**
 * 开发任务
 */

/**
 * 源文件目录
 */
var src = root + (thing ? thing + '/' : '');

/**
 * 编译 sass 文件
 */
gulp.task('build-sass', function () {
	return gulp.src(src + 'sass/**/*.scss')
		.pipe(compass({
			css: src + 'css',
			sass: src + 'sass'
		})).on('error', (err) => {
			console.log('sass Error!', err.message);
		});
});

/**
 * 开发服务器任务、文件监听
 */
gulp.task('browser', function () {

	// 监听文件自动刷新
	watch([src + '**/**.js', src + '**/**.css', src + '**/**.html'], browserSync.reload);

	gulp.watch(src + 'sass/**/*.scss', gulp.parallel('build-sass'));

	// 开发服务器
	return browserSync.init({
		server: {
			baseDir: root,
			//开启目录浏览
			directory: true
		},
		port: 4001,
		startPath: src,
		// 禁用、启用每个单独的功能
		// ghostMode: {
		//     clicks: true,
		//     forms: true,
		//     scroll: false
		// },
		// 禁用操作同步
		ghostMode: false
	});
});

/**
 * 开启开发任务
 */
gulp.task('debug', gulp.series('build-sass', 'browser'), function (callback) {
	callback();
});

/**
 * 发布任务
 */

/**
 * 发布目录
 */
var dist = root + (thing ? thing + '/' : '');

// /**
//  * 目录清空插件
//  */
// var clean = require('gulp-clean');

/**
 * css 压缩器
 */
var cleancss = require('gulp-clean-css');

/**
 * 文件重命名插件
 */
var rename = require('gulp-rename');

/**
 * js 压缩器
 */
var uglify = require('gulp-uglify');

// /**
//  * 清空 dist 目录
//  */
// gulp.task('clean', function () {
// 	return gulp.src(dist, { read: false })
// 		.pipe(clean());
// });

// /**
//  * 图片文件处理
//  */
// gulp.task('img', function () {
// 	return gulp.src(src + '**/img/**/*.*')
// 		// .pipe(rev())
// 		.pipe(gulp.dest(dist))
// 		// .pipe(rev.manifest())
// 		// .pipe(gulp.dest(revd + imgs))
// 		;
// });

/**
 * js 文件处理
 */
gulp.task('js', function () {
	return gulp.src([src + '**/*.js', '!' + src + '**/*.min.js'])
		// .pipe(gulp.dest(dist))
		// 丑化
		.pipe(uglify())
		// 重命名
		.pipe(rename({ suffix: '.min' }))
		// 计算 hash
		// .pipe(rev())
		// 发布到 dist
		.pipe(gulp.dest(dist))
		// // 生成列表
		// .pipe(rev.manifest())
		// // 列表发布到 rev
		// .pipe(gulp.dest(revd + js))
		;
});

/**
 *  css 文件处理
 */
gulp.task('css', function () {
	return gulp.src([src + '**/*.css', '!' + src + '**/*.min.css'])
		// .pipe(gulp.dest(dist))
		.pipe(cleancss())
		.pipe(rename({ suffix: '.min' }))
		// .pipe(rev())
		.pipe(gulp.dest(dist))
		// .pipe(rev.manifest())
		// .pipe(gulp.dest(revd + css))
		;
});

// // css 替换链接文件，并给 css 文件打版本号
// gulp.task('cssrevc', function() {
//     return gulp.src([rev + '**', dist + css + '**'])
//         .pipe(revCollector())
//         .pipe(rev())
//         .pipe(gulp.dest(dist + css))
//         .pipe(rev.manifest())
//         .pipe(gulp.dest(revd + css));
// });

// /**
//  * html 文件处理
//  */
// gulp.task('html', function () {
// 	return gulp.src(src + '**/*.html')
// 		.pipe(gulp.dest(dist));
// });

/**
 * 发布任务
 */
gulp.task('build', gulp.series(
	// 'clean',
	// 'html',
	// 'img',
	'build-sass',
	'css',
	'js'
));<|endoftext|>


<commit_before>var gulp = require('gulp'),

    gutil = require('gulp-util'),
    clean = require('gulp-clean'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    less = require('gulp-less'),
    csso = require('gulp-csso'),
    imagemin = require('gulp-imagemin'),
    connect = require('gulp-connect'),
    handlebars = require('gulp-handlebars'),
    defineModule = require('gulp-define-module'),
    declare = require('gulp-declare'),
    jshint = require('gulp-jshint'),
    plumber = require('gulp-plumber'),
    headerfooter = require('gulp-headerfooter'),

    runSequence = require('run-sequence'),

    args = require('yargs').argv;

var config = require('./config.js'),

    defaultConfig = {
        port: 3000,
        root: ''
    };

var buildOptions = {
        release: 'r' in args || 'release' in args
    };

gulp.task('default', function() {
    return gulp.start('dev');
});

gulp.task('d', ['dev']);

gulp.task('dev', ['build'], function(callback) {
    return runSequence('build', 'connect', 'watch', callback);
});

gulp.task('watch', function(callback) {
    gulp.watch('./source/blocks/**/*.less', ['build-css']);
    gulp.watch('./source/less/**/*.less', ['build-css']);

    gulp.watch('./source/blocks/**/*.js', ['build-js']);
    gulp.watch('./source/js/**/*.js', ['build-js']);

    gulp.watch('./source/images/**/*.{jpg,jpeg,gif,png}', ['build-img']);
    gulp.watch('./source/svg/**/*.svg', ['build-img']);

    gulp.watch('./source/templates/*.html', ['build-templates', 'build-js']);
});

gulp.task('build', function(callback) {
    return runSequence('build-templates', 'build-js', 'build-img', 'build-css', callback);
});

gulp.task('clean', function() {
    return gulp.src(['dist/*', 'temp/*'], { read: false }).pipe(clean());
});

gulp.task('connect', function() {
    connect.server({
        root: __dirname + '/' + (config.root || defaultConfig.root),
        port: config.port || defaultConfig.port
    });
});

gulp.task('build-templates', function() {
    var minify = require('html-minifier').minify;

    return (
        gulp.src('source/templates/*.html')
            .pipe(handlebars())
            .pipe(defineModule('plain'))
            .pipe(declare({
                namespace: 'makeupTemplates',
                processContent: function(content, filepath) {
                    return minify(content, {
                        removeComments: true,
                        collapseWhitespace: true,
                        conservativeCollapse: true,
                        removeEmptyAttributes: true
                    });
                }
            }))
            .pipe(concat('templates.js'))
            .pipe(gulp.dest('temp/'))
    );
});

gulp.task('jshint', function() {
    return (
        gulp.src([
            'source/js/main.js',
            'source/blocks/*/*.js'
        ])
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
    );
});

gulp.task('build-js', ['jshint'], function() {
    return (
        gulp.src([
                'bower_components/handlebars/handlebars.min.js',
                'bower_components/lodash/dist/lodash.min.js',
                'bower_components/jquery/dist/jquery.min.js',
                'bower_components/baron/baron.min.js',
                'bower_components/rader/rader.min.js',
                'temp/templates.js',
                'source/js/*.js',
                'source/blocks/*/*.js'
        ])
            .pipe(concat('makeup.js'))
            .pipe(headerfooter.header('(function(global) {'))
            .pipe(headerfooter.footer('    global.Makeup = Makeup;'))
            .pipe(headerfooter.footer('})(window);'))
            .pipe(buildOptions.release ? uglify() : gutil.noop())
            .pipe(gulp.dest('dist/'))
    );
});

gulp.task('build-img', function() {
    return (
        gulp.src(['source/images/**/*.{jpg,jpeg,gif,png,svg}',
                  '!source/images/**/_*'])
            .pipe(imagemin())
            .pipe(gulp.dest('dist/images/'))
    );
});

gulp.task('build-css', function() {
    return (
        gulp.src([
                'source/less/reset.less',
                'source/less/mixins.less',
                'source/less/common.less',
                'source/blocks/*/*.less'
            ])
            .pipe(concat('makeup.css'))
            .pipe(plumber())
            .pipe(less())
            .pipe(buildOptions.release ? csso() : gutil.noop())
            .pipe(gulp.dest('dist/'))
    );
});

var mocha = require('gulp-mocha'),

    mochaOptions = {
        globals: ['DEBUG'],
        reporter: 'landing'
    };

gulp.task('test', ['unit']);

gulp.task('unit', function() {
    return (
        gulp.src('test/*.spec.js', { read: false })
            .pipe(mocha(mochaOptions))
            .on('error', function() {
                gulp.emit('tl.fail', 'Unit tests failed!');
            })
    );
});
<commit_msg>Update Connect settings<commit_after>var gulp = require('gulp'),

    gutil = require('gulp-util'),
    clean = require('gulp-clean'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    less = require('gulp-less'),
    csso = require('gulp-csso'),
    imagemin = require('gulp-imagemin'),
    connect = require('gulp-connect'),
    handlebars = require('gulp-handlebars'),
    defineModule = require('gulp-define-module'),
    declare = require('gulp-declare'),
    jshint = require('gulp-jshint'),
    plumber = require('gulp-plumber'),
    headerfooter = require('gulp-headerfooter'),

    runSequence = require('run-sequence'),

    args = require('yargs').argv;

var config = require('./config.js'),

    defaultConfig = {
        port: 3000,
        root: '',
        hostname: '*'
    };

var buildOptions = {
        release: 'r' in args || 'release' in args
    };

gulp.task('default', function() {
    return gulp.start('dev');
});

gulp.task('d', ['dev']);

gulp.task('dev', ['build'], function(callback) {
    return runSequence('build', 'connect', 'watch', callback);
});

gulp.task('watch', function(callback) {
    gulp.watch('./source/blocks/**/*.less', ['build-css']);
    gulp.watch('./source/less/**/*.less', ['build-css']);

    gulp.watch('./source/blocks/**/*.js', ['build-js']);
    gulp.watch('./source/js/**/*.js', ['build-js']);

    gulp.watch('./source/images/**/*.{jpg,jpeg,gif,png}', ['build-img']);
    gulp.watch('./source/svg/**/*.svg', ['build-img']);

    gulp.watch('./source/templates/*.html', ['build-templates', 'build-js']);
});

gulp.task('build', function(callback) {
    return runSequence('build-templates', 'build-js', 'build-img', 'build-css', callback);
});

gulp.task('clean', function() {
    return gulp.src(['dist/*', 'temp/*'], { read: false }).pipe(clean());
});

gulp.task('connect', function() {
    connect.server({
        root: __dirname + '/' + (config.root || defaultConfig.root),
        port: config.port || defaultConfig.port
    });
});

gulp.task('build-templates', function() {
    var minify = require('html-minifier').minify;

    return (
        gulp.src('source/templates/*.html')
            .pipe(handlebars())
            .pipe(defineModule('plain'))
            .pipe(declare({
                namespace: 'makeupTemplates',
                processContent: function(content, filepath) {
                    return minify(content, {
                        removeComments: true,
                        collapseWhitespace: true,
                        conservativeCollapse: true,
                        removeEmptyAttributes: true
                    });
                }
            }))
            .pipe(concat('templates.js'))
            .pipe(gulp.dest('temp/'))
    );
});

gulp.task('jshint', function() {
    return (
        gulp.src([
            'source/js/main.js',
            'source/blocks/*/*.js'
        ])
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
    );
});

gulp.task('build-js', ['jshint'], function() {
    return (
        gulp.src([
                'bower_components/handlebars/handlebars.min.js',
                'bower_components/lodash/dist/lodash.min.js',
                'bower_components/jquery/dist/jquery.min.js',
                'bower_components/baron/baron.min.js',
                'bower_components/rader/rader.min.js',
                'temp/templates.js',
                'source/js/*.js',
                'source/blocks/*/*.js'
        ])
            .pipe(concat('makeup.js'))
            .pipe(headerfooter.header('(function(global) {'))
            .pipe(headerfooter.footer('    global.Makeup = Makeup;'))
            .pipe(headerfooter.footer('})(window);'))
            .pipe(buildOptions.release ? uglify() : gutil.noop())
            .pipe(gulp.dest('dist/'))
    );
});

gulp.task('build-img', function() {
    return (
        gulp.src(['source/images/**/*.{jpg,jpeg,gif,png,svg}',
                  '!source/images/**/_*'])
            .pipe(imagemin())
            .pipe(gulp.dest('dist/images/'))
    );
});

gulp.task('build-css', function() {
    return (
        gulp.src([
                'source/less/reset.less',
                'source/less/mixins.less',
                'source/less/common.less',
                'source/blocks/*/*.less'
            ])
            .pipe(concat('makeup.css'))
            .pipe(plumber())
            .pipe(less())
            .pipe(buildOptions.release ? csso() : gutil.noop())
            .pipe(gulp.dest('dist/'))
    );
});

var mocha = require('gulp-mocha'),

    mochaOptions = {
        globals: ['DEBUG'],
        reporter: 'landing'
    };

gulp.task('test', ['unit']);

gulp.task('unit', function() {
    return (
        gulp.src('test/*.spec.js', { read: false })
            .pipe(mocha(mochaOptions))
            .on('error', function() {
                gulp.emit('tl.fail', 'Unit tests failed!');
            })
    );
});
<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/5/5.
 */

'use strict';

var path = require('path');
var gulp = require('gulp');
var rimraf = require('del');
var transport = require('gulp-cmd');
var uglify = require('gulp-uglify');
var css = require('gulp-css');
var plumber = require('gulp-plumber');
var colors = transport.colors;

// alias
var alias = {
  'import-style': '/online/loader/import-style',
  'jquery': 'base/jquery/1.11.2/jquery',
  'base': 'base/base/1.2.0/base',
  'class': 'base/class/1.2.0/class',
  'events': 'base/events/1.2.0/events',
  'widget': 'base/widget/1.2.0/widget',
  'template': 'base/template/3.0.3/template',
  'templatable': 'base/templatable/0.10.0/templatable',
  'iframe-shim': 'util/iframe-shim/1.1.0/iframe-shim',
  'position': 'util/position/1.1.0/position',
  'messenger': 'util/messenger/2.1.0/messenger',
  'mask': 'common/overlay/1.2.0/mask',
  'overlay': 'common/overlay/1.2.0/overlay',
  'dialog': 'common/dialog/1.5.1/dialog',
  'confirmbox': 'common/dialog/1.5.1/confirmbox'
};

var startTime = Date.now();

// complete callback
function complete(){
  var now = new Date();

  console.log(
    '  %s [%s] build complete ... %s%s',
    colors.cyan.bold('gulp-cmd'),
    now.toLocaleString(),
    colors.green(now - startTime),
    colors.cyan('ms')
  );
}

// clean task
gulp.task('clean', function (callback){
  rimraf('online', callback);
});

// runtime task
gulp.task('runtime', ['clean'], function (){
  gulp.src('assets/loader/**/*.js', { base: 'assets' })
    .pipe(uglify())
    .pipe(gulp.dest('online'));

  gulp.src('assets/?(loader|images)/**/*.!(js)', { base: 'assets' })
    .pipe(gulp.dest('online'));
});

// online task
gulp.task('online', ['runtime'], function (){
  // all js
  gulp.src('assets/js/**/*.js', { base: 'assets/js' })
    .pipe(transport({
      alias: alias,
      ignore: ['jquery'],
      include: function (id){
        return id.indexOf('view') === 0 ? 'all' : 'relative';
      },
      css: {
        onpath: function (path){
          return path.replace('assets/', 'online/')
        }
      }
    }))
    .pipe(uglify())
    .pipe(gulp.dest('online/js'))
    .on('end', complete);

  // other file
  gulp.src('assets/js/**/*.!(js|css|json|tpl|html)')
    .pipe(gulp.dest('online/js'));

  // css
  gulp.src('assets/css/**/*.*')
    .pipe(css({ compatibility: 'ie8' }))
    .pipe(gulp.dest('online/css'));
});

// develop task
gulp.task('default', ['runtime'], function (){
  // all file
  //gulp.src('assets/js/**/*.*', { base: 'assets/js' })
  //  .pipe(transport({
  //    alias: alias,
  //    include: 'self',
  //    css: {
  //      onpath: function (path){
  //        return path.replace('assets/', 'online/')
  //      }
  //    }
  //  }))
  //  .pipe(gulp.dest('online/js'))
  //  .on('end', complete);

  gulp.src('assets/css/**/*.*', { base: 'assets' })
    .pipe(css({ compress: true }))
    .pipe(gulp.dest('online'));
});

// develop watch task
gulp.task('watch', ['default'], function (){
  var base = path.join(process.cwd(), 'assets');

  // watch all file
  gulp.watch('assets/js/**/*.*', function (e){
    if (e.type === 'deleted') {
      rimraf(path.resolve('online', path.relative(base, e.path)));
    } else {
      startTime = Date.now();

      gulp.src(e.path, { base: 'assets/js' })
        .pipe(plumber())
        .pipe(transport({
          alias: alias,
          include: 'self',
          cache: false,
          css: {
            onpath: function (path){
              return path.replace('assets/', 'online/')
            }
          }
        }))
        .pipe(gulp.dest('online/js'))
        .on('end', complete);
    }
  });

  // watch all file
  gulp.watch('assets/?(images|loader|css)/**/*.*', function (e){
    if (e.type === 'deleted') {
      rimraf(path.resolve('online', path.relative(base, e.path)));
    } else {
      startTime = Date.now();

      gulp.src(e.path, { base: 'assets' })
        .pipe(plumber())
        .pipe(gulp.dest('online'))
        .on('end', complete);
    }
  });
});
<commit_msg>add source<commit_after>/**
 * Created by nuintun on 2015/5/5.
 */

'use strict';

var path = require('path');
var gulp = require('gulp');
var rimraf = require('del');
var transport = require('gulp-cmd');
var uglify = require('gulp-uglify');
var css = require('gulp-css');
var plumber = require('gulp-plumber');
var colors = transport.colors;

// alias
var alias = {
  'import-style': '/online/loader/import-style',
  'jquery': 'base/jquery/1.11.2/jquery',
  'base': 'base/base/1.2.0/base',
  'class': 'base/class/1.2.0/class',
  'events': 'base/events/1.2.0/events',
  'widget': 'base/widget/1.2.0/widget',
  'template': 'base/template/3.0.3/template',
  'templatable': 'base/templatable/0.10.0/templatable',
  'iframe-shim': 'util/iframe-shim/1.1.0/iframe-shim',
  'position': 'util/position/1.1.0/position',
  'messenger': 'util/messenger/2.1.0/messenger',
  'mask': 'common/overlay/1.2.0/mask',
  'overlay': 'common/overlay/1.2.0/overlay',
  'dialog': 'common/dialog/1.5.1/dialog',
  'confirmbox': 'common/dialog/1.5.1/confirmbox'
};

var startTime = Date.now();

// complete callback
function complete(){
  var now = new Date();

  console.log(
    '  %s [%s] build complete ... %s%s',
    colors.cyan.bold('gulp-cmd'),
    now.toLocaleString(),
    colors.green(now - startTime),
    colors.cyan('ms')
  );
}

// clean task
gulp.task('clean', function (callback){
  rimraf('online', callback);
});

// runtime task
gulp.task('runtime', ['clean'], function (){
  gulp.src('assets/loader/**/*.js', { base: 'assets' })
    .pipe(uglify())
    .pipe(gulp.dest('online'));

  gulp.src('assets/?(loader|images)/**/*.!(js)', { base: 'assets' })
    .pipe(gulp.dest('online'));
});

// online task
gulp.task('online', ['runtime'], function (){
  // all js
  gulp.src('assets/js/**/*.js', { base: 'assets/js' })
    .pipe(transport({
      alias: alias,
      ignore: ['jquery'],
      include: function (id){
        return id.indexOf('view') === 0 ? 'all' : 'relative';
      },
      css: {
        onpath: function (path){
          return path.replace('assets/', 'online/')
        }
      }
    }))
    .pipe(uglify())
    .pipe(gulp.dest('online/js'))
    .on('end', complete);

  // other file
  gulp.src('assets/js/**/*.!(js|css|json|tpl|html)')
    .pipe(gulp.dest('online/js'));

  // css
  gulp.src('assets/css/**/*.*')
    .pipe(css({ compatibility: 'ie8' }))
    .pipe(gulp.dest('online/css'));
});

// develop task
gulp.task('default', ['runtime'], function (){
  // all file
  gulp.src('assets/js/**/*.*', { base: 'assets/js' })
    .pipe(transport({
      alias: alias,
      include: 'self',
      css: {
        onpath: function (path){
          return path.replace('assets/', 'online/')
        }
      }
    }))
    .pipe(gulp.dest('online/js'))
    .on('end', complete);

  gulp.src('assets/css/**/*.*', { base: 'assets' })
    .pipe(css({ compress: true }))
    .pipe(gulp.dest('online'));
});

// develop watch task
gulp.task('watch', ['default'], function (){
  var base = path.join(process.cwd(), 'assets');

  // watch all file
  gulp.watch('assets/js/**/*.*', function (e){
    if (e.type === 'deleted') {
      rimraf(path.resolve('online', path.relative(base, e.path)));
    } else {
      startTime = Date.now();

      gulp.src(e.path, { base: 'assets/js' })
        .pipe(plumber())
        .pipe(transport({
          alias: alias,
          include: 'self',
          cache: false,
          css: {
            onpath: function (path){
              return path.replace('assets/', 'online/')
            }
          }
        }))
        .pipe(gulp.dest('online/js'))
        .on('end', complete);
    }
  });

  // watch all file
  gulp.watch('assets/?(images|loader|css)/**/*.*', function (e){
    if (e.type === 'deleted') {
      rimraf(path.resolve('online', path.relative(base, e.path)));
    } else {
      startTime = Date.now();

      gulp.src(e.path, { base: 'assets' })
        .pipe(plumber())
        .pipe(gulp.dest('online'))
        .on('end', complete);
    }
  });
});
<|endoftext|>


<commit_before>'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
const runSequence = require('gulp4-run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/main.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

gulp.task('js', function() {
  return gulp.src([
    'app/scripts/particles.js',
    'app/scripts/typed.min.js',
    'app/scripts/*.js'
    ])
    .pipe($.uglify())
    .pipe($.concat('scripts.min.js'))
    .pipe(gulp.dest('.tmp/scripts'))
    .pipe(gulp.dest('dist/scripts'))
    .pipe($.size({title: 'js'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
    'app/styles/**/*.css',
    'app/styles/*.scss'
  ])
    .pipe($.changed('styles', {extension: '.scss'}))
    .pipe($.sass({
      precision: 10,
      onError: console.error.bind(console, 'Sass error:')
    }))

    .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
    .pipe($.cleanCss())
    // Concatenate And Minify Styles
    // .pipe($.if('*.css', $.csso()))
    .pipe($.concat('styles.min.css'))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  // var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe($.useref({searchPath: '{.tmp,app}'}))
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe($.useref())
    // Update Production Style Guide Paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Watch Files For Changes & Reload
gulp.task('serve', gulp.series('styles', 'js', function () {
  browserSync({
    notify: false,
    // Customize the BrowserSync console logging prefix
    logPrefix: 'WSK',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint', 'js', reload]);
  gulp.watch(['app/images/**/*'], reload);
}));

// Build Production Files, the Default Task
gulp.task('default', gulp.series('clean', function (cb) {
  // runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'js', 'copy'], cb);
  runSequence('styles', ['jshint', 'html', 'fonts', 'js', 'copy'], cb);
}));

// Build and serve the output from the dist build
gulp.task('serve:dist', gulp.series('default', function () {
  browserSync({
    notify: false,
    logPrefix: 'WSK',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist'
  });
}));

// Run PageSpeed Insights
gulp.task('pagespeed', function (cb) {
  // Update the below URL to the public URL of your site
  pagespeed.output('example.com', {
    strategy: 'mobile',
    // By default we use the PageSpeed Insights free (no API key) tier.
    // Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
    // key: 'YOUR_API_KEY'
  }, cb);
});

// Load custom tasks from the `tasks` directory
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }FF
<commit_msg>fixing merge conflicts<commit_after>'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
const runSequence = require('gulp4-run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/main.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

gulp.task('js', function() {
  return gulp.src([
    'app/scripts/particles.js',
    'app/scripts/typed.min.js',
    'app/scripts/*.js'
    ])
    .pipe($.uglify())
    .pipe($.concat('scripts.min.js'))
    .pipe(gulp.dest('.tmp/scripts'))
    .pipe(gulp.dest('dist/scripts'))
    .pipe($.size({title: 'js'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
    'app/styles/**/*.css',
    'app/styles/*.scss'
  ])
    .pipe($.changed('styles', {extension: '.scss'}))
    .pipe($.sass({
      precision: 10,
      onError: console.error.bind(console, 'Sass error:')
    }))

    .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
    .pipe($.cleanCss())
    // Concatenate And Minify Styles
    // .pipe($.if('*.css', $.csso()))
    .pipe($.concat('styles.min.css'))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  // var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe($.useref({searchPath: '{.tmp,app}'}))
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe($.useref())
    // Update Production Style Guide Paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Watch Files For Changes & Reload
gulp.task('serve', gulp.series('styles', 'js', function () {
  browserSync({
    notify: false,
    // Customize the BrowserSync console logging prefix
    logPrefix: 'WSK',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint', 'js', reload]);
  gulp.watch(['app/images/**/*'], reload);
}));

// Build Production Files, the Default Task
gulp.task('default', gulp.series('clean', function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'js', 'copy'], cb);
  // runSequence('styles', ['jshint', 'html', 'fonts', 'js', 'copy'], cb);
}));

// Build and serve the output from the dist build
gulp.task('serve:dist', gulp.series('default', function () {
  browserSync({
    notify: false,
    logPrefix: 'WSK',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist'
  });
}));

// Run PageSpeed Insights
gulp.task('pagespeed', function (cb) {
  // Update the below URL to the public URL of your site
  pagespeed.output('example.com', {
    strategy: 'mobile',
    // By default we use the PageSpeed Insights free (no API key) tier.
    // Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
    // key: 'YOUR_API_KEY'
  }, cb);
});

// Load custom tasks from the `tasks` directory
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }FF
<|endoftext|>


<commit_before>"use strict";

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

var gulp = require('gulp'),
    path = require('path'),
    mochaStream = require('spawn-mocha-parallel').mochaStream,
    jshint = require('gulp-jshint'),
    jshintStylish = require('jshint-stylish'),
    jscs = require('gulp-jscs'),
    Q = require('q'),
    runSequence = Q.denodeify(require('run-sequence')),
    cp = require('child_process'),
    spawn = cp.spawn,
    exec = Q.denodeify(cp.exec),
    stream = require('stream'),
    fs = require('fs'),
    split = require('split'),
    os = require('os'),
    _ = require('underscore'),
    through = require('through'),
    promisePipe = require("promisepipe"),
    assert = require('assert'),
    splitArray = require('./test/helpers/split-array');

var childProcs = [];

function newMochaOpts() {
  return {
    flags: {
      u: 'bdd-with-opts',
      R: process.env.MOCHA_REPORTER || 'nyan',
      'c': true
    },
    env: _.clone(process.env),
    bin: path.join(__dirname,  'node_modules/.bin/mocha'),
    concurrency: 5
  };
}

var JS_SOURCES = ['*.js', 'bin/**/*.js', 'ci/**/*.js', 'new-ci/**/*.js', 'lib/**/*.js', 'test/**/*.js'];

gulp.task('jshint', function () {
  return gulp.src(JS_SOURCES)
    .pipe(jshint())
    .pipe(jshint.reporter(jshintStylish))
    .pipe(jshint.reporter('fail'));
});

gulp.task('jscs', function () {
  return gulp.src(JS_SOURCES)
    .pipe(jscs({configPath: __dirname + '/.jscsrc'}));
});

gulp.task('lint', ['jshint', 'jscs']);

gulp.task('test-unit', function () {
  var opts = newMochaOpts();
  var mocha = mochaStream(opts);
  return gulp.src('test/unit/**/*-specs.js', {read: false})
    .pipe(mocha)
    .on('error',  console.warn.bind(console));
});

function splitAndroidE2ETests() {
  var testFiles = [];
  var androidGroups = {};
  return promisePipe(
    gulp.src(['test/functional/common/**/*-specs.js', 'test/functional/android/**/*-specs.js',
              '!test/functional/android/chrome/**'], {read: false})
      .pipe(through(function (file) {
        testFiles.push(path.relative(file.cwd ,file.path));
      })).on('close', function () {
        testFiles.sort();
        androidGroups = splitArray(testFiles, argv.androidTestSplit);
      })).then(function () {
        assert(androidGroups.length === argv.androidTestSplit);
        return androidGroups;
      });
}

function killProcs() {
  _(childProcs).each(function (child) {
    try { child.kill(); } catch (err) {}
  });
}

gulp.task('kill-procs', function () {
  killProcs();
});

gulp.task('show-android-e2e-tests-split', function () {
  return splitAndroidE2ETests()
    .then(function (androidGroups) {
      console.log('Android groups:');
      _(androidGroups).each(function (group, i) {
        console.log(i + 1, '-->', group);
      });
    });
});

gulp.task('test-android-e2e', function () {
  return splitAndroidE2ETests().then(function (androidGroups) {
    var opts = newMochaOpts();
    opts.env.DEVICE='android';
    opts.env.VERBOSE=1;
    opts.flags.g = '@skip-android-all|@android-arm-only|@skip-ci';
    opts.flags.i = true;
    opts.concurrency = 1;
    opts.liveOutput = true;
    opts.liveOutputPrepend= 'client -> ';
    opts.fileOutput = 'client.log';
    var mocha = mochaStream(opts);
    var androidGroup = androidGroups[argv.androidTestGroup - 1];
    console.log('running tests for:' + androidGroup);
    return promisePipe( gulp.src(androidGroup, {read: false})
      .pipe(mocha)
      .on('error',  function (err) {
        killProcs();
        throw err;
      })
    );
  });
});

gulp.task('launch-appium', function () {
  var deferred = Q.defer();
  var out = new stream.PassThrough();

  out.pipe(split())
    .on('data', function (line) {
      if (line.match(/Appium REST http interface listener started/)) {
         deferred.resolve();
      }
      console.log('server -->', line);
    });
  out.pipe(fs.createWriteStream('appium.log'));
  var child = spawn("node", ['.'], { detached: false });
  childProcs.push(child);
  child.stdout.pipe(out);
  child.stderr.pipe(out);
  child.on('close', function () {
    deferred.reject('Something went wrong!');
  });
  return deferred.promise;
});

gulp.task('launch-emu', function () {
  var LOG_PREPEND= 'emu --> ';
  var deferred = Q.defer();

  var emuErrored = false;
  function waitForEmu() {
    var INIT_WAIT = 5000;
    var MAX_WAIT_MS = 120000;
    var POOL_MS = 2000;
    var startMs = Date.now();
    function _waitForEmu () {
      function retry() {
        if (emuErrored) {
          throw new Error('Emulator errored');
        }
        if (Date.now() - startMs > MAX_WAIT_MS) {
          throw new Error('Emulator did not show up');
        }
        console.log(LOG_PREPEND + 'Waiting for emu...');
        return Q.delay(POOL_MS).then(_waitForEmu);
      }
      return exec('adb shell getprop sys.boot_completed')
        .spread(function (stdout) {
          if (stdout && stdout.trim() === '1') {
            console.log(LOG_PREPEND + 'emulator started');
            return;
          }
          return retry();
        }, function (err) {
          if (err.toString().match(/device not found/)) {
            console.log(LOG_PREPEND + 'Device not found, it should be there, killing adb server.');
            return exec('adb kill-server').then(retry);
          }
          return retry();
        });
    }
    return Q.delay(INIT_WAIT).then(_waitForEmu)
      .then(function () {deferred.resolve();});
  }

  var out = new stream.PassThrough();
  out.pipe(split())
    .on('data', function (line) {
      console.log(LOG_PREPEND + line);
    });
  out.pipe(fs.createWriteStream('emulator.log'));
  var emuBin = os.platform() === 'linux' ? 'emulator64-x86' : 'emulator';
  var emuArgs = [
    '-avd', argv.avd,
    '-no-snapshot-load', '-no-snapshot-save',
    '-no-audio', '-netfast'
  ];
  if (os.platform() === 'linux') {
    emuArgs = emuArgs.concat([
      '-qemu', '-m', '512', '-enable-kvm'
    ]);
  }
  console.log(LOG_PREPEND + 'executing', emuBin, emuArgs.join(' '));
  var child = spawn(emuBin, emuArgs);
  childProcs.push(child);
  child.stdout.pipe(out);
  child.stderr.pipe(out);
  child.on('error', function (err) {
    emuErrored = true;
    deferred.reject(err);
  });
  child.on('close', function () {
    deferred.reject('Something went wrong!');
  });
  return Q.all([
    waitForEmu(),
    deferred.promise
  ]);
});

gulp.task('run-android-e2e', function () {
  return runSequence(['launch-emu', 'launch-appium'], 'test-android-e2e', 'kill-procs')
    .catch(function (err) {
      killProcs();
      throw err;
    });
});

gulp.task('default', function () {
  return runSequence('lint', 'test-unit');
});
<commit_msg>increasing emulator wait timeout<commit_after>"use strict";

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

var gulp = require('gulp'),
    path = require('path'),
    mochaStream = require('spawn-mocha-parallel').mochaStream,
    jshint = require('gulp-jshint'),
    jshintStylish = require('jshint-stylish'),
    jscs = require('gulp-jscs'),
    Q = require('q'),
    runSequence = Q.denodeify(require('run-sequence')),
    cp = require('child_process'),
    spawn = cp.spawn,
    exec = Q.denodeify(cp.exec),
    stream = require('stream'),
    fs = require('fs'),
    split = require('split'),
    os = require('os'),
    _ = require('underscore'),
    through = require('through'),
    promisePipe = require("promisepipe"),
    assert = require('assert'),
    splitArray = require('./test/helpers/split-array');

var childProcs = [];

function newMochaOpts() {
  return {
    flags: {
      u: 'bdd-with-opts',
      R: process.env.MOCHA_REPORTER || 'nyan',
      'c': true
    },
    env: _.clone(process.env),
    bin: path.join(__dirname,  'node_modules/.bin/mocha'),
    concurrency: 5
  };
}

var JS_SOURCES = ['*.js', 'bin/**/*.js', 'ci/**/*.js', 'new-ci/**/*.js', 'lib/**/*.js', 'test/**/*.js'];

gulp.task('jshint', function () {
  return gulp.src(JS_SOURCES)
    .pipe(jshint())
    .pipe(jshint.reporter(jshintStylish))
    .pipe(jshint.reporter('fail'));
});

gulp.task('jscs', function () {
  return gulp.src(JS_SOURCES)
    .pipe(jscs({configPath: __dirname + '/.jscsrc'}));
});

gulp.task('lint', ['jshint', 'jscs']);

gulp.task('test-unit', function () {
  var opts = newMochaOpts();
  var mocha = mochaStream(opts);
  return gulp.src('test/unit/**/*-specs.js', {read: false})
    .pipe(mocha)
    .on('error',  console.warn.bind(console));
});

function splitAndroidE2ETests() {
  var testFiles = [];
  var androidGroups = {};
  return promisePipe(
    gulp.src(['test/functional/common/**/*-specs.js', 'test/functional/android/**/*-specs.js',
              '!test/functional/android/chrome/**'], {read: false})
      .pipe(through(function (file) {
        testFiles.push(path.relative(file.cwd ,file.path));
      })).on('close', function () {
        testFiles.sort();
        androidGroups = splitArray(testFiles, argv.androidTestSplit);
      })).then(function () {
        assert(androidGroups.length === argv.androidTestSplit);
        return androidGroups;
      });
}

function killProcs() {
  _(childProcs).each(function (child) {
    try { child.kill(); } catch (err) {}
  });
}

gulp.task('kill-procs', function () {
  killProcs();
});

gulp.task('show-android-e2e-tests-split', function () {
  return splitAndroidE2ETests()
    .then(function (androidGroups) {
      console.log('Android groups:');
      _(androidGroups).each(function (group, i) {
        console.log(i + 1, '-->', group);
      });
    });
});

gulp.task('test-android-e2e', function () {
  return splitAndroidE2ETests().then(function (androidGroups) {
    var opts = newMochaOpts();
    opts.env.DEVICE='android';
    opts.env.VERBOSE=1;
    opts.flags.g = '@skip-android-all|@android-arm-only|@skip-ci';
    opts.flags.i = true;
    opts.concurrency = 1;
    opts.liveOutput = true;
    opts.liveOutputPrepend= 'client -> ';
    opts.fileOutput = 'client.log';
    var mocha = mochaStream(opts);
    var androidGroup = androidGroups[argv.androidTestGroup - 1];
    console.log('running tests for:' + androidGroup);
    return promisePipe( gulp.src(androidGroup, {read: false})
      .pipe(mocha)
      .on('error',  function (err) {
        killProcs();
        throw err;
      })
    );
  });
});

gulp.task('launch-appium', function () {
  var deferred = Q.defer();
  var out = new stream.PassThrough();

  out.pipe(split())
    .on('data', function (line) {
      if (line.match(/Appium REST http interface listener started/)) {
         deferred.resolve();
      }
      console.log('server -->', line);
    });
  out.pipe(fs.createWriteStream('appium.log'));
  var child = spawn("node", ['.'], { detached: false });
  childProcs.push(child);
  child.stdout.pipe(out);
  child.stderr.pipe(out);
  child.on('close', function () {
    deferred.reject('Something went wrong!');
  });
  return deferred.promise;
});

gulp.task('launch-emu', function () {
  var LOG_PREPEND= 'emu --> ';
  var deferred = Q.defer();

  var emuErrored = false;
  function waitForEmu() {
    var INIT_WAIT = 15000;
    var MAX_WAIT_MS = 180000;
    var POOL_MS = 5000;
    var startMs = Date.now();
    function _waitForEmu () {
      function retry() {
        if (emuErrored) {
          throw new Error('Emulator errored');
        }
        if (Date.now() - startMs > MAX_WAIT_MS) {
          throw new Error('Emulator did not show up');
        }
        console.log(LOG_PREPEND + 'Waiting for emu...');
        return Q.delay(POOL_MS).then(_waitForEmu);
      }
      return exec('adb shell getprop sys.boot_completed')
        .spread(function (stdout) {
          if (stdout && stdout.trim() === '1') {
            console.log(LOG_PREPEND + 'emulator started');
            return;
          }
          return retry();
        }, function (err) {
          if (err.toString().match(/device not found/)) {
            console.log(LOG_PREPEND + 'Device not found, it should be there, killing adb server.');
            return exec('adb kill-server').then(retry);
          }
          return retry();
        });
    }
    return Q.delay(INIT_WAIT).then(_waitForEmu)
      .then(function () {deferred.resolve();});
  }

  var out = new stream.PassThrough();
  out.pipe(split())
    .on('data', function (line) {
      console.log(LOG_PREPEND + line);
    });
  out.pipe(fs.createWriteStream('emulator.log'));
  var emuBin = os.platform() === 'linux' ? 'emulator64-x86' : 'emulator';
  var emuArgs = [
    '-avd', argv.avd,
    '-no-snapshot-load', '-no-snapshot-save',
    '-no-audio', '-netfast'
  ];
  if (os.platform() === 'linux') {
    emuArgs = emuArgs.concat([
      '-qemu', '-m', '512', '-enable-kvm'
    ]);
  }
  console.log(LOG_PREPEND + 'executing', emuBin, emuArgs.join(' '));
  var child = spawn(emuBin, emuArgs);
  childProcs.push(child);
  child.stdout.pipe(out);
  child.stderr.pipe(out);
  child.on('error', function (err) {
    emuErrored = true;
    deferred.reject(err);
  });
  child.on('close', function () {
    deferred.reject('Something went wrong!');
  });
  return Q.all([
    waitForEmu(),
    deferred.promise
  ]);
});

gulp.task('run-android-e2e', function () {
  return runSequence(['launch-emu', 'launch-appium'], 'test-android-e2e', 'kill-procs')
    .catch(function (err) {
      killProcs();
      throw err;
    });
});

gulp.task('default', function () {
  return runSequence('lint', 'test-unit');
});
<|endoftext|>


<commit_before>const babel = require('rollup-plugin-babel'),
  babili = require('gulp-babili'),
  buffer = require('vinyl-buffer'),
  esdoc = require('gulp-esdoc'),
  eslint = require('gulp-eslint'),
  filter = require('gulp-filter'),
  gulp = require('gulp'),
  jest = require('gulp-jest').default,
  lazypipe = require('lazypipe'),
  prettierOptions = require('./.prettier.js'),
  prettier = require('prettier'),
  rename = require('gulp-rename'),
  rollup = require('rollup-stream'),
  runSequence = require('run-sequence'),
  source = require('vinyl-source-stream'),
  sourcemaps = require('gulp-sourcemaps'),
  through = require('through2');

function process(inopts) {
  const opts = Object.assign(
    { entry: inopts.entry, sourceMap: true, format: inopts.format, plugins: [] },
    inopts.rollupOpts || {}
  );

  if (inopts.compile || typeof inopts.compile === 'undefined') {
    opts.plugins.push(
      babel({
        babelrc: false,
        presets: [['es2015', { modules: false }]],
        plugins: ['external-helpers']
      })
    );
  }

  return rollup(opts);
}

function processLib(opts) {
  return () => {
    opts.entry = './src/luxon.js';

    const dest = `./dist/${opts.dest || opts.format}`,
      // confession: I have no idea why piping to lazypipe works
      // after dest, but you can't pipe directly but it does so...
      minify = lazypipe()
        .pipe(filter, ['**/*.js'])
        .pipe(babili, { mangle: { keepClassNames: true } })
        .pipe(rename, { extname: '.min.js' })
        .pipe(sourcemaps.write, '.')
        .pipe(gulp.dest, dest);

    return process(opts)
      .pipe(source('luxon.js'))
      .pipe(buffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest(dest))
      .pipe(minify());
  };
}

function prettify(opts) {
  return through.obj((file, _, callback) => {
    const str = file.contents.toString(), data = prettier.format(str, opts);
    file.contents = new Buffer(data);
    callback(null, file);
  });
}

gulp.task('cjs', processLib({ format: 'cjs', rollupOpts: { external: ['intl'] } }));

gulp.task(
  'es6',
  processLib({
    format: 'es',
    dest: 'es6',
    rollupOpts: { external: ['intl'] },
    compile: false
  })
);

gulp.task(
  'amd',
  processLib({
    format: 'amd',
    rollupOpts: { moduleName: 'luxon', external: ['intl'] }
  })
);

gulp.task(
  'global-es6',
  processLib({
    format: 'iife',
    rollupOpts: { moduleName: 'luxon', globals: { intl: 'IntlPolyfill' }, external: ['intl'] },
    dest: 'global-es6',
    compile: false
  })
);

gulp.task(
  'global',
  processLib({
    format: 'iife',
    rollupOpts: { moduleName: 'luxon', globals: { intl: 'IntlPolyfill' }, external: ['intl'] },
    dest: 'global'
  })
);

gulp.task('build', ['cjs', 'es6', 'amd', 'global', 'global-es6']);

gulp.task('test', ['cjs'], () => gulp.src('test').pipe(jest()));

const lintable = ['src/**/*.js', 'test/**/*.js', 'gulpfile.js', '.eslintrc.js', '.prettier.js'];

gulp.task('lint', ['format'], () =>
  gulp.src(lintable).pipe(eslint()).pipe(eslint.format()).pipe(eslint.failAfterError())
);

gulp.task('format', () =>
  gulp.src(lintable, { base: './' }).pipe(prettify(prettierOptions)).pipe(gulp.dest('./'))
);

gulp.task('docs', () => gulp.src('./src').pipe(esdoc({ destination: './docs' })));

gulp.task('default', ['lint', 'build', 'test', 'docs']);

gulp.task('default', cb => runSequence('lint', 'build', 'test', 'docs', cb));
<commit_msg>build before lint<commit_after>const babel = require('rollup-plugin-babel'),
  babili = require('gulp-babili'),
  buffer = require('vinyl-buffer'),
  esdoc = require('gulp-esdoc'),
  eslint = require('gulp-eslint'),
  filter = require('gulp-filter'),
  gulp = require('gulp'),
  jest = require('gulp-jest').default,
  lazypipe = require('lazypipe'),
  prettierOptions = require('./.prettier.js'),
  prettier = require('prettier'),
  rename = require('gulp-rename'),
  rollup = require('rollup-stream'),
  runSequence = require('run-sequence'),
  source = require('vinyl-source-stream'),
  sourcemaps = require('gulp-sourcemaps'),
  through = require('through2');

function process(inopts) {
  const opts = Object.assign(
    { entry: inopts.entry, sourceMap: true, format: inopts.format, plugins: [] },
    inopts.rollupOpts || {}
  );

  if (inopts.compile || typeof inopts.compile === 'undefined') {
    opts.plugins.push(
      babel({
        babelrc: false,
        presets: [['es2015', { modules: false }]],
        plugins: ['external-helpers']
      })
    );
  }

  return rollup(opts);
}

function processLib(opts) {
  return () => {
    opts.entry = './src/luxon.js';

    const dest = `./dist/${opts.dest || opts.format}`,
      // confession: I have no idea why piping to lazypipe works
      // after dest, but you can't pipe directly but it does so...
      minify = lazypipe()
        .pipe(filter, ['**/*.js'])
        .pipe(babili, { mangle: { keepClassNames: true } })
        .pipe(rename, { extname: '.min.js' })
        .pipe(sourcemaps.write, '.')
        .pipe(gulp.dest, dest);

    return process(opts)
      .pipe(source('luxon.js'))
      .pipe(buffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest(dest))
      .pipe(minify());
  };
}

function prettify(opts) {
  return through.obj((file, _, callback) => {
    const str = file.contents.toString(), data = prettier.format(str, opts);
    file.contents = new Buffer(data);
    callback(null, file);
  });
}

gulp.task('cjs', processLib({ format: 'cjs', rollupOpts: { external: ['intl'] } }));

gulp.task(
  'es6',
  processLib({
    format: 'es',
    dest: 'es6',
    rollupOpts: { external: ['intl'] },
    compile: false
  })
);

gulp.task(
  'amd',
  processLib({
    format: 'amd',
    rollupOpts: { moduleName: 'luxon', external: ['intl'] }
  })
);

gulp.task(
  'global-es6',
  processLib({
    format: 'iife',
    rollupOpts: { moduleName: 'luxon', globals: { intl: 'IntlPolyfill' }, external: ['intl'] },
    dest: 'global-es6',
    compile: false
  })
);

gulp.task(
  'global',
  processLib({
    format: 'iife',
    rollupOpts: { moduleName: 'luxon', globals: { intl: 'IntlPolyfill' }, external: ['intl'] },
    dest: 'global'
  })
);

gulp.task('build', ['cjs', 'es6', 'amd', 'global', 'global-es6']);

gulp.task('test', ['cjs'], () => gulp.src('test').pipe(jest()));

const lintable = ['src/**/*.js', 'test/**/*.js', 'gulpfile.js', '.eslintrc.js', '.prettier.js'];

gulp.task('lint', ['format'], () =>
  gulp.src(lintable).pipe(eslint()).pipe(eslint.format()).pipe(eslint.failAfterError())
);

gulp.task('format', () =>
  gulp.src(lintable, { base: './' }).pipe(prettify(prettierOptions)).pipe(gulp.dest('./'))
);

gulp.task('docs', () => gulp.src('./src').pipe(esdoc({ destination: './docs' })));

// build first so the test deps work
gulp.task('default', cb => runSequence('build', 'lint', 'test', 'docs', cb));
<|endoftext|>


<commit_before>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var historyApiFallback = require('connect-history-api-fallback');
var packageJson = require('./package.json');
var crypto = require('crypto');
var config = require('./config');
var taskDir = './gulp-tasks/';

var styleTask = function (stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(config.autoprefixer.browsers))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.if('*.css', $.cssmin()))
    .pipe(gulp.dest('dist/' + stylesPath))
    .pipe($.size({title: stylesPath}));
};

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function () {
  return styleTask('elements', ['**/*.css']);
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src([
      'app/scripts/**/*.js',
      'app/elements/**/*.js',
      'app/elements/**/*.html'
    ])
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint.extract()) // Extract JS from .html files
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/cache-config.json'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));

  var bower = gulp.src([
    'bower_components/**/*.{css,html,js}',
    '!bower_components/**/index.html',
    '!bower_components/**/{demo,test}/**/*'
  ]).pipe(gulp.dest('dist/bower_components'));

  var elements = gulp.src(['app/elements/**/*.html'])
    .pipe(gulp.dest('dist/elements'));

  var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
    .pipe(gulp.dest('dist/elements/bootstrap'));

  var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
    .pipe(gulp.dest('dist/sw-toolbox'));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest('dist/elements'));

  return merge(app, bower, elements, vulcanized, swBootstrap, swToolbox)
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: ['.tmp', 'app', 'dist']});

  return gulp.src(['app/**/*.html', '!app/{elements,test}/**/*.html'])
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace('elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.cssmin()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({
      empty: true,  // KEEP empty attributes
      loose: true,  // KEEP one whitespace
      quotes: true, // KEEP arbitrary quotes
      spare: true   // KEEP redundant attributes
    })))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Vulcanize imports
gulp.task('vulcanize', function () {
  return gulp.src('dist/elements/elements.vulcanized.html')
    .pipe($.vulcanize({
      stripComments: true,
      inlineCss: true,
      inlineScripts: true
    }))
    // Split inline scripts from an HTML file for CSP compliance
    .pipe($.crisper())
    // Minify elements.vulcanized.html
    // https://github.com/PolymerLabs/polybuild/issues/3
    .pipe($.if('*.html', $.htmlmin({
      customAttrAssign: [
        {source:'\\$='}
      ],
      customAttrSurround: [
        [ {source: '\\({\\{'}, {source: '\\}\\}'} ],
        [ {source: '\\[\\['}, {source: '\\]\\]'}  ]
      ],
      removeComments: true,
      collapseWhitespace: true
    })))
    // Remove newline characters
    .pipe($.if('*.html', $.replace(/[\n]/g, '')))
    // Remove 2 or more spaces from CSS
    // (single spaces can be syntactically significant)
    .pipe($.if('*.html', $.replace(/ {2,}/g, '')))
    // Remove CSS comments
    .pipe($.if('*.html', $.stripCssComments({preserve: false})))
    // Minify elements.vulcanized.js
    .pipe($.if('*.js', $.uglify()))
    .pipe(gulp.dest('dist/elements'))
    .pipe($.size({title: 'vulcanize'}));
});

// Generate config data for the <sw-precache-cache> element.
// This include a list of files that should be precached, as well as a (hopefully unique) cache
// id that ensure that multiple PSK projects don't share the same Cache Storage.
gulp.task('cache-config', function (callback) {
  var dir = 'dist';
  var config = {
    cacheId: packageJson.name || path.basename(__dirname),
    disabled: false
  };

  glob('{elements,scripts,styles}/**/*.*', {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      files.push('index.html', './', 'bower_components/webcomponentsjs/webcomponents-lite.min.js');
      config.precache = files;

      var md5 = crypto.createHash('md5');
      md5.update(JSON.stringify(config.precache));
      config.precacheFingerprint = md5.digest('hex');

      var configPath = path.join(dir, 'cache-config.json');
      fs.writeFile(configPath, JSON.stringify(config), callback);
    }
  });
});

// Clean Output Directory
gulp.task('clean', function (cb) {
  del(['.tmp', 'dist', 'deploy'], cb);
});

// Watch Files For Changes & Reload
gulp.task('serve', ['styles', 'elements', 'images'], function () {
  browserSync({
    browser: config.browserSync.browser,
    https: config.browserSync.https,
    notify: config.browserSync.notify,
    port: config.browserSync.port,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    server: {
      baseDir: ['.tmp', 'app'],
      middleware: [ historyApiFallback() ],
      routes: {
        '/bower_components': 'bower_components'
      }
    },
    ui: {
      port: config.browserSync.ui.port
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/{scripts,elements}/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    browser: config.browserSync.browser,
    https: config.browserSync.https,
    notify: config.browserSync.notify,
    port: config.browserSync.port,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    server: 'dist',
    middleware: [ historyApiFallback() ],
    ui: {
      port: config.browserSync.ui.port
    }
  });
});

// Clean dist directory
gulp.task('clean-dist', require(taskDir + 'clean-dist')(del));

// Disable hashbang in routing
gulp.task('disable-hashbang',
  require(taskDir + 'disable-hashbang')($, config, gulp));

// Fetch newest Google analytics.js and replace link to analytics.js
// https://www.google-analytics.com/analytics.js have only 2 hours cache
gulp.task('fetch-newest-analytics',
  require(taskDir + 'fetch-newest-analytics')($, gulp, merge));

// Fix path to sw-toolbox.js
gulp.task('fix-path-sw-toolbox',
  require(taskDir + 'fix-path-sw-toolbox')($, gulp));

// Minify JavaScript in dist directory
gulp.task('minify-dist', require(taskDir + 'minify-dist')($, gulp, merge));

// Static asset revisioning by appending content hash to filenames
gulp.task('revision', require(taskDir + 'revision')($, gulp));

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['jshint', 'images', 'fonts', 'html', 'fetch-newest-analytics'],
    'vulcanize',
    ['clean-dist', 'minify-dist'],
    'cache-config',
    cb);
});

// Deploy Tasks
// ------------

// Pre-deploy tasks
gulp.task('pre-deploy', function(cb) {
  runSequence(
    'default',
    ['disable-hashbang', 'fix-path-sw-toolbox'],
    'revision',
    cb);
});

// Deploy to development environment
gulp.task('deploy:dev', ['pre-deploy'],
  require(taskDir + 'deploy')($, config, gulp, 'development'));

// Deploy to staging environment
gulp.task('deploy:staging', ['pre-deploy'],
  require(taskDir + 'deploy')($, config, gulp, 'staging'));

// Deploy to production environment
gulp.task('deploy:prod', ['pre-deploy'],
  require(taskDir + 'deploy')($, config, gulp, 'production'));

// Promote the staging version to the production environment
gulp.task('deploy:promote',
  require(taskDir + 'deploy')($, config, gulp, 'promote'));

// Tool Tasks
// ----------

// Run PageSpeed Insights
gulp.task('pagespeed', require(taskDir + 'pagespeed')(config));

// Test Tasks
// ----------

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
require('web-component-tester').gulp.init(gulp);

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<commit_msg>Rename deploy:staging task to deploy:stag<commit_after>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var historyApiFallback = require('connect-history-api-fallback');
var packageJson = require('./package.json');
var crypto = require('crypto');
var config = require('./config');
var taskDir = './gulp-tasks/';

var styleTask = function (stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(config.autoprefixer.browsers))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.if('*.css', $.cssmin()))
    .pipe(gulp.dest('dist/' + stylesPath))
    .pipe($.size({title: stylesPath}));
};

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function () {
  return styleTask('elements', ['**/*.css']);
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src([
      'app/scripts/**/*.js',
      'app/elements/**/*.js',
      'app/elements/**/*.html'
    ])
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint.extract()) // Extract JS from .html files
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/cache-config.json'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));

  var bower = gulp.src([
    'bower_components/**/*.{css,html,js}',
    '!bower_components/**/index.html',
    '!bower_components/**/{demo,test}/**/*'
  ]).pipe(gulp.dest('dist/bower_components'));

  var elements = gulp.src(['app/elements/**/*.html'])
    .pipe(gulp.dest('dist/elements'));

  var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
    .pipe(gulp.dest('dist/elements/bootstrap'));

  var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
    .pipe(gulp.dest('dist/sw-toolbox'));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest('dist/elements'));

  return merge(app, bower, elements, vulcanized, swBootstrap, swToolbox)
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: ['.tmp', 'app', 'dist']});

  return gulp.src(['app/**/*.html', '!app/{elements,test}/**/*.html'])
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace('elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.cssmin()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({
      empty: true,  // KEEP empty attributes
      loose: true,  // KEEP one whitespace
      quotes: true, // KEEP arbitrary quotes
      spare: true   // KEEP redundant attributes
    })))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Vulcanize imports
gulp.task('vulcanize', function () {
  return gulp.src('dist/elements/elements.vulcanized.html')
    .pipe($.vulcanize({
      stripComments: true,
      inlineCss: true,
      inlineScripts: true
    }))
    // Split inline scripts from an HTML file for CSP compliance
    .pipe($.crisper())
    // Minify elements.vulcanized.html
    // https://github.com/PolymerLabs/polybuild/issues/3
    .pipe($.if('*.html', $.htmlmin({
      customAttrAssign: [
        {source:'\\$='}
      ],
      customAttrSurround: [
        [ {source: '\\({\\{'}, {source: '\\}\\}'} ],
        [ {source: '\\[\\['}, {source: '\\]\\]'}  ]
      ],
      removeComments: true,
      collapseWhitespace: true
    })))
    // Remove newline characters
    .pipe($.if('*.html', $.replace(/[\n]/g, '')))
    // Remove 2 or more spaces from CSS
    // (single spaces can be syntactically significant)
    .pipe($.if('*.html', $.replace(/ {2,}/g, '')))
    // Remove CSS comments
    .pipe($.if('*.html', $.stripCssComments({preserve: false})))
    // Minify elements.vulcanized.js
    .pipe($.if('*.js', $.uglify()))
    .pipe(gulp.dest('dist/elements'))
    .pipe($.size({title: 'vulcanize'}));
});

// Generate config data for the <sw-precache-cache> element.
// This include a list of files that should be precached, as well as a (hopefully unique) cache
// id that ensure that multiple PSK projects don't share the same Cache Storage.
gulp.task('cache-config', function (callback) {
  var dir = 'dist';
  var config = {
    cacheId: packageJson.name || path.basename(__dirname),
    disabled: false
  };

  glob('{elements,scripts,styles}/**/*.*', {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      files.push('index.html', './', 'bower_components/webcomponentsjs/webcomponents-lite.min.js');
      config.precache = files;

      var md5 = crypto.createHash('md5');
      md5.update(JSON.stringify(config.precache));
      config.precacheFingerprint = md5.digest('hex');

      var configPath = path.join(dir, 'cache-config.json');
      fs.writeFile(configPath, JSON.stringify(config), callback);
    }
  });
});

// Clean Output Directory
gulp.task('clean', function (cb) {
  del(['.tmp', 'dist', 'deploy'], cb);
});

// Watch Files For Changes & Reload
gulp.task('serve', ['styles', 'elements', 'images'], function () {
  browserSync({
    browser: config.browserSync.browser,
    https: config.browserSync.https,
    notify: config.browserSync.notify,
    port: config.browserSync.port,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    server: {
      baseDir: ['.tmp', 'app'],
      middleware: [ historyApiFallback() ],
      routes: {
        '/bower_components': 'bower_components'
      }
    },
    ui: {
      port: config.browserSync.ui.port
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/{scripts,elements}/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    browser: config.browserSync.browser,
    https: config.browserSync.https,
    notify: config.browserSync.notify,
    port: config.browserSync.port,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    server: 'dist',
    middleware: [ historyApiFallback() ],
    ui: {
      port: config.browserSync.ui.port
    }
  });
});

// Clean dist directory
gulp.task('clean-dist', require(taskDir + 'clean-dist')(del));

// Disable hashbang in routing
gulp.task('disable-hashbang',
  require(taskDir + 'disable-hashbang')($, config, gulp));

// Fetch newest Google analytics.js and replace link to analytics.js
// https://www.google-analytics.com/analytics.js have only 2 hours cache
gulp.task('fetch-newest-analytics',
  require(taskDir + 'fetch-newest-analytics')($, gulp, merge));

// Fix path to sw-toolbox.js
gulp.task('fix-path-sw-toolbox',
  require(taskDir + 'fix-path-sw-toolbox')($, gulp));

// Minify JavaScript in dist directory
gulp.task('minify-dist', require(taskDir + 'minify-dist')($, gulp, merge));

// Static asset revisioning by appending content hash to filenames
gulp.task('revision', require(taskDir + 'revision')($, gulp));

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['jshint', 'images', 'fonts', 'html', 'fetch-newest-analytics'],
    'vulcanize',
    ['clean-dist', 'minify-dist'],
    'cache-config',
    cb);
});

// Deploy Tasks
// ------------

// Pre-deploy tasks
gulp.task('pre-deploy', function(cb) {
  runSequence(
    'default',
    ['disable-hashbang', 'fix-path-sw-toolbox'],
    'revision',
    cb);
});

// Deploy to development environment
gulp.task('deploy:dev', ['pre-deploy'],
  require(taskDir + 'deploy')($, config, gulp, 'development'));

// Deploy to staging environment
gulp.task('deploy:stag', ['pre-deploy'],
  require(taskDir + 'deploy')($, config, gulp, 'staging'));

// Deploy to production environment
gulp.task('deploy:prod', ['pre-deploy'],
  require(taskDir + 'deploy')($, config, gulp, 'production'));

// Promote the staging version to the production environment
gulp.task('deploy:promote',
  require(taskDir + 'deploy')($, config, gulp, 'promote'));

// Tool Tasks
// ----------

// Run PageSpeed Insights
gulp.task('pagespeed', require(taskDir + 'pagespeed')(config));

// Test Tasks
// ----------

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
require('web-component-tester').gulp.init(gulp);

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<|endoftext|>