<commit_before>// ## Setup
var _ = require('lodash');
var del = require("del");
var gulp = require("gulp");
var $ = require('gulp-load-plugins')();
var opn = require('opn');
var marked = require('marked');
var cheerio = require('cheerio');
// [Karma](http://karma-runner.github.io/) for running browser tests
// in [PhantomJS](http://phantomjs.org/).
var karma = require('karma').server;

// Load config for webpack target below.
// karma.conf.js uses the same configuration file.
var webpackConfig = require("./webpack.config.js");

// Custom template tags so cheerio doesn't reformat
// our template markup.
var TemplateOptions = {
  interpolate: /\[\[=([\s\S]+?)\]\]/g,
  escape:      /\[\[-([\s\S]+?)\]\]/g,
  evaluate:    /\[\[([\s\S]+?)\]\]/g
};

// [Karma](http://karma-runner.github.io/) needs a full path to the config file.
var KarmaConfig = require('path').join(__dirname, './karma.conf.js');

// Sources for generating `index.html`.
var IndexSources = [
  'index.js',
  'index.html',
  'webpack.config.js',
  'gulpfile.js',
  'karma.conf.js',
  'style.less',
  'bootstrap.config.less',
  'bootstrap.config.js'
];

// ## Helper Functions

// ### highlight
// Returns code with [google-code-prettify](https://code.google.com/p/google-code-prettify/)
// markup setup to use line numbers started at specified line. Used in both docco and
// doccoHtml to add prettify markup to the code sections of the docs.
var highlight = function (code, startLine) {
  html = '<?prettify';
  if (_.isNumber(startLine))
    html += ' linenums=' + startLine;
  html += '>
' + _.escape(code) + '
'
  return html;
};
// Setup marked to use our highlighter.
marked.setOptions({ highlight: highlight });

// ### doccoHtml

// Uses [cheerio](https://github.com/cheeriojs/cheerio) to do for html
// what we use docco for with other languages. Extracts out the comments
// and maintains the line numbers for
// [google-code-prettify](https://code.google.com/p/google-code-prettify/)
var doccoHtml = function (path, html, config) {
  var walk, $, docs = [], sections = [], marker = "";
  isValidComment = function (node) {
    return node.type === 'comment' && !String(node.nodeValue).match(/\[if\s+[^\]]+\]/);
  };
  walk = function () {
    if (isValidComment(this)) {
      docs.push(this.nodeValue);
      $(this).replaceWith($(marker));
    } else {
      $(this).contents().each(walk);
    }
  };
  $ = cheerio.load(html);
  $.root().contents().each(walk);
  var nextDoc = '', startLine = 1;
  _.forEach($.html().split(marker), function (htmlPart) {
    // Edge Case - First thing in html is a comment, we loose a line if that happens.
    if (htmlPart === '' && nextDoc === '')
      startLine++;
    else
      startLine += nextDoc.split("\n").length - 1;
    sections.push({
      docsHtml: marked(nextDoc),
      codeHtml: highlight(htmlPart, startLine),
      codeText: htmlPart
    });
    startLine += htmlPart.split("\n").length - 1;
    nextDoc = docs.shift() || '';
  });
  return sections;
};

// ### docco

// [docco](http://jashkenas.github.io/docco/) To parse out code/docs
// and [marked](https://github.com/chjj/marked) to format the docs.
// marked is manually applied because we are using
// [google-code-prettify](https://code.google.com/p/google-code-prettify/)
// to highlight code.
var docco = function (path, code, config) {
  if (/\.html$/.test(path)) {
    return doccoHtml(path, code, config);
  }
  if (!config) config = {};
  _.defaults(config, { languages: {} });

  var d = require('docco');
  var sections = d.parse(path, code, config);
  var startLine = 1;
  _.forEach(sections, function (section) {
    if (section.docsText !== '') {
      startLine += section.docsText.split("\n").length - 1;
    }
    section.codeHtml = highlight(section.codeText, startLine);
    startLine += section.codeText.split("\n").length - 1;
    section.docsHtml = marked(section.docsText);
  });
  return sections;
}

// ## Tasks

// ### task clean
// Cleans up dist directory using [del](https://github.com/sindresorhus/del).
gulp.task("clean", function (done) {
  del(["dist/*"], done);
});

// ### task index
// Build's the index file with documentation from [docco](http://jashkenas.github.io/docco/)
// with the `index.html` [lodash template](https://lodash.com/docs#template).
gulp.task("index", ["clean"], function (done) {
  var docs = [];
  gulp.src(IndexSources)
    .pipe($.tap(function (file) {
      docs.push({
        file: file,
        docco: docco(file.path, file.contents.toString()),
        id: _.uniqueId('file-')
      })}))
    // After we've created the `docs` array, build the template.
    .on('end', function () {
      gulp.src('index.html')
        .pipe($.template({ docs: docs }, TemplateOptions))
        .pipe(gulp.dest('dist'))
        .on('end', function () { done() })
    });
});

// ### task webpack
// Builds the main.js and any resources (bootstrap uses a few)
// into the dist directory. Uses [gulp-webpack](https://github.com/shama/gulp-webpack).
gulp.task("webpack", ["clean"], function () {
  return gulp.src("index.js")
    .pipe($.webpack(webpackConfig))
    .pipe(gulp.dest('dist'));
});

// ### task build
// Build `index.html` and `main.js`.
gulp.task("build", ["webpack", "index"]);

// ### task watch
// Build and serve `index.html` on localhost port 3000
// launching a browser with [opn](https://github.com/sindresorhus/opn) to view.
// If you have the [livereload](https://github.com/vohof/gulp-livereload)
// plugin for chrome installed it will also reload
// your browser when files in the dist directory change.
gulp.task("watch", ["build"], function () {
  $.livereload.listen();
  gulp.watch('dist/**/*').on('change', $.livereload.changed);
  gulp.watch(IndexSources, ['build']);
  opn("http://127.0.0.1:3000/");
  return $.serve('dist')();
});

// ### task deploy
// Deploy to Github pages. *UNTESTED*
gulp.task("deploy", function () {
  return gulp.src("dist/**/*")
    .pipe($.ghPages('git@github.com:bline/bootstrap-webpack-example.git'));
});

// ### task test
// Run tests in [Karma](http://karma-runner.github.io/) using [FantomJS](http://phantomjs.org/).
gulp.task("test", function (done) {
  karma.start({
    configFile: KarmaConfig,
    singleRun: true
  }, done);
});

// ### task default
// Run test by default.
gulp.task("default", ["test"]);

<commit_msg>build as dep of deploy.<commit_after>// ## Setup
var _ = require('lodash');
var del = require("del");
var gulp = require("gulp");
var $ = require('gulp-load-plugins')();
var opn = require('opn');
var marked = require('marked');
var cheerio = require('cheerio');
// [Karma](http://karma-runner.github.io/) for running browser tests
// in [PhantomJS](http://phantomjs.org/).
var karma = require('karma').server;

// Load config for webpack target below.
// karma.conf.js uses the same configuration file.
var webpackConfig = require("./webpack.config.js");

// Custom template tags so cheerio doesn't reformat
// our template markup.
var TemplateOptions = {
  interpolate: /\[\[=([\s\S]+?)\]\]/g,
  escape:      /\[\[-([\s\S]+?)\]\]/g,
  evaluate:    /\[\[([\s\S]+?)\]\]/g
};

// [Karma](http://karma-runner.github.io/) needs a full path to the config file.
var KarmaConfig = require('path').join(__dirname, './karma.conf.js');

// Sources for generating `index.html`.
var IndexSources = [
  'index.js',
  'index.html',
  'webpack.config.js',
  'gulpfile.js',
  'karma.conf.js',
  'style.less',
  'bootstrap.config.less',
  'bootstrap.config.js'
];

// ## Helper Functions

// ### highlight
// Returns code with [google-code-prettify](https://code.google.com/p/google-code-prettify/)
// markup setup to use line numbers started at specified line. Used in both docco and
// doccoHtml to add prettify markup to the code sections of the docs.
var highlight = function (code, startLine) {
  html = '<?prettify';
  if (_.isNumber(startLine))
    html += ' linenums=' + startLine;
  html += '>
' + _.escape(code) + '
'
  return html;
};
// Setup marked to use our highlighter.
marked.setOptions({ highlight: highlight });

// ### doccoHtml

// Uses [cheerio](https://github.com/cheeriojs/cheerio) to do for html
// what we use docco for with other languages. Extracts out the comments
// and maintains the line numbers for
// [google-code-prettify](https://code.google.com/p/google-code-prettify/)
var doccoHtml = function (path, html, config) {
  var walk, $, docs = [], sections = [], marker = "";
  isValidComment = function (node) {
    return node.type === 'comment' && !String(node.nodeValue).match(/\[if\s+[^\]]+\]/);
  };
  walk = function () {
    if (isValidComment(this)) {
      docs.push(this.nodeValue);
      $(this).replaceWith($(marker));
    } else {
      $(this).contents().each(walk);
    }
  };
  $ = cheerio.load(html);
  $.root().contents().each(walk);
  var nextDoc = '', startLine = 1;
  _.forEach($.html().split(marker), function (htmlPart) {
    // Edge Case - First thing in html is a comment, we loose a line if that happens.
    if (htmlPart === '' && nextDoc === '')
      startLine++;
    else
      startLine += nextDoc.split("\n").length - 1;
    sections.push({
      docsHtml: marked(nextDoc),
      codeHtml: highlight(htmlPart, startLine),
      codeText: htmlPart
    });
    startLine += htmlPart.split("\n").length - 1;
    nextDoc = docs.shift() || '';
  });
  return sections;
};

// ### docco

// [docco](http://jashkenas.github.io/docco/) To parse out code/docs
// and [marked](https://github.com/chjj/marked) to format the docs.
// marked is manually applied because we are using
// [google-code-prettify](https://code.google.com/p/google-code-prettify/)
// to highlight code.
var docco = function (path, code, config) {
  if (/\.html$/.test(path)) {
    return doccoHtml(path, code, config);
  }
  if (!config) config = {};
  _.defaults(config, { languages: {} });

  var d = require('docco');
  var sections = d.parse(path, code, config);
  var startLine = 1;
  _.forEach(sections, function (section) {
    if (section.docsText !== '') {
      startLine += section.docsText.split("\n").length - 1;
    }
    section.codeHtml = highlight(section.codeText, startLine);
    startLine += section.codeText.split("\n").length - 1;
    section.docsHtml = marked(section.docsText);
  });
  return sections;
}

// ## Tasks

// ### task clean
// Cleans up dist directory using [del](https://github.com/sindresorhus/del).
gulp.task("clean", function (done) {
  del(["dist/*"], done);
});

// ### task index
// Build's the index file with documentation from [docco](http://jashkenas.github.io/docco/)
// with the `index.html` [lodash template](https://lodash.com/docs#template).
gulp.task("index", ["clean"], function (done) {
  var docs = [];
  gulp.src(IndexSources)
    .pipe($.tap(function (file) {
      docs.push({
        file: file,
        docco: docco(file.path, file.contents.toString()),
        id: _.uniqueId('file-')
      })}))
    // After we've created the `docs` array, build the template.
    .on('end', function () {
      gulp.src('index.html')
        .pipe($.template({ docs: docs }, TemplateOptions))
        .pipe(gulp.dest('dist'))
        .on('end', function () { done() })
    });
});

// ### task webpack
// Builds the main.js and any resources (bootstrap uses a few)
// into the dist directory. Uses [gulp-webpack](https://github.com/shama/gulp-webpack).
gulp.task("webpack", ["clean"], function () {
  return gulp.src("index.js")
    .pipe($.webpack(webpackConfig))
    .pipe(gulp.dest('dist'));
});

// ### task build
// Build `index.html` and `main.js`.
gulp.task("build", ["webpack", "index"]);

// ### task watch
// Build and serve `index.html` on localhost port 3000
// launching a browser with [opn](https://github.com/sindresorhus/opn) to view.
// If you have the [livereload](https://github.com/vohof/gulp-livereload)
// plugin for chrome installed it will also reload
// your browser when files in the dist directory change.
gulp.task("watch", ["build"], function () {
  $.livereload.listen();
  gulp.watch('dist/**/*').on('change', $.livereload.changed);
  gulp.watch(IndexSources, ['build']);
  opn("http://127.0.0.1:3000/");
  return $.serve('dist')();
});

// ### task deploy
// Deploy to Github pages. *UNTESTED*
gulp.task("deploy", ['build'], function () {
  return gulp.src("dist/**/*")
    .pipe($.ghPages('git@github.com:bline/bootstrap-webpack-example.git'));
});

// ### task test
// Run tests in [Karma](http://karma-runner.github.io/) using [FantomJS](http://phantomjs.org/).
gulp.task("test", function (done) {
  karma.start({
    configFile: KarmaConfig,
    singleRun: true
  }, done);
});

// ### task default
// Run test by default.
gulp.task("default", ["test"]);

<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var del = require('del');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var plugins = require('gulp-load-plugins')();
var $ = require('gulp-load-plugins')({ pattern: ['gulp-*'] });
var getBundleName = function () {
  var version = require('./package.json').version;
  var name = require('./package.json').name;
  return version + '.' + name + '.' + 'min';
};

gulp.task('browser-sync',  [,  function() {
  browserSync({
    server: {
      baseDir: './',
      directory: true
    },
    open: false
  });
});

function handleError(err) {
  console.error(err.toString());
  this.emit('end');
}

gulp.task('clean', function(cb) {
  del(['css','posts'], cb);
});

gulp.task('css', function () {
    return gulp.src('src/css/*.less')
        .pipe($.less())
        .on('error', handleError)
        .pipe($.autoprefixer({
            browsers: ['last 2 versions']
        }))
        .pipe($.csso())
        .pipe(gulp.dest('css'))
        .pipe(reload({stream:true}));
});

gulp.task('posts', function () {
    return  gulp.src('./src/posts/**/*.jade')
        .pipe($.jade())
        .pipe(gulp.dest('./posts'))
        .pipe(reload({stream:true}));
});

gulp.task( ['css','posts']);

gulp.task('default', ['clean'], function () {
    gulp.start([ 'browser-sync']);
    gulp.watch('**/*.less', ['css']);
    gulp.watch('**/*.jade', ['posts']);
});<commit_msg>Fix broken file<commit_after>'use strict';

var gulp = require('gulp');
var del = require('del');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var plugins = require('gulp-load-plugins')();
var $ = require('gulp-load-plugins')({ pattern: ['gulp-*'] });
var getBundleName = function () {
  var version = require('./package.json').version;
  var name = require('./package.json').name;
  return version + '.' + name + '.' + 'min';
};

gulp.task('browser-sync',  ['build'],  function() {
  browserSync({
    server: {
      baseDir: './',
      directory: false
    },
    open: false
  });
});

function handleError(err) {
  console.error(err.toString());
  this.emit('end');
}

gulp.task('clean', function(cb) {
  del(['css','posts'], cb);
});

gulp.task('css', function () {
    return gulp.src('src/css/*.less')
        .pipe($.less())
        .on('error', handleError)
        .pipe($.autoprefixer({
            browsers: ['last 2 versions']
        }))
        .pipe($.csso())
        .pipe(gulp.dest('css'))
        .pipe(reload({stream:true}));
});

gulp.task('posts', function () {
    return  gulp.src('./src/posts/**/*.jade')
        .pipe($.jade())
        .pipe(gulp.dest('./posts'))
        .pipe(reload({stream:true}));
});

gulp.task('build', ['css','posts']);

gulp.task('default', ['clean'], function () {
    gulp.start(['build', 'browser-sync']);
    gulp.watch('**/*.less', ['css']);
    gulp.watch('**/*.jade', ['posts']);
});<|endoftext|>


<commit_before>var fs = require('fs');
var gulp = require('gulp');
var gutil = require('gulp-util');
var path = require('path');
var spawnSync = require('child_process').spawnSync;
var webpack = require('webpack');
var zip = require('gulp-zip');

var ENVIRONMENT = process.env.NODE_ENV || 'development';
var PRODUCTION = ENVIRONMENT === 'production';

var CHROME_SOURCE_PATH = path.join(__dirname, 'chrome/src');
var CHROME_BUILD_PATH = path.join(__dirname, 'chrome/build');
var CHROME_PACKAGES_PATH = path.join(__dirname, 'chrome/package');

var CHROME_ASSETS_SOURCE_PATH = CHROME_SOURCE_PATH + '/{html/*,img/*,manifest.json}';
var CHROME_SCRIPTS_SOURCE_PATH = path.join(CHROME_SOURCE_PATH, 'js');

var WEBPACK_CONFIG = {
  context: CHROME_SCRIPTS_SOURCE_PATH,
  devtool: PRODUCTION ? null : 'source-map',
  entry: {
    'js/contentscript': './contentscript',
    'js/popup': './popup'
  },
  resolve: {
    root: [__dirname, CHROME_SCRIPTS_SOURCE_PATH]
  },
  output: {
    path: CHROME_BUILD_PATH,
    filename: '[name].js'
  },
  module: {
    loaders: [{
      loader: 'babel',
      test: /\.jsx?$/,
      exclude: /node_modules/,
      query: {
        presets: ['es2015', 'react'],
        plugins: ['transform-object-rest-spread']
      }
    }, {
      loader: 'json',
      test: /\.json$/
    }]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(ENVIRONMENT)
      }
    }),
    PRODUCTION && new webpack.optimize.DedupePlugin(),
    PRODUCTION && new webpack.optimize.UglifyJsPlugin()
  ].filter(Boolean)
};

gulp.task('scripts', function(done) {
  webpack(WEBPACK_CONFIG, function(error, stats) {
    if (error) throw new gutil.PluginError('webpack:build', error);

    gutil.log('[webpack:build]', '\n' + stats.toString({ chunks: false, colors: true }));

    done();
  });
});

gulp.task('watch:scripts', function(done) { //eslint-disable-line no-unused-vars
  var config = Object.assign({}, WEBPACK_CONFIG, { watch: true });
  var compiler = webpack(config);

  compiler.watch({}, function(error, stats) {
    if (error) throw new gutil.PluginError('webpack:build', error);

    gutil.log('[webpack:build]', stats.toString({ colors: true }));
    gutil.log('[webpack:build]', 'Built scripts');
  });
});

gulp.task('assets', function() {
  return gulp.src(CHROME_ASSETS_SOURCE_PATH)
    .pipe(gulp.dest(CHROME_BUILD_PATH));
});

gulp.task('watch:assets', function() {
  gulp.watch(CHROME_ASSETS_SOURCE_PATH, ['assets']);
});

gulp.task('clean', function() {
  spawnSync('rm', ['-rf', CHROME_BUILD_PATH]);
});

gulp.task('package', () => {
  var manifestContents = fs.readFileSync(path.join(CHROME_SOURCE_PATH, 'manifest.json'));
  var manifest = JSON.parse(manifestContents);
  var version = manifest.version;
  var name = 'package-' + version + '.zip';

  return gulp.src(CHROME_BUILD_PATH)
    .pipe(zip(name))
    .pipe(gulp.dest(CHROME_PACKAGES_PATH));
});

gulp.task('watch', ['watch:assets', 'watch:scripts']);
gulp.task('build', ['scripts', 'assets']);
<commit_msg>Fix gulp package task<commit_after>var fs = require('fs');
var gulp = require('gulp');
var gutil = require('gulp-util');
var path = require('path');
var spawnSync = require('child_process').spawnSync;
var webpack = require('webpack');
var zip = require('gulp-zip');

var ENVIRONMENT = process.env.NODE_ENV || 'development';
var PRODUCTION = ENVIRONMENT === 'production';

var CHROME_SOURCE_PATH = path.join(__dirname, 'chrome/src');
var CHROME_BUILD_PATH = path.join(__dirname, 'chrome/build');
var CHROME_PACKAGES_PATH = path.join(__dirname, 'chrome/package');

var CHROME_ASSETS_SOURCE_PATH = CHROME_SOURCE_PATH + '/{html/*,img/*,manifest.json}';
var CHROME_SCRIPTS_SOURCE_PATH = path.join(CHROME_SOURCE_PATH, 'js');

var WEBPACK_CONFIG = {
  context: CHROME_SCRIPTS_SOURCE_PATH,
  devtool: PRODUCTION ? null : 'source-map',
  entry: {
    'js/contentscript': './contentscript',
    'js/popup': './popup'
  },
  resolve: {
    root: [__dirname, CHROME_SCRIPTS_SOURCE_PATH]
  },
  output: {
    path: CHROME_BUILD_PATH,
    filename: '[name].js'
  },
  module: {
    loaders: [{
      loader: 'babel',
      test: /\.jsx?$/,
      exclude: /node_modules/,
      query: {
        presets: ['es2015', 'react'],
        plugins: ['transform-object-rest-spread']
      }
    }, {
      loader: 'json',
      test: /\.json$/
    }]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(ENVIRONMENT)
      }
    }),
    PRODUCTION && new webpack.optimize.DedupePlugin(),
    PRODUCTION && new webpack.optimize.UglifyJsPlugin()
  ].filter(Boolean)
};

gulp.task('scripts', function(done) {
  webpack(WEBPACK_CONFIG, function(error, stats) {
    if (error) throw new gutil.PluginError('webpack:build', error);

    gutil.log('[webpack:build]', '\n' + stats.toString({ chunks: false, colors: true }));

    done();
  });
});

gulp.task('watch:scripts', function(done) { //eslint-disable-line no-unused-vars
  var config = Object.assign({}, WEBPACK_CONFIG, { watch: true });
  var compiler = webpack(config);

  compiler.watch({}, function(error, stats) {
    if (error) throw new gutil.PluginError('webpack:build', error);

    gutil.log('[webpack:build]', stats.toString({ colors: true }));
    gutil.log('[webpack:build]', 'Built scripts');
  });
});

gulp.task('assets', function() {
  return gulp.src(CHROME_ASSETS_SOURCE_PATH)
    .pipe(gulp.dest(CHROME_BUILD_PATH));
});

gulp.task('watch:assets', function() {
  gulp.watch(CHROME_ASSETS_SOURCE_PATH, ['assets']);
});

gulp.task('clean', function() {
  spawnSync('rm', ['-rf', CHROME_BUILD_PATH]);
});

gulp.task('package', () => {
  var manifestContents = fs.readFileSync(path.join(CHROME_SOURCE_PATH, 'manifest.json'));
  var manifest = JSON.parse(manifestContents);
  var version = manifest.version;
  var name = 'package-' + version + '.zip';

  return gulp.src(CHROME_BUILD_PATH + '/*')
    .pipe(zip(name))
    .pipe(gulp.dest(CHROME_PACKAGES_PATH));
});

gulp.task('watch', ['watch:assets', 'watch:scripts']);
gulp.task('build', ['scripts', 'assets']);
<|endoftext|>


<commit_before>/**
 * @module gulpfile
 * @license MIT
 * @version 2018/03/26
 */

'use strict';

const util = require('util');
const gulp = require('gulp');
const rimraf = require('del');
const cssnano = require('cssnano');
const uglify = require('uglify-es');
const chokidar = require('chokidar');
const concat = require('gulp-concat');
const plumber = require('gulp-plumber');
const css = require('@nuintun/gulp-css');
const cmd = require('@nuintun/gulp-cmd');
const cmdAddons = require('@nuintun/gulp-cmd-plugins');
const cssAddons = require('@nuintun/gulp-css-plugins');
const switchStream = require('@nuintun/switch-stream');
const { join, relative, dirname, extname, resolve } = require('path');

const { chalk, logger } = cmd;
const { through } = switchStream;

const ROOT = process.cwd();
const RUNTIME = ['static/develop/loader/sea.js'];
const CSS_LOADER = '/static/develop/loader/css-loader.js';
const IGNORE = new Set(['static/develop/js/base/jquery/**/*', CSS_LOADER.slice(1)]);

// Plumber configure
const plumberOpts = {
  /**
   * @method errorHandler
   * @param {Error} error
   */
  errorHandler(error) {
    return logger.error(inspectError(error));
  }
};

/**
 * @function unixify
 * @param {string} path
 * @returns {string}
 */
function unixify(path) {
  return path.replace(/\\/g, '/');
}

/**
 * @function progress
 * @description Show progress logger
 */
function progress() {
  return through(function(vinyl, encoding, next) {
    const file = chalk.reset.green(unixify(join(vinyl.base, vinyl.relative)));
    const info = chalk.reset.reset('Building ') + file;

    logger.info(info);

    next(null, vinyl);
  });
}

/**
 * @function inspectError
 * @param {Error} error
 * @returns {string}
 */
function inspectError(error) {
  error = util.inspect(error, { colors: true });
  error = error.replace(/^\{\s*|\}\s*$/g, '');

  return `${error}\x07`;
}

/**
 * @function compress
 * @description Compress javascript file
 */
function compress() {
  return switchStream(
    vinyl => {
      return extname(vinyl.path)
        .slice(1)
        .toLowerCase();
    },
    {
      js: through(function(vinyl, encoding, next) {
        const path = vinyl.path;
        const contents = vinyl.contents.toString();
        const options = { ecma: 5, ie8: true, mangle: { eval: true } };
        const result = uglify.minify({ [path]: contents }, options);

        if (result.error) {
          logger.error(inspectError(result.error));
        } else {
          vinyl.contents = Buffer.from(result.code);
        }

        next(null, vinyl);
      }),
      css: through(async function(vinyl, encoding, next) {
        try {
          const result = await cssnano.process(vinyl.contents.toString(), { safe: true });

          vinyl.contents = Buffer.from(result.css);
        } catch (error) {
          logger.error(inspectError(error));
        }

        next(null, vinyl);
      })
    }
  );
}

/**
 * @function watch
 * @description Files watch
 * @param {string|Array<string>} glob
 * @param {Object} options
 * @param {Function} callabck
 */
function watch(glob, options, callabck) {
  if (typeof options === 'function') {
    callabck = options;
    options = {};
  }

  // Ignore initial add event
  options.ignoreInitial = true;
  // Ignore permission errors
  options.ignorePermissionErrors = true;

  // Get watcher
  const watcher = chokidar.watch(glob, options);

  // Bind event
  if (callabck) {
    watcher.on('all', callabck);
  }

  // Return watcher
  return watcher;
}

/**
 * @function getAlias
 */
function getAlias() {
  delete require.cache[require.resolve('./alias.json')];

  return require('./alias.json');
}

/**
 * @function onpath
 * @description Resolve css path
 * @param {string} prop
 * @param {string} path
 * @param {string} referer
 * @returns {string}
 */
function onpath(prop, path, referer) {
  if (/^(?:[a-z0-9.+-]+:)?\/\/|^data:\w+?\/\w+?[,;]/i.test(path)) {
    return path;
  }

  if (!path.startsWith('/')) {
    path = join(dirname(referer), path);
    path = '/' + unixify(relative(ROOT, path));
  }

  return path.replace('/static/develop/', '/static/product/');
}

/**
 * @function resolveMap
 * @description Resolve map path
 * @param {string} path
 * @returns {string}
 */
function resolveMap(path) {
  return path.replace('/static/develop/', '/static/product/');
}

/**
 * @function clean
 */
function clean() {
  return rimraf('static/product');
}

/**
 * @function runtime
 * @param {boolean} product
 */
function runtime(product) {
  return function runtime() {
    // Loader file
    return gulp
      .src(RUNTIME, { base: 'static/develop/loader', nodir: true })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(concat('sea.js'))
      .pipe(product ? compress() : through())
      .pipe(gulp.dest('static/product/loader'));
  };
}

/**
 * @function images
 * @param {boolean} product
 */
function images(product) {
  return function images() {
    return gulp
      .src('static/develop/images/**/*', { base: 'static/develop/images', nodir: true })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(gulp.dest('static/product/images'));
  };
}

/**
 * @function script
 * @param {boolean} product
 */
function script(product) {
  let uid = 0;
  const manifest = new Map();
  const skipCache = new Map();

  /**
   * @function skipMinifyId
   * @param {string} path
   * @returns {boolean}
   */
  function skipMinifyId(path) {
    if (skipCache.has(path)) return skipCache.get(path);

    const src = unixify(path);
    const skipped = src.includes('/jquery.js') || src.includes('/css-loader.js');

    skipCache.set(path, skipped);

    return skipped;
  }

  /**
   * @function map
   * @param {string} path
   * @param {string} resolved
   * @returns {string}
   */
  function map(path, resolved) {
    if (product && !skipMinifyId(resolved)) {
      if (manifest.has(resolved)) return manifest.get(resolved);

      const id = String(uid++);

      manifest.set(resolved, id);

      return id;
    }

    return resolveMap(path);
  }
  /**
   * @function isBootstrapScript
   * @param {string} path
   * @returns {boolean}
   */
  function isBootstrapScript(path) {
    return extname(path).toLowerCase() === '.js' && /[\\/]view[\\/]/.test(path);
  }

  function common() {
    return gulp
      .src('static/develop/js/view/common.js', { base: 'static/develop/js', nodir: true, allowEmpty: true })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(
        cmd({
          map: (path, resolved) => {
            if (product) {
              IGNORE.add(resolved);
            }

            return map(path, resolved);
          },
          combine: product,
          alias: getAlias(),
          indent: product ? 0 : 2,
          base: 'static/develop/js',
          ignore: product ? [...IGNORE] : [],
          css: { onpath, loader: CSS_LOADER },
          plugins: [cmdAddons({ minify: product, sourceMaps: !product })]
        })
      )
      .pipe(
        through((vinyl, encoding, next) => {
          if (!product) return next(null, vinyl);

          const path = vinyl.path;
          const id = manifest.has(path) ? manifest.get(path) : '/static/product/js/view/common.js';
          const entry = Buffer.from(`${product ? '' : '\n\n'}seajs.use(${JSON.stringify(id)});`);

          vinyl.contents = Buffer.concat([vinyl.contents, entry]);

          return next(null, vinyl);
        })
      )
      .pipe(gulp.dest('static/product/js'));
  }

  function script() {
    return gulp
      .src(['static/develop/js/**/*', '!static/develop/js/view/common.js'], {
        base: 'static/develop/js',
        nodir: true
      })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(
        cmd({
          map,
          alias: getAlias(),
          indent: product ? 0 : 2,
          base: 'static/develop/js',
          ignore: product ? [...IGNORE] : [],
          css: { onpath, loader: CSS_LOADER },
          plugins: [cmdAddons({ minify: product, sourceMaps: !product })],
          combine: module => product && unixify(module).includes('/js/view/')
        })
      )
      .pipe(
        through((vinyl, encoding, next) => {
          if (!product) return next(null, vinyl);

          const path = vinyl.path;

          if (isBootstrapScript(path)) {
            const id = manifest.has(path)
              ? manifest.get(path)
              : ('/' + unixify(relative(ROOT, path))).replace('/static/develop/', '/static/product/');

            const entry = Buffer.from(`${product ? '' : '\n\n'}seajs.use(${JSON.stringify(id)});`);

            vinyl.contents = Buffer.concat([vinyl.contents, entry]);
          }

          return next(null, vinyl);
        })
      )
      .pipe(gulp.dest('static/product/js'));
  }

  return gulp.series(common, script);
}

/**
 * @function style
 * @param {boolean} product
 */
function style(product) {
  return function style() {
    return gulp
      .src(product ? 'static/develop/css/?(base|view)/**/*' : 'static/develop/css/**/*', {
        base: 'static/develop/css',
        nodir: true
      })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(
        css({
          onpath,
          map: resolveMap,
          combine: product,
          plugins: [cssAddons({ minify: product })]
        })
      )
      .pipe(gulp.dest('static/product/css'));
  };
}

/**
 * @function watching
 */
function watching() {
  let bookmark = new Date();
  const base = join(process.cwd(), 'static/develop');

  /**
   * @function finish
   * @description Build finish function
   */
  function finish() {
    const now = new Date();

    logger.info(
      '%s build complete... %s',
      chalk.reset.green.bold.inverse(' √ DONE '),
      chalk.reset.green('+' + (now - bookmark) + 'ms')
    );
  }

  /**
   * @function debugWatcher
   * @param {string} event
   * @param {string} path
   */
  function debugWatcher(event, path) {
    const now = new Date();

    logger.info(
      '%s %s: %s',
      chalk.reset.green.bold.inverse(' • READ '),
      event,
      chalk.reset.green(join('static/develop', path).replace(/\\/g, '/'))
    );
  }

  // Watch js file
  watch('static/develop/js', (event, path) => {
    const rpath = relative(base, path);

    bookmark = new Date();
    event = event.toLowerCase();

    debugWatcher(event, rpath);

    if (event === 'unlink' || event === 'unlinkdir') {
      rimraf(resolve('static/product', rpath)).then(finish);
    } else {
      gulp
        .src(path, { base: 'static/develop/js' })
        .pipe(plumber(plumberOpts))
        .pipe(
          cmd({
            map: resolveMap,
            alias: getAlias(),
            plugins: [cmdAddons()],
            base: 'static/develop/js',
            css: { onpath, loader: CSS_LOADER }
          })
        )
        .pipe(gulp.dest('static/product/js'))
        .on('finish', finish);
    }
  });

  // Watch css file
  watch('static/develop/css', (event, path) => {
    const rpath = relative(base, path);

    bookmark = new Date();
    event = event.toLowerCase();

    debugWatcher(event, rpath);

    if (event === 'unlink' || event === 'unlinkdir') {
      rimraf(resolve('static/product', rpath)).then(finish);
    } else {
      gulp
        .src(path, { base: 'static/develop/css' })
        .pipe(plumber(plumberOpts))
        .pipe(
          css({
            onpath,
            map: resolveMap,
            plugins: [cssAddons()]
          })
        )
        .pipe(gulp.dest('static/product/css'))
        .on('finish', finish);
    }
  });

  // Watch image files
  watch('static/develop/images', (event, path) => {
    const rpath = relative(base, path);

    bookmark = Date.now();
    event = event.toLowerCase();

    debugWatcher(event, rpath);

    if (event === 'unlink' || event === 'unlinkdir') {
      rimraf(resolve('static/product', relative(base, path))).then(finish);
    } else {
      gulp
        .src(path, { base: 'static/develop/images' })
        .pipe(plumber(plumberOpts))
        .pipe(gulp.dest('static/product/images'))
        .on('finish', finish);
    }
  });
}

// Task default
gulp.task('default', gulp.series(clean, gulp.parallel(runtime(), images(), script(), style())));

// Task product
gulp.task('product', gulp.series(clean, gulp.parallel(runtime(true), images(true), script(true), style(true))));

// Task watch
gulp.task('watch', gulp.series('default', watching));
<commit_msg>:art: Update files<commit_after>/**
 * @module gulpfile
 * @license MIT
 * @version 2018/03/26
 */

'use strict';

const util = require('util');
const gulp = require('gulp');
const rimraf = require('del');
const cssnano = require('cssnano');
const uglify = require('uglify-es');
const chokidar = require('chokidar');
const concat = require('gulp-concat');
const plumber = require('gulp-plumber');
const css = require('@nuintun/gulp-css');
const cmd = require('@nuintun/gulp-cmd');
const cmdAddons = require('@nuintun/gulp-cmd-plugins');
const cssAddons = require('@nuintun/gulp-css-plugins');
const switchStream = require('@nuintun/switch-stream');
const { join, relative, dirname, extname, resolve } = require('path');

const { chalk, logger } = cmd;
const { through } = switchStream;

const ROOT = process.cwd();
const RUNTIME = ['static/develop/loader/sea.js'];
const CSS_LOADER = '/static/develop/loader/css-loader.js';
const IGNORE = new Set(['static/develop/js/base/jquery/**/*', CSS_LOADER.slice(1)]);

// Plumber configure
const plumberOpts = {
  /**
   * @method errorHandler
   * @param {Error} error
   */
  errorHandler(error) {
    return logger.error(inspectError(error));
  }
};

/**
 * @function unixify
 * @param {string} path
 * @returns {string}
 */
function unixify(path) {
  return path.replace(/\\/g, '/');
}

/**
 * @function progress
 * @description Show progress logger
 */
function progress() {
  return through(function(vinyl, encoding, next) {
    const file = chalk.reset.green(unixify(join(vinyl.base, vinyl.relative)));
    const info = chalk.reset.reset('Building ') + file;

    logger.info(info);

    next(null, vinyl);
  });
}

/**
 * @function inspectError
 * @param {Error} error
 * @returns {string}
 */
function inspectError(error) {
  error = util.inspect(error, { colors: true });
  error = error.replace(/^\{\s*|\}\s*$/g, '');

  return `${error}\x07`;
}

/**
 * @function compress
 * @description Compress javascript file
 */
function compress() {
  return switchStream(
    vinyl => {
      return extname(vinyl.path)
        .slice(1)
        .toLowerCase();
    },
    {
      js: through(function(vinyl, encoding, next) {
        const path = vinyl.path;
        const contents = vinyl.contents.toString();
        const options = { ecma: 5, ie8: true, mangle: { eval: true } };
        const result = uglify.minify({ [path]: contents }, options);

        if (result.error) {
          logger.error(inspectError(result.error));
        } else {
          vinyl.contents = Buffer.from(result.code);
        }

        next(null, vinyl);
      }),
      css: through(async function(vinyl, encoding, next) {
        try {
          const result = await cssnano.process(vinyl.contents.toString());

          vinyl.contents = Buffer.from(result.css);
        } catch (error) {
          logger.error(inspectError(error));
        }

        next(null, vinyl);
      })
    }
  );
}

/**
 * @function watch
 * @description Files watch
 * @param {string|Array<string>} glob
 * @param {Object} options
 * @param {Function} callabck
 */
function watch(glob, options, callabck) {
  if (typeof options === 'function') {
    callabck = options;
    options = {};
  }

  // Ignore initial add event
  options.ignoreInitial = true;
  // Ignore permission errors
  options.ignorePermissionErrors = true;

  // Get watcher
  const watcher = chokidar.watch(glob, options);

  // Bind event
  if (callabck) {
    watcher.on('all', callabck);
  }

  // Return watcher
  return watcher;
}

/**
 * @function getAlias
 */
function getAlias() {
  delete require.cache[require.resolve('./alias.json')];

  return require('./alias.json');
}

/**
 * @function onpath
 * @description Resolve css path
 * @param {string} prop
 * @param {string} path
 * @param {string} referer
 * @returns {string}
 */
function onpath(prop, path, referer) {
  if (/^(?:[a-z0-9.+-]+:)?\/\/|^data:\w+?\/\w+?[,;]/i.test(path)) {
    return path;
  }

  if (!path.startsWith('/')) {
    path = join(dirname(referer), path);
    path = '/' + unixify(relative(ROOT, path));
  }

  return path.replace('/static/develop/', '/static/product/');
}

/**
 * @function resolveMap
 * @description Resolve map path
 * @param {string} path
 * @returns {string}
 */
function resolveMap(path) {
  return path.replace('/static/develop/', '/static/product/');
}

/**
 * @function clean
 */
function clean() {
  return rimraf('static/product');
}

/**
 * @function runtime
 * @param {boolean} product
 */
function runtime(product) {
  return function runtime() {
    // Loader file
    return gulp
      .src(RUNTIME, { base: 'static/develop/loader', nodir: true })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(concat('sea.js'))
      .pipe(product ? compress() : through())
      .pipe(gulp.dest('static/product/loader'));
  };
}

/**
 * @function images
 * @param {boolean} product
 */
function images(product) {
  return function images() {
    return gulp
      .src('static/develop/images/**/*', { base: 'static/develop/images', nodir: true })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(gulp.dest('static/product/images'));
  };
}

/**
 * @function script
 * @param {boolean} product
 */
function script(product) {
  let uid = 0;
  const manifest = new Map();
  const skipCache = new Map();

  /**
   * @function skipMinifyId
   * @param {string} path
   * @returns {boolean}
   */
  function skipMinifyId(path) {
    if (skipCache.has(path)) return skipCache.get(path);

    const src = unixify(path);
    const skipped = src.includes('/jquery.js') || src.includes('/css-loader.js');

    skipCache.set(path, skipped);

    return skipped;
  }

  /**
   * @function map
   * @param {string} path
   * @param {string} resolved
   * @returns {string}
   */
  function map(path, resolved) {
    if (product && !skipMinifyId(resolved)) {
      if (manifest.has(resolved)) return manifest.get(resolved);

      const id = String(uid++);

      manifest.set(resolved, id);

      return id;
    }

    return resolveMap(path);
  }
  /**
   * @function isBootstrapScript
   * @param {string} path
   * @returns {boolean}
   */
  function isBootstrapScript(path) {
    return extname(path).toLowerCase() === '.js' && /[\\/]view[\\/]/.test(path);
  }

  function common() {
    return gulp
      .src('static/develop/js/view/common.js', { base: 'static/develop/js', nodir: true, allowEmpty: true })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(
        cmd({
          map: (path, resolved) => {
            if (product) {
              IGNORE.add(resolved);
            }

            return map(path, resolved);
          },
          combine: product,
          alias: getAlias(),
          indent: product ? 0 : 2,
          base: 'static/develop/js',
          ignore: product ? [...IGNORE] : [],
          css: { onpath, loader: CSS_LOADER },
          plugins: [cmdAddons({ minify: product, sourceMaps: !product })]
        })
      )
      .pipe(
        through((vinyl, encoding, next) => {
          if (!product) return next(null, vinyl);

          const path = vinyl.path;
          const id = manifest.has(path) ? manifest.get(path) : '/static/product/js/view/common.js';
          const entry = Buffer.from(`${product ? '' : '\n\n'}seajs.use(${JSON.stringify(id)});`);

          vinyl.contents = Buffer.concat([vinyl.contents, entry]);

          return next(null, vinyl);
        })
      )
      .pipe(gulp.dest('static/product/js'));
  }

  function script() {
    return gulp
      .src(['static/develop/js/**/*', '!static/develop/js/view/common.js'], {
        base: 'static/develop/js',
        nodir: true
      })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(
        cmd({
          map,
          alias: getAlias(),
          indent: product ? 0 : 2,
          base: 'static/develop/js',
          ignore: product ? [...IGNORE] : [],
          css: { onpath, loader: CSS_LOADER },
          plugins: [cmdAddons({ minify: product, sourceMaps: !product })],
          combine: module => product && unixify(module).includes('/js/view/')
        })
      )
      .pipe(
        through((vinyl, encoding, next) => {
          if (!product) return next(null, vinyl);

          const path = vinyl.path;

          if (isBootstrapScript(path)) {
            const id = manifest.has(path)
              ? manifest.get(path)
              : ('/' + unixify(relative(ROOT, path))).replace('/static/develop/', '/static/product/');

            const entry = Buffer.from(`${product ? '' : '\n\n'}seajs.use(${JSON.stringify(id)});`);

            vinyl.contents = Buffer.concat([vinyl.contents, entry]);
          }

          return next(null, vinyl);
        })
      )
      .pipe(gulp.dest('static/product/js'));
  }

  return gulp.series(common, script);
}

/**
 * @function style
 * @param {boolean} product
 */
function style(product) {
  return function style() {
    return gulp
      .src(product ? 'static/develop/css/?(base|view)/**/*' : 'static/develop/css/**/*', {
        base: 'static/develop/css',
        nodir: true
      })
      .pipe(plumber(plumberOpts))
      .pipe(progress())
      .pipe(
        css({
          onpath,
          map: resolveMap,
          combine: product,
          plugins: [cssAddons({ minify: product })]
        })
      )
      .pipe(gulp.dest('static/product/css'));
  };
}

/**
 * @function watching
 */
function watching() {
  let bookmark = new Date();
  const base = join(process.cwd(), 'static/develop');

  /**
   * @function finish
   * @description Build finish function
   */
  function finish() {
    const now = new Date();

    logger.info(
      '%s build complete... %s',
      chalk.reset.green.bold.inverse(' √ DONE '),
      chalk.reset.green('+' + (now - bookmark) + 'ms')
    );
  }

  /**
   * @function debugWatcher
   * @param {string} event
   * @param {string} path
   */
  function debugWatcher(event, path) {
    const now = new Date();

    logger.info(
      '%s %s: %s',
      chalk.reset.green.bold.inverse(' • READ '),
      event,
      chalk.reset.green(join('static/develop', path).replace(/\\/g, '/'))
    );
  }

  // Watch js file
  watch('static/develop/js', (event, path) => {
    const rpath = relative(base, path);

    bookmark = new Date();
    event = event.toLowerCase();

    debugWatcher(event, rpath);

    if (event === 'unlink' || event === 'unlinkdir') {
      rimraf(resolve('static/product', rpath)).then(finish);
    } else {
      gulp
        .src(path, { base: 'static/develop/js' })
        .pipe(plumber(plumberOpts))
        .pipe(
          cmd({
            map: resolveMap,
            alias: getAlias(),
            plugins: [cmdAddons()],
            base: 'static/develop/js',
            css: { onpath, loader: CSS_LOADER }
          })
        )
        .pipe(gulp.dest('static/product/js'))
        .on('finish', finish);
    }
  });

  // Watch css file
  watch('static/develop/css', (event, path) => {
    const rpath = relative(base, path);

    bookmark = new Date();
    event = event.toLowerCase();

    debugWatcher(event, rpath);

    if (event === 'unlink' || event === 'unlinkdir') {
      rimraf(resolve('static/product', rpath)).then(finish);
    } else {
      gulp
        .src(path, { base: 'static/develop/css' })
        .pipe(plumber(plumberOpts))
        .pipe(
          css({
            onpath,
            map: resolveMap,
            plugins: [cssAddons()]
          })
        )
        .pipe(gulp.dest('static/product/css'))
        .on('finish', finish);
    }
  });

  // Watch image files
  watch('static/develop/images', (event, path) => {
    const rpath = relative(base, path);

    bookmark = Date.now();
    event = event.toLowerCase();

    debugWatcher(event, rpath);

    if (event === 'unlink' || event === 'unlinkdir') {
      rimraf(resolve('static/product', relative(base, path))).then(finish);
    } else {
      gulp
        .src(path, { base: 'static/develop/images' })
        .pipe(plumber(plumberOpts))
        .pipe(gulp.dest('static/product/images'))
        .on('finish', finish);
    }
  });
}

// Task default
gulp.task('default', gulp.series(clean, gulp.parallel(runtime(), images(), script(), style())));

// Task product
gulp.task('product', gulp.series(clean, gulp.parallel(runtime(true), images(true), script(true), style(true))));

// Task watch
gulp.task('watch', gulp.series('default', watching));
<|endoftext|>


<commit_before>/**
 * Gulp Packages
 */

// General
var gulp = require('gulp');
var fs = require('fs');
var del = require('del');
var lazypipe = require('lazypipe');
var plumber = require('gulp-plumber');
var flatten = require('gulp-flatten');
var tap = require('gulp-tap');
var rename = require('gulp-rename');
var header = require('gulp-header');
var footer = require('gulp-footer');
var watch = require('gulp-watch');
var livereload = require('gulp-livereload');
var package = require('./package.json');

// Scripts and tests
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var karma = require('gulp-karma');

// Styles
var sass = require('gulp-ruby-sass');
var prefix = require('gulp-autoprefixer');
var minify = require('gulp-minify-css');

// SVGs
var svgmin = require('gulp-svgmin');
var svgstore = require('gulp-svgstore');

// Docs
var markdown = require('gulp-markdown');
var fileinclude = require('gulp-file-include');

/**
 * Paths to project folders
 */

var paths = {
	input: 'src/**/*',
	output: 'dist/',
	scripts: {
		input: 'src/js/*',
		output: 'dist/js/'
	},
	styles: {
		input: 'src/sass/**/*.{scss,sass}',
		output: 'dist/css/'
	},
	svgs: {
		input: 'src/svg/**/*.svg',
		output: 'dist/svg/'
	},
	static: 'src/static/**',
	test: {
		input: 'src/js/**/*.js',
		karma: 'test/karma.conf.js',
		spec: 'test/spec/**/*.js',
		coverage: 'test/coverage/',
		results: 'test/results/'
	},
	docs: {
		input: 'src/docs/*.{html,md,markdown}',
		output: 'docs/',
		templates: 'src/docs/_templates/',
		assets: 'src/docs/assets/**'
	}
};

/**
 * Template for banner to add to file headers
 */

var banner = {
	full :
		'/**\n' +
		' * <%= package.name %> v<%= package.version %>\n' +
		' * <%= package.description %>, by <%= package.author.name %>.\n' +
		' * <%= package.repository.url %>\n' +
		' * \n' +
		' * Free to use under the MIT License.\n' +
		' * http://gomakethings.com/mit/\n' +
		' */\n\n',
	min :
		'/**' +
		' <%= package.name %> v<%= package.version %>, by Chris Ferdinandi' +
		' | <%= package.repository.url %>' +
		' | Licensed under MIT: http://gomakethings.com/mit/' +
		' */\n'
};

/**
 * Gulp Taks
 */

// Lint, minify, and concatenate scripts
gulp.task('build:scripts', ['clean:dist'], function() {
	var jsTasks = lazypipe()
		.pipe(header, banner.full, { package : package })
		.pipe(gulp.dest, paths.scripts.output)
		.pipe(rename, { suffix: '.min' })
		.pipe(uglify)
		.pipe(header, banner.min, { package : package })
		.pipe(gulp.dest, paths.scripts.output);

	return gulp.src(paths.scripts.input)
		.pipe(plumber())
		.pipe(tap(function (file, t) {
			if ( file.isDirectory() ) {
				var name = file.relative + '.js';
				return gulp.src(file.path + '/*.js')
					.pipe(concat(name))
					.pipe(jsTasks());
			}
		}))
		.pipe(jsTasks());
});

// Process, lint, and minify Sass files
gulp.task('build:styles', ['clean:dist'], function() {
	return gulp.src(paths.styles.input)
		.pipe(plumber())
		.pipe(sass({style: 'expanded', noCache: true, 'sourcemap=none': true}))
		.pipe(flatten())
		.pipe(prefix('last 2 version', '> 1%'))
		.pipe(header(banner.full, { package : package }))
		.pipe(gulp.dest(paths.styles.output))
		.pipe(rename({ suffix: '.min' }))
		.pipe(minify())
		.pipe(header(banner.min, { package : package }))
		.pipe(gulp.dest(paths.styles.output));
});

// Generate SVG sprites
gulp.task('build:svgs', ['clean:dist'], function () {
	return gulp.src(paths.svgs.input)
		.pipe(svgmin())
		.pipe(svgstore({
			fileName: 'icons.svg',
			prefix: 'icon-',
			inlineSvg: true
		}))
		.pipe(gulp.dest(paths.svgs.output));
});

// Copy static files into output folder
gulp.task('copy:static', ['clean:dist'], function() {
	return gulp.src(paths.static)
		.pipe(plumber())
		.pipe(gulp.dest(paths.output));
});

// Lint scripts
gulp.task('lint:scripts', function () {
	return gulp.src(paths.scripts.input)
		.pipe(plumber())
		.pipe(jshint())
		.pipe(jshint.reporter('jshint-stylish'));
});

// Remove prexisting content from output and test folders
gulp.task('clean:dist', function () {
	del.sync([
		paths.output,
		paths.test.coverage,
		paths.test.results
	]);
});

// Run unit tests
gulp.task('test:scripts', function() {
	return gulp.src([paths.test.input].concat([paths.test.spec]))
		.pipe(plumber())
		.pipe(karma({ configFile: paths.test.karma }))
		.on('error', function(err) { throw err; });
});

// Generate documentation
gulp.task('build:docs', ['default', 'clean:docs'], function() {
	return gulp.src(paths.docs.input)
		.pipe(plumber())
		.pipe(fileinclude({
			prefix: '@@',
			basepath: '@file'
		}))
		.pipe(tap(function (file, t) {
			if ( /\.md|\.markdown/.test(file.path) ) {
				return t.through(markdown);
			}
		}))
		.pipe(header(fs.readFileSync(paths.docs.templates + '/_header.html', 'utf8')))
		.pipe(footer(fs.readFileSync(paths.docs.templates + '/_footer.html', 'utf8')))
		.pipe(gulp.dest(paths.docs.output));
});

// Copy distribution files to docs
gulp.task('copy:dist', ['default', 'clean:docs'], function() {
	return gulp.src(paths.output + '/**')
		.pipe(plumber())
		.pipe(gulp.dest(paths.docs.output + '/dist'));
});

// Copy documentation assets to docs
gulp.task('copy:assets', ['clean:docs'], function() {
	return gulp.src(paths.docs.assets)
		.pipe(plumber())
		.pipe(gulp.dest(paths.docs.output + '/assets'));
});

// Remove prexisting content from docs folder
gulp.task('clean:docs', function () {
	return del.sync(paths.docs.output);
});

// Watch for changes to files
gulp.task('listen', function () {
	watch(paths.input, function (files) {
		gulp.start('default');
	});
});

// Watch for changes to files and docs
gulp.task('listen:docs', function () {
	watch(paths.input, function (files) {
		gulp.start('docs');
	});
});

// Spin up livereload server and listen for file changes
gulp.task('server', function () {
	livereload.listen();
	watch(paths.input, function (files) {
		gulp.start('default');
		gulp.start('refresh');
	});
});

// Spin up livereload server and listen for file and documentation changes
gulp.task('server:docs', function () {
	livereload.listen();
	watch(paths.input, function (files) {
		gulp.start('docs');
		gulp.start('refresh:docs');
	});
});

// Run livereload after file change
gulp.task('refresh', ['default'], function () {
	livereload.changed();
});

// Run livereload after file or documentation change
gulp.task('refresh:docs', ['docs'], function () {
	livereload.changed();
});

/**
 * Task Runners
 */

// Compile files (default)
gulp.task('default', [
	'lint:scripts',
	'clean:dist',
	'copy:static',
	'build:scripts',
	'build:svgs',
	'build:styles',
	'test:scripts'
]);

// Compile files and generate documentation
gulp.task('docs', [
	'default',
	'clean:docs',
	'build:docs',
	'copy:dist',
	'copy:assets'
]);

// Compile files when something changes
gulp.task('watch', [
	'listen',
	'default'
]);

// Compile files and generate docs when something changes
gulp.task('watch:docs', [
	'listen:docs',
	'docs'
]);

// Compile files and livereload pages when something changes
gulp.task('reload', [
	'server',
	'default'
]);

// Compile files, generate docs, and livereload pages when something changes
gulp.task('reload:docs', [
	'server:docs',
	'docs'
]);<commit_msg>Updated gulpfile<commit_after>/**
 * Gulp Packages
 */

// General
var gulp = require('gulp');
var fs = require('fs');
var del = require('del');
var lazypipe = require('lazypipe');
var plumber = require('gulp-plumber');
var flatten = require('gulp-flatten');
var tap = require('gulp-tap');
var rename = require('gulp-rename');
var header = require('gulp-header');
var footer = require('gulp-footer');
var watch = require('gulp-watch');
var livereload = require('gulp-livereload');
var package = require('./package.json');

// Scripts and tests
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var karma = require('gulp-karma');

// Styles
var sass = require('gulp-ruby-sass');
var prefix = require('gulp-autoprefixer');
var minify = require('gulp-minify-css');

// SVGs
var svgmin = require('gulp-svgmin');
var svgstore = require('gulp-svgstore');

// Docs
var markdown = require('gulp-markdown');
var fileinclude = require('gulp-file-include');

/**
 * Paths to project folders
 */

var paths = {
	input: 'src/**/*',
	output: 'dist/',
	scripts: {
		input: 'src/js/*',
		output: 'dist/js/'
	},
	styles: {
		input: 'src/sass/**/*.{scss,sass}',
		output: 'dist/css/'
	},
	svgs: {
		input: 'src/svg/*',
		output: 'dist/svg/'
	},
	static: 'src/static/**',
	test: {
		input: 'src/js/**/*.js',
		karma: 'test/karma.conf.js',
		spec: 'test/spec/**/*.js',
		coverage: 'test/coverage/',
		results: 'test/results/'
	},
	docs: {
		input: 'src/docs/*.{html,md,markdown}',
		output: 'docs/',
		templates: 'src/docs/_templates/',
		assets: 'src/docs/assets/**'
	}
};

/**
 * Template for banner to add to file headers
 */

var banner = {
	full :
		'/**\n' +
		' * <%= package.name %> v<%= package.version %>\n' +
		' * <%= package.description %>, by <%= package.author.name %>.\n' +
		' * <%= package.repository.url %>\n' +
		' * \n' +
		' * Free to use under the MIT License.\n' +
		' * http://gomakethings.com/mit/\n' +
		' */\n\n',
	min :
		'/**' +
		' <%= package.name %> v<%= package.version %>, by Chris Ferdinandi' +
		' | <%= package.repository.url %>' +
		' | Licensed under MIT: http://gomakethings.com/mit/' +
		' */\n'
};

/**
 * Gulp Taks
 */

// Lint, minify, and concatenate scripts
gulp.task('build:scripts', ['clean:dist'], function() {
	var jsTasks = lazypipe()
		.pipe(header, banner.full, { package : package })
		.pipe(gulp.dest, paths.scripts.output)
		.pipe(rename, { suffix: '.min' })
		.pipe(uglify)
		.pipe(header, banner.min, { package : package })
		.pipe(gulp.dest, paths.scripts.output);

	return gulp.src(paths.scripts.input)
		.pipe(plumber())
		.pipe(tap(function (file, t) {
			if ( file.isDirectory() ) {
				var name = file.relative + '.js';
				return gulp.src(file.path + '/*.js')
					.pipe(concat(name))
					.pipe(jsTasks());
			}
		}))
		.pipe(jsTasks());
});

// Process, lint, and minify Sass files
gulp.task('build:styles', ['clean:dist'], function() {
	return gulp.src(paths.styles.input)
		.pipe(plumber())
		.pipe(sass({style: 'expanded', noCache: true, 'sourcemap=none': true}))
		.pipe(flatten())
		.pipe(prefix('last 2 version', '> 1%'))
		.pipe(header(banner.full, { package : package }))
		.pipe(gulp.dest(paths.styles.output))
		.pipe(rename({ suffix: '.min' }))
		.pipe(minify())
		.pipe(header(banner.min, { package : package }))
		.pipe(gulp.dest(paths.styles.output));
});

// Generate SVG sprites
gulp.task('build:svgs', ['clean:dist'], function () {
	return gulp.src(paths.svgs.input)
		.pipe(plumber())
		.pipe(tap(function (file, t) {
			if ( file.isDirectory() ) {
				var name = file.relative + '.svg';
				return gulp.src(file.path + '/*.svg')
					.pipe(svgmin())
					.pipe(svgstore({
						fileName: name,
						prefix: 'icon-',
						inlineSvg: true
					}))
					.pipe(gulp.dest(paths.svgs.output));
			}
		}))
		.pipe(svgmin())
		.pipe(svgstore({
			fileName: 'icons.svg',
			prefix: 'icon-',
			inlineSvg: true
		}))
		.pipe(gulp.dest(paths.svgs.output));
});

// Copy static files into output folder
gulp.task('copy:static', ['clean:dist'], function() {
	return gulp.src(paths.static)
		.pipe(plumber())
		.pipe(gulp.dest(paths.output));
});

// Lint scripts
gulp.task('lint:scripts', function () {
	return gulp.src(paths.scripts.input)
		.pipe(plumber())
		.pipe(jshint())
		.pipe(jshint.reporter('jshint-stylish'));
});

// Remove prexisting content from output and test folders
gulp.task('clean:dist', function () {
	del.sync([
		paths.output,
		paths.test.coverage,
		paths.test.results
	]);
});

// Run unit tests
gulp.task('test:scripts', function() {
	return gulp.src([paths.test.input].concat([paths.test.spec]))
		.pipe(plumber())
		.pipe(karma({ configFile: paths.test.karma }))
		.on('error', function(err) { throw err; });
});

// Generate documentation
gulp.task('build:docs', ['compile', 'clean:docs'], function() {
	return gulp.src(paths.docs.input)
		.pipe(plumber())
		.pipe(fileinclude({
			prefix: '@@',
			basepath: '@file'
		}))
		.pipe(tap(function (file, t) {
			if ( /\.md|\.markdown/.test(file.path) ) {
				return t.through(markdown);
			}
		}))
		.pipe(header(fs.readFileSync(paths.docs.templates + '/_header.html', 'utf8')))
		.pipe(footer(fs.readFileSync(paths.docs.templates + '/_footer.html', 'utf8')))
		.pipe(gulp.dest(paths.docs.output));
});

// Copy distribution files to docs
gulp.task('copy:dist', ['compile', 'clean:docs'], function() {
	return gulp.src(paths.output + '/**')
		.pipe(plumber())
		.pipe(gulp.dest(paths.docs.output + '/dist'));
});

// Copy documentation assets to docs
gulp.task('copy:assets', ['clean:docs'], function() {
	return gulp.src(paths.docs.assets)
		.pipe(plumber())
		.pipe(gulp.dest(paths.docs.output + '/assets'));
});

// Remove prexisting content from docs folder
gulp.task('clean:docs', function () {
	return del.sync(paths.docs.output);
});

// Spin up livereload server and listen for file changes
gulp.task('listen', function () {
    livereload.listen();
    gulp.watch(paths.input).on('change', function(file) {
        gulp.start('default');
        gulp.start('refresh');
    });
});

// Run livereload after file change
gulp.task('refresh', ['compile', 'docs'], function () {
    livereload.changed();
});

/**
 * Task Runners
 */

// Compile files
gulp.task('compile', [
	'lint:scripts',
	'clean:dist',
	'copy:static',
	'build:scripts',
	'build:svgs',
	'build:styles'
]);

// Generate documentation
gulp.task('docs', [
	'clean:docs',
	'build:docs',
	'copy:dist',
	'copy:assets'
]);

// Generate documentation
gulp.task('tests', [
	'test:scripts'
]);

// Compile files, generate docs, and run unit tests (default)
gulp.task('default', [
	'compile',
	'docs',
	'tests'
]);

// Compile files, generate docs, and run unit tests when something changes
gulp.task('watch', [
    'listen',
    'default'
]);<|endoftext|>


<commit_before>var
gulp = require('gulp'),
fs = require('fs'),
path = require('path'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
del = require('del'),
less = require('gulp-less'),
paths =
{
	less: 'less/build.less',
	js:
	{
		player:
		[
			'./browser/vendor/gl-matrix.js',
			'./browser/scripts/util.js',
			'./browser/scripts/renderer.js',
			'./browser/scripts/plugin-manager-bundled.js',
			'./browser/scripts/plugin-group.js',
			'./browser/scripts/connection.js',
			'./browser/scripts/graph.js',
			'./browser/scripts/node.js',
			'./browser/scripts/registers.js',
			'./browser/scripts/core.js',
			'./browser/plugins/*.plugin.js',
			'./browser/scripts/player.js',
			'./browser/scripts/player-run.js'
		]
	}
};

gulp.task('clean:js:plugins', function(cb)
{
	del('./browser/plugins/all.plugins.js', cb);
});

gulp.task('clean:js:player', function(cb)
{
	del('./browser/scripts/player.min.js', cb);
});

gulp.task('clean:less', function(cb)
{
	del('./browser/style/less.css', cb);
});

gulp.task('clean:js', ['clean:js:plugins', 'clean:js:player']);

gulp.task('clean', ['clean:js']);

gulp.task('js:plugins', ['clean:js:plugins'], function()
{
	gulp.src('browser/plugins/*.js')
	.pipe(uglify())
	.pipe(concat('all.plugins.js'))
	.pipe(gulp.dest('./browser/plugins/'))
});

gulp.task('js:player', ['clean:js:player'], function()
{
	gulp.src(paths.js.player)
	.pipe(uglify())
	.pipe(concat('player.min.js'))
	.pipe(gulp.dest('./browser/scripts/'))
});

gulp.task('js', ['js:plugins', 'js:player']);

gulp.task('less', ['clean:less'], function()
{
	gulp.src(paths.less)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }))
	.pipe(concat('less.css'))
    .pipe(gulp.dest('./browser/style'));
});

gulp.task('default', ['less', 'js']);

<commit_msg>gulp watch and windows support<commit_after>var
gulp = require('gulp'),
fs = require('fs'),
path = require('path'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
del = require('del'),
less = require('gulp-less'),
paths =
{
	less: './less/build.less',
	js:
	{
		player:
		[
			'./browser/vendor/gl-matrix.js',
			'./browser/scripts/util.js',
			'./browser/scripts/renderer.js',
			'./browser/scripts/plugin-manager-bundled.js',
			'./browser/scripts/plugin-group.js',
			'./browser/scripts/connection.js',
			'./browser/scripts/graph.js',
			'./browser/scripts/node.js',
			'./browser/scripts/registers.js',
			'./browser/scripts/core.js',
			'./browser/plugins/*.plugin.js',
			'./browser/scripts/player.js',
			'./browser/scripts/player-run.js'
		]
	}
};

gulp.task('clean:js:plugins', function(cb)
{
	del('./browser/plugins/all.plugins.js', cb);
});

gulp.task('clean:js:player', function(cb)
{
	del('./browser/scripts/player.min.js', cb);
});

gulp.task('clean:less', function(cb)
{
	del('./browser/style/less.css', cb);
});

gulp.task('clean:js', ['clean:js:plugins', 'clean:js:player']);

gulp.task('clean', ['clean:js']);

gulp.task('js:plugins', ['clean:js:plugins'], function()
{
	gulp.src('browser/plugins/*.js')
	.pipe(uglify())
	.pipe(concat('all.plugins.js'))
	.pipe(gulp.dest('./browser/plugins/'))
});

gulp.task('js:player', ['clean:js:player'], function()
{
	gulp.src(paths.js.player)
	.pipe(uglify())
	.pipe(concat('player.min.js'))
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'scripts')))
});

gulp.task('js', ['js:plugins', 'js:player']);

gulp.task('less', ['clean:less'], function()
{
	gulp.src(paths.less)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }))
	.pipe(concat('less.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style'));
});

gulp.task('watch', ['default'], function() {
	gulp.watch('less/**/*', ['less']);
	gulp.watch(paths.js.site, ['scripts']);
});

gulp.task('default', ['less', 'js']);

<|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 promise polyfill for node 0.10 compatibility
require('es6-promise').polyfill();

// 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-all');
var historyApiFallback = require('connect-history-api-fallback');
var packageJson = require('./package.json');
var crypto = require('crypto');
var ensureFiles = require('./tasks/ensure-files.js');

// var ghPages = require('gulp-gh-pages');

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

var DIST = 'dist';

var dist = function(subpath) {
  return !subpath ? DIST : path.join(DIST, subpath);
};

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(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.minifyCss())
    .pipe(gulp.dest(dist(stylesPath)))
    .pipe($.size({title: stylesPath}));
};

var imageOptimizeTask = function(src, dest) {
  return gulp.src(src)
    .pipe($.imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest(dest))
    .pipe($.size({title: 'images'}));
};

var optimizeHtmlTask = function(src, dest) {
  var assets = $.useref.assets({
    searchPath: ['.tmp', 'app']
  });

  return gulp.src(src)
    .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', $.minifyCss()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output files
    .pipe(gulp.dest(dest))
    .pipe($.size({
      title: 'html'
    }));
};

// Compile and automatically prefix stylesheets
gulp.task('styles', function() {
  return styleTask('styles', ['**/*.css']);
});

// Ensure that we are not missing required files for the project
// "dot" files are specifically tricky due to them being hidden on
// some systems.
gulp.task('ensureFiles', function(cb) {
  var requiredFiles = ['.bowerrc'];

  ensureFiles(requiredFiles.map(function(p) {
    return path.join(__dirname, p);
  }), cb);
});

// Optimize images
gulp.task('images', function() {
  return imageOptimizeTask('app/images/**/*', dist('images'));
});

// Copy all files at the root level (app)
gulp.task('copy', function() {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/elements',
    '!app/bower_components',
    '!app/cache-config.json',
    '!**/.DS_Store'
  ], {
    dot: true
  }).pipe(gulp.dest(dist()));

  // Copy over only the bower_components we need
  // These are things which cannot be vulcanized
  var bower = gulp.src([
    'app/bower_components/{webcomponentsjs,platinum-sw,sw-toolbox,promise-polyfill,bridgeit-web-components,jQuery-QueryBuilder}/**/*'
  ]).pipe(gulp.dest(dist('bower_components')));

  return merge(app, bower)
    .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() {
  return optimizeHtmlTask(
    ['app/**/*.html', '!app/{elements,test,bower_components}/**/*.html'],
    dist());
});

// Vulcanize granular configuration
gulp.task('vulcanize', function() {
  return gulp.src('app/elements/elements.html')
    .pipe($.vulcanize({
      stripComments: true,
      inlineCss: true,
      inlineScripts: true
    }))
    .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.
// This task does not run by default, but if you are interested in using service worker caching
// in your project, please enable it within the 'default' task.
// See https://github.com/PolymerElements/polymer-starter-kit#enable-service-worker-support
// for more context.
gulp.task('cache-config', function(callback) {
  var dir = dist();
  var config = {
    cacheId: packageJson.name || path.basename(__dirname),
    disabled: false
  };

  glob([
    'index.html',
    './',
    'bower_components/webcomponentsjs/webcomponents-lite.min.js',
    '{elements,scripts,styles}/**/*.*'],
    {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      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() {
  return del(['.tmp', dist()]);
});

// Watch files for changes & reload
gulp.task('serve', ['styles'], function() {
  browserSync({
    port: 5000,
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // 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: {
      baseDir: ['.tmp', 'app'],
      middleware: [historyApiFallback()]
    }
  });

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

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function() {
  browserSync({
    port: 5001,
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // 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(),
    middleware: [historyApiFallback()]
  });
});

// Build production files, the default task
gulp.task('default', ['clean'], function(cb) {
  // Uncomment 'cache-config' if you are going to use service workers.
  runSequence(
    ['ensureFiles', 'copy', 'styles'],
    ['images', 'fonts', 'html'],
    'vulcanize', // 'cache-config',
    cb);
});

// Build then deploy to GitHub pages gh-pages branch
gulp.task('build-deploy-gh-pages', function(cb) {
  runSequence(
    'default',
    'deploy-gh-pages',
    cb);
});

// Deploy to GitHub pages gh-pages branch
gulp.task('deploy-gh-pages', function() {
  return gulp.src(dist('**/*'))
    // Check if running task from Travis CI, if so run using GH_TOKEN
    // otherwise run using ghPages defaults.
    .pipe($.if(process.env.TRAVIS === 'true', $.ghPages({
      remoteUrl: 'https://$GH_TOKEN@github.com/polymerelements/polymer-starter-kit.git',
      silent: true,
      branch: 'gh-pages'
    }), $.ghPages()));
});

// 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) {
  // Do nothing
}
<commit_msg>add font-awesome to dist bower_components<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 promise polyfill for node 0.10 compatibility
require('es6-promise').polyfill();

// 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-all');
var historyApiFallback = require('connect-history-api-fallback');
var packageJson = require('./package.json');
var crypto = require('crypto');
var ensureFiles = require('./tasks/ensure-files.js');

// var ghPages = require('gulp-gh-pages');

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

var DIST = 'dist';

var dist = function(subpath) {
  return !subpath ? DIST : path.join(DIST, subpath);
};

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(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.minifyCss())
    .pipe(gulp.dest(dist(stylesPath)))
    .pipe($.size({title: stylesPath}));
};

var imageOptimizeTask = function(src, dest) {
  return gulp.src(src)
    .pipe($.imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest(dest))
    .pipe($.size({title: 'images'}));
};

var optimizeHtmlTask = function(src, dest) {
  var assets = $.useref.assets({
    searchPath: ['.tmp', 'app']
  });

  return gulp.src(src)
    .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', $.minifyCss()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output files
    .pipe(gulp.dest(dest))
    .pipe($.size({
      title: 'html'
    }));
};

// Compile and automatically prefix stylesheets
gulp.task('styles', function() {
  return styleTask('styles', ['**/*.css']);
});

// Ensure that we are not missing required files for the project
// "dot" files are specifically tricky due to them being hidden on
// some systems.
gulp.task('ensureFiles', function(cb) {
  var requiredFiles = ['.bowerrc'];

  ensureFiles(requiredFiles.map(function(p) {
    return path.join(__dirname, p);
  }), cb);
});

// Optimize images
gulp.task('images', function() {
  return imageOptimizeTask('app/images/**/*', dist('images'));
});

// Copy all files at the root level (app)
gulp.task('copy', function() {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/elements',
    '!app/bower_components',
    '!app/cache-config.json',
    '!**/.DS_Store'
  ], {
    dot: true
  }).pipe(gulp.dest(dist()));

  // Copy over only the bower_components we need
  // These are things which cannot be vulcanized
  var bower = gulp.src([
    'app/bower_components/{webcomponentsjs,platinum-sw,sw-toolbox,promise-polyfill,bridgeit-web-components,jQuery-QueryBuilder,components-font-awesome}/**/*'
  ]).pipe(gulp.dest(dist('bower_components')));

  return merge(app, bower)
    .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() {
  return optimizeHtmlTask(
    ['app/**/*.html', '!app/{elements,test,bower_components}/**/*.html'],
    dist());
});

// Vulcanize granular configuration
gulp.task('vulcanize', function() {
  return gulp.src('app/elements/elements.html')
    .pipe($.vulcanize({
      stripComments: true,
      inlineCss: true,
      inlineScripts: true
    }))
    .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.
// This task does not run by default, but if you are interested in using service worker caching
// in your project, please enable it within the 'default' task.
// See https://github.com/PolymerElements/polymer-starter-kit#enable-service-worker-support
// for more context.
gulp.task('cache-config', function(callback) {
  var dir = dist();
  var config = {
    cacheId: packageJson.name || path.basename(__dirname),
    disabled: false
  };

  glob([
    'index.html',
    './',
    'bower_components/webcomponentsjs/webcomponents-lite.min.js',
    '{elements,scripts,styles}/**/*.*'],
    {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      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() {
  return del(['.tmp', dist()]);
});

// Watch files for changes & reload
gulp.task('serve', ['styles'], function() {
  browserSync({
    port: 5000,
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // 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: {
      baseDir: ['.tmp', 'app'],
      middleware: [historyApiFallback()]
    }
  });

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

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function() {
  browserSync({
    port: 5001,
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // 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(),
    middleware: [historyApiFallback()]
  });
});

// Build production files, the default task
gulp.task('default', ['clean'], function(cb) {
  // Uncomment 'cache-config' if you are going to use service workers.
  runSequence(
    ['ensureFiles', 'copy', 'styles'],
    ['images', 'fonts', 'html'],
    'vulcanize', // 'cache-config',
    cb);
});

// Build then deploy to GitHub pages gh-pages branch
gulp.task('build-deploy-gh-pages', function(cb) {
  runSequence(
    'default',
    'deploy-gh-pages',
    cb);
});

// Deploy to GitHub pages gh-pages branch
gulp.task('deploy-gh-pages', function() {
  return gulp.src(dist('**/*'))
    // Check if running task from Travis CI, if so run using GH_TOKEN
    // otherwise run using ghPages defaults.
    .pipe($.if(process.env.TRAVIS === 'true', $.ghPages({
      remoteUrl: 'https://$GH_TOKEN@github.com/polymerelements/polymer-starter-kit.git',
      silent: true,
      branch: 'gh-pages'
    }), $.ghPages()));
});

// 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) {
  // Do nothing
}
<|endoftext|>


<commit_before>var path    = require('path');
var gulp    = require('gulp');
var through = require('through2');
var gutil   = require('gulp-util');
var gm      = require('gulp-gm');
var watch   = require('gulp-watch');

var debug          = false;
var PluginError    = gutil.PluginError;
var dirname        = __dirname;
var parent_dir     = path.dirname(dirname);
var source_dir     = parent_dir + '/hue/public/images/uploaded/';
var debug_dir      = parent_dir + '/hue/opt/images/';
var production_dir = parent_dir + '/hue/public/images/uploaded/';
var target_dir     = (debug ? debug_dir : production_dir);

/**
 * Optimise the images
 */
gulp.task('image-opt', function(cb) {

	return watch(source_dir + '*.*', function(vinyl){

		// console.info('from:', source_dir, ', to:', target_dir);
		// console.info('vinyl:', vinyl.event, ', path:',vinyl.path);

		if(vinyl.event === 'add'){

			gulp.src(vinyl.path) //only take care of the newly added images
				.pipe(gm(function(gm_file, done){

					gm_file.format(function(err, format){

			    		// console.info('go go go:', format);

			    		if(format === 'JPEG'){
			    			done(null, gm_file.strip().quality(85).interlace('Line').samplingFactor(2, 1).noProfile());
			    		} else if(format === 'PNG'){
			    			done(null, gm_file.type('PaletteMatte').strip().noProfile());
			    		} else {
			    			done(null, gm_file.strip());
			    		}
			    	});
			    }, {imageMagick: true}))
			    .pipe(gulp.dest(target_dir));

		}

	});
});

gulp.task('force-image-opt', function(cb){
	gulp.src(source_dir + '*.*') //all images
		.pipe(gm(function(gm_file, done){

			gm_file.format(function(err, format){

	    		if(format === 'JPEG'){
	    			done(null, gm_file.strip().quality(85).interlace('Line').samplingFactor(2, 1).noProfile());
	    		} else if(format === 'PNG'){
	    			done(null, gm_file.type('PaletteMatte').strip().noProfile());
	    		} else {
	    			done(null, gm_file.strip());
	    		}
	    	});
	    }, {imageMagick: true}))
	    .pipe(gulp.dest(target_dir));
});

//old files:
gulp.task('force-image-opt-old', function(cb){
	gulp.src([
		'/var/www/html/car/app/webroot/files/lian-car/**/*.jpg',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.jpeg',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.png',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.JPG',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.JPEG',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.PNG'
		]) //all old images
		.pipe(gm(function(gm_file, done){

			console.info('source:', gm_file.source);

			gm_file.format(function(err, format){

				if(err){
					console.error('Error happended when compressing the image:', err);
					return done(null, gm_file);
				}

	    		if(format === 'JPEG'){
	    			done(null, gm_file.strip().quality(85).interlace('Line').samplingFactor(2, 1).noProfile());
	    		} else if(format === 'PNG'){
	    			done(null, gm_file.type('PaletteMatte').strip().noProfile());
	    		} else {
	    			done(null, gm_file.strip());
	    		}
	    	});

			global.gc();

	    }, {imageMagick: true}))
	    .pipe(gulp.dest(function(file){
	    	return file.base;
	    }));
});

gulp.task('default', ['image-opt']);<commit_msg>Added old image compression<commit_after>var path    = require('path');
var gulp    = require('gulp');
var through = require('through2');
var gutil   = require('gulp-util');
var gm      = require('gulp-gm');
var watch   = require('gulp-watch');

var debug          = false;
var PluginError    = gutil.PluginError;
var dirname        = __dirname;
var parent_dir     = path.dirname(dirname);
var source_dir     = parent_dir + '/hue/public/images/uploaded/';
var debug_dir      = parent_dir + '/hue/opt/images/';
var production_dir = parent_dir + '/hue/public/images/uploaded/';
var target_dir     = (debug ? debug_dir : production_dir);

/**
 * Optimise the images
 */
gulp.task('image-opt', function(cb) {

	return watch(source_dir + '*.*', function(vinyl){

		// console.info('from:', source_dir, ', to:', target_dir);
		// console.info('vinyl:', vinyl.event, ', path:',vinyl.path);

		if(vinyl.event === 'add'){

			gulp.src(vinyl.path) //only take care of the newly added images
				.pipe(gm(function(gm_file, done){

					gm_file.format(function(err, format){

			    		// console.info('go go go:', format);

			    		if(format === 'JPEG'){
			    			done(null, gm_file.strip().quality(90).interlace('Line').samplingFactor(2, 1).noProfile());
			    		} else if(format === 'PNG'){
			    			done(null, gm_file.type('PaletteMatte').strip().noProfile());
			    		} else {
			    			done(null, gm_file.strip());
			    		}
			    	});
			    }, {imageMagick: true}))
			    .pipe(gulp.dest(target_dir));

		}

	});
});

gulp.task('force-image-opt', function(cb){
	gulp.src(source_dir + '*.*') //all images
		.pipe(gm(function(gm_file, done){

			console.info('source:', gm_file.source);

			gm_file.format(function(err, format){

	    		if(format === 'JPEG'){
	    			done(null, gm_file.strip().quality(90).interlace('Line').samplingFactor(2, 1).noProfile());
	    		} else if(format === 'PNG'){
	    			done(null, gm_file.type('PaletteMatte').strip().noProfile());
	    		} else {
	    			done(null, gm_file.strip());
	    		}
	    	});
	    }, {imageMagick: true}))
	    .pipe(gulp.dest(target_dir));
});

//old files:
gulp.task('force-image-opt-old', function(cb){
	gulp.src([
		'/var/www/html/car/app/webroot/files/lian-car/**/*.jpg',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.jpeg',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.png',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.JPG',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.JPEG',
		'/var/www/html/car/app/webroot/files/lian-car/**/*.PNG'
		]) //all old images
		.pipe(gm(function(gm_file, done){

			console.info('source:', gm_file.source);

			gm_file.format(function(err, format){

				if(err){
					console.error('Error happended when compressing the image:', err);
					return done(null, gm_file);
				}

	    		if(format === 'JPEG'){
	    			done(null, gm_file.strip().quality(90).interlace('Line').samplingFactor(2, 1).noProfile());
	    		} else if(format === 'PNG'){
	    			done(null, gm_file.type('PaletteMatte').strip().noProfile());
	    		} else {
	    			done(null, gm_file.strip());
	    		}
	    	});

			global.gc();

	    }, {imageMagick: true}))
	    .pipe(gulp.dest(function(file){
	    	return file.base;
	    }));
});

gulp.task('default', ['image-opt']);<|endoftext|>