<commit_before>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & tools we'll use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var critical = require('critical');
var pngquant = require('imagemin-pngquant');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
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/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

gulp.task('compress', function() {
  return gulp.src('dist/**/*.*')
    .pipe($.zopfli())
    .pipe(gulp.dest('dist/'));
});

// Optimize images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngquant()]
    })))
    .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',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    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('copystyles', function () {
    return gulp.src(['dist/styles/main.css'])
        .pipe($.rename({
            basename: "site" // site.css
        }))
        .pipe(gulp.dest('dist/styles'));
});

// 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/main.scss'
  ])
    .pipe($.sourcemaps.init())
    //.pipe($.changed('.tmp/styles', {extension: '.css'}))
    .pipe($.sass({
      precision: 10,
      onError: console.error.bind(console, 'Sass error:')
    }))
    .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate and minify styles
    .pipe($.uncss({
        html: ['app/index.html']
    }))
    .pipe($.if('*.css', $.csso()))
    .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(assets)
    // 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',
        'app/styleguide.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(assets.restore())
    .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'}));
});

gulp.task('inline', function(){
  return gulp.src(['dist/index.html'])
    .pipe($.inlineSource())
    .pipe(gulp.dest('dist/'))
    .pipe($.size({title: 'inline'}));
});

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

// Watch files for changes & reload
gulp.task('serve', ['styles'], function () {
  browserSync({
    notify: false,
    // Customize the BrowserSync console logging prefix
    logPrefix: 'FQI',
    // 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']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    logPrefix: 'FQI',
    // 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'
  });
});

// Build production files, the default task
gulp.task('default', ['clean', 'serve'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

gulp.task('compile', ['clean'], function(cb) {
  runSequence('styles', ['html', 'images', 'fonts', 'copy'], function(){
    setTimeout(function(){
      runSequence('inline', 'compress', function(){
        cb();
      });
    }, 100);
  });
});

// Load custom tasks from the `tasks` directory
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
<commit_msg>Fix clean task to not delete dist build targets<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & tools we'll use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var critical = require('critical');
var pngquant = require('imagemin-pngquant');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
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/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

gulp.task('compress', function() {
  return gulp.src('dist/**/*.*')
    .pipe($.zopfli())
    .pipe(gulp.dest('dist/'));
});

// Optimize images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngquant()]
    })))
    .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',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    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('copystyles', function () {
    return gulp.src(['dist/styles/main.css'])
        .pipe($.rename({
            basename: "site" // site.css
        }))
        .pipe(gulp.dest('dist/styles'));
});

// 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/main.scss'
  ])
    .pipe($.sourcemaps.init())
    //.pipe($.changed('.tmp/styles', {extension: '.css'}))
    .pipe($.sass({
      precision: 10,
      onError: console.error.bind(console, 'Sass error:')
    }))
    .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate and minify styles
    .pipe($.uncss({
        html: ['app/index.html']
    }))
    .pipe($.if('*.css', $.csso()))
    .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(assets)
    // 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',
        'app/styleguide.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(assets.restore())
    .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'}));
});

gulp.task('inline', function(){
  return gulp.src(['dist/index.html'])
    .pipe($.inlineSource())
    .pipe(gulp.dest('dist/'))
    .pipe($.size({title: 'inline'}));
});

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

// Watch files for changes & reload
gulp.task('serve', ['styles'], function () {
  browserSync({
    notify: false,
    // Customize the BrowserSync console logging prefix
    logPrefix: 'FQI',
    // 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']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    logPrefix: 'FQI',
    // 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'
  });
});

// Build production files, the default task
gulp.task('default', ['clean', 'serve'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

gulp.task('compile', ['clean'], function(cb) {
  runSequence('styles', ['html', 'images', 'fonts', 'copy'], function(){
    setTimeout(function(){
      runSequence('inline', 'compress', function(){
        cb();
      });
    }, 100);
  });
});

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


<commit_before>var autoprefixer  = require("autoprefixer");
var calc          = require("postcss-calc");
var concat        = require("gulp-concat");
var del           = require("del");
var gulp          = require("gulp");
var imagemin      = require("gulp-imagemin");
var jade          = require("gulp-jade");
var jshint        = require("gulp-jshint");
var minifyCss     = require("gulp-minify-css");
var mixins        = require("postcss-mixins");
var nested        = require("postcss-nested");
var pxtorem       = require("postcss-pxtorem");
var postcss       = require("gulp-postcss");
var postcssImport = require("postcss-import");
var postcssUrl    = require("postcss-url");
var rev           = require("gulp-rev");
var revReplace    = require("gulp-rev-replace");
var simpleVars    = require("postcss-simple-vars");
var uglify        = require("gulp-uglify");

gulp.task("clean", function() {
    return del([
        "dist/css/*.css",
        "dist/js/*.js"
    ]);
});

gulp.task("copy-assets", function() {
    return gulp.src("node_modules/normalize.css/normalize.css")
        .pipe(gulp.dest("src/css/lib"));
});

gulp.task("images", function() {
    return gulp.src("src/img/**/*.{gif,jpg,png,svg}")
        .pipe(imagemin())
        .pipe(gulp.dest("dist/img"));
});

gulp.task("css", ["clean", "copy-assets"], function() {
    return gulp.src([
            "src/less/main.less",
            "src/less/portfolio-main.less"
        ])
        .pipe(less())
        .pipe(pixrem())
        .pipe(autoprefixer())
        .pipe(minifyCss({ "noAdvanced": true })) // noAdvanced is true so pixrem fallbacks aren't marked as duplicates and removed.
        .pipe(gulp.dest("dist/css"));
});

gulp.task("css-new", function() {
    return gulp.src([
            "src/css/main.css",
            "src/css/portfolio.css"
        ])
        .pipe(postcss([
            postcssImport,
            mixins,
            simpleVars,
            calc,
            nested,
            pxtorem({
                //  Apply pxtorem to all style properties.
                propWhiteList: []
            }),
            postcssUrl({
                url: "inline"
            }),
            autoprefixer
        ]))
        // .pipe(minifyCss())
        .pipe(gulp.dest("dist/css"));
});

gulp.task("js-lint", function() {
    return gulp.src("src/js/*.js")
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
        .pipe(jshint.reporter("fail"));
});

gulp.task("js-build-home", ["clean", "js-lint"], function() {
    return gulp.src([
            "src/js/lib/jquery-1.7.2.min.js",
            "src/js/main.js"
        ])
        .pipe(concat("main.js"))
        .pipe(uglify())
        .pipe(gulp.dest("dist/js/"));
});

gulp.task("js-build-portfolio", ["clean", "js-lint"], function() {
    return gulp.src([
            "src/js/lib/jquery-2.0.3.min.js",
            "src/js/lib/jquery.lazyload.min.js",
            "src/js/portfolio-main.js"
        ])
        .pipe(concat("portfolio-main.js"))
        .pipe(uglify())
        .pipe(gulp.dest("dist/js/"));
});

gulp.task("html", function() {
    //  Normally the locals would be out of Gulp and in a controller but this site is otherwise all static.
    var dateObj = new Date();
    var currentYear = dateObj.getFullYear();

    return gulp.src("src/views/pages/**/*.jade")
        .pipe(jade({
            "locals": {
                "currentYear": currentYear
            }
        }))
        .pipe(gulp.dest("dist/"));
});

gulp.task("revision", ["css", "js-build-home", "js-build-portfolio"], function() {
    return gulp.src([
            "dist/**/*.css",
            "dist/**/*.js"
        ])
        .pipe(rev())
        .pipe(gulp.dest("dist"))
        .pipe(rev.manifest())
        .pipe(gulp.dest("dist"));
});

gulp.task("revisionReplace", ["revision"], function() {
    var manifest = gulp.src("dist/rev-manifest.json");

    return gulp.src("dist/**/*.html")
        .pipe(revReplace({"manifest": manifest}))
        .pipe(gulp.dest("dist"));
});

gulp.task("default", [
    "clean",
    "copy-assets",
    "images",
    "css",
    "js-lint",
    "js-build-home",
    "js-build-portfolio",
    "html",
    "revision",
    "revisionReplace"
]);
<commit_msg>Added explicit function calls to PostCSS plugins that didn't have them yet, for clarity.<commit_after>var autoprefixer  = require("autoprefixer");
var calc          = require("postcss-calc");
var concat        = require("gulp-concat");
var del           = require("del");
var gulp          = require("gulp");
var imagemin      = require("gulp-imagemin");
var jade          = require("gulp-jade");
var jshint        = require("gulp-jshint");
var minifyCss     = require("gulp-minify-css");
var mixins        = require("postcss-mixins");
var nested        = require("postcss-nested");
var pxtorem       = require("postcss-pxtorem");
var postcss       = require("gulp-postcss");
var postcssImport = require("postcss-import");
var postcssUrl    = require("postcss-url");
var rev           = require("gulp-rev");
var revReplace    = require("gulp-rev-replace");
var simpleVars    = require("postcss-simple-vars");
var uglify        = require("gulp-uglify");

gulp.task("clean", function() {
    return del([
        "dist/css/*.css",
        "dist/js/*.js"
    ]);
});

gulp.task("copy-assets", function() {
    return gulp.src("node_modules/normalize.css/normalize.css")
        .pipe(gulp.dest("src/css/lib"));
});

gulp.task("images", function() {
    return gulp.src("src/img/**/*.{gif,jpg,png,svg}")
        .pipe(imagemin())
        .pipe(gulp.dest("dist/img"));
});

gulp.task("css", ["clean", "copy-assets"], function() {
    return gulp.src([
            "src/less/main.less",
            "src/less/portfolio-main.less"
        ])
        .pipe(less())
        .pipe(pixrem())
        .pipe(autoprefixer())
        .pipe(minifyCss({ "noAdvanced": true })) // noAdvanced is true so pixrem fallbacks aren't marked as duplicates and removed.
        .pipe(gulp.dest("dist/css"));
});

gulp.task("css-new", function() {
    return gulp.src([
            "src/css/main.css",
            "src/css/portfolio.css"
        ])
        .pipe(postcss([
            postcssImport(),
            mixins(),
            simpleVars(),
            calc(),
            nested(),
            pxtorem({
                //  Apply pxtorem to all style properties.
                propWhiteList: []
            }),
            postcssUrl({
                url: "inline"
            }),
            autoprefixer()
        ]))
        // .pipe(minifyCss())
        .pipe(gulp.dest("dist/css"));
});

gulp.task("js-lint", function() {
    return gulp.src("src/js/*.js")
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
        .pipe(jshint.reporter("fail"));
});

gulp.task("js-build-home", ["clean", "js-lint"], function() {
    return gulp.src([
            "src/js/lib/jquery-1.7.2.min.js",
            "src/js/main.js"
        ])
        .pipe(concat("main.js"))
        .pipe(uglify())
        .pipe(gulp.dest("dist/js/"));
});

gulp.task("js-build-portfolio", ["clean", "js-lint"], function() {
    return gulp.src([
            "src/js/lib/jquery-2.0.3.min.js",
            "src/js/lib/jquery.lazyload.min.js",
            "src/js/portfolio-main.js"
        ])
        .pipe(concat("portfolio-main.js"))
        .pipe(uglify())
        .pipe(gulp.dest("dist/js/"));
});

gulp.task("html", function() {
    //  Normally the locals would be out of Gulp and in a controller but this site is otherwise all static.
    var dateObj = new Date();
    var currentYear = dateObj.getFullYear();

    return gulp.src("src/views/pages/**/*.jade")
        .pipe(jade({
            "locals": {
                "currentYear": currentYear
            }
        }))
        .pipe(gulp.dest("dist/"));
});

gulp.task("revision", ["css", "js-build-home", "js-build-portfolio"], function() {
    return gulp.src([
            "dist/**/*.css",
            "dist/**/*.js"
        ])
        .pipe(rev())
        .pipe(gulp.dest("dist"))
        .pipe(rev.manifest())
        .pipe(gulp.dest("dist"));
});

gulp.task("revisionReplace", ["revision"], function() {
    var manifest = gulp.src("dist/rev-manifest.json");

    return gulp.src("dist/**/*.html")
        .pipe(revReplace({"manifest": manifest}))
        .pipe(gulp.dest("dist"));
});

gulp.task("default", [
    "clean",
    "copy-assets",
    "images",
    "css",
    "js-lint",
    "js-build-home",
    "js-build-portfolio",
    "html",
    "revision",
    "revisionReplace"
]);
<|endoftext|>


<commit_before>/****************************
 HTML Email Builder
 Max Lapides
 September 2014
****************************/

'use strict';

// includes
var gulp           = require('gulp');
var fse            = require('fs-extra');
var path           = require('path');
var _              = require('lodash');
var q              = require('q');
var entityconvert  = require('entity-convert');
var sass           = require('node-sass');
var css            = require('css');
var cssc           = require('css-condense');
var chalk          = require('chalk');
var browserSync    = require('browser-sync');
var handlebars     = require('handlebars');
var cheerio        = require('cheerio');
var juice          = require('juice');

var configClass = require('./lib/config.js');
var config      = new configClass(__dirname);

var templateInfoClass = require('./lib/templateInfo.js');
var templateInfo      = new templateInfoClass(config);

// globals
var devBuildsOn  = true;
var prodBuildsOn = true;

/*** GULP TASKS ***/

gulp.task('default', ['start']);
gulp.task('dev-only', ['disableProdBuilds', 'start']);
gulp.task('prod-only', ['disableDevBuilds', 'start']);

gulp.task('start', ['compile', 'watch']);

gulp.task('compile', compile);

gulp.task('watch', function() {
	gulp.watch(config.commonDir+'/**/*', compile);
	gulp.watch(config.templatesDir+'/**/*', compile);
});

gulp.task('disableDevBuilds', function() {
	devBuildsOn = false;

});

gulp.task('disableProdBuilds', function() {
	prodBuildsOn = false;
});

/*** BUILD METHODS ***/

function compile(event) {
	templateInfo.getTplNames(event.path)
		.then(generateEmails)
		.then(reload)
		.done();
}

function generateEmails(templates) {

	var defer = q.defer();
	var allPromises = [];

	_.each(templates, function(tplName) {

		var promise = prepareBuild(tplName)
			.then(buildHTMLEmail)
			.then(buildTextEmail)
			.then(cleanSpecialChars)
			.then(injectResetStyles)
			.then(saveEmails);

		allPromises.push(promise);

	});

	q.all(allPromises).then(function() {
		defer.resolve();
		logSuccess('Emails compiled and saved.');
	});

	return defer.promise;

}

function prepareBuild(tplName) {

	var defer = q.defer();

	defer.resolve({
		tplName : tplName
	});

	return defer.promise;

}

function buildHTMLEmail(args) {

	var defer = q.defer();

	var htmlPromise = compileHandlebars(args.tplName);
	var stylesPromise = compileMainStyles(args.tplName);

	q.all([htmlPromise, stylesPromise]).then(function(compiled) {

		var html = compiled[0];
		var styles = compiled[1];

		var inlineStyles = styles.styles;
		var responsiveStyles = styles.mediaQueries;

		// inline styles
		inlineCSS(html, inlineStyles)

			// inject responsive styles
			.then(function(html) {
				return injectInternalStyles(html, responsiveStyles);
			})

			// save HTML
			.then(function(html) {
				args.html = html;
				defer.resolve(args);
			});

	});

	return defer.promise;

}

function inlineCSS(html, styles) {

	var defer = q.defer();

	// inline styles using Juice
	html = juice.inlineContent(html, styles);

	// add DOCTYPE
	// this is a bug in Juice, hopefully it will be patched soon
	var doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n';
	html = html.trim();
	if(_.indexOf(html.toLowerCase(), '<!doctype') < 0) {
		html = doctype + html;
	}

	defer.resolve(html);
	return defer.promise;
}

function buildTextEmail(args) {

	var defer = q.defer();

	// @todo: compile text version
	args.text = '';

	defer.resolve(args);

	return defer.promise;

}

function compileHandlebars(tplName) {

	var defer = q.defer();

	// get the paths for the Handlebars code and the data
	var hbsPath = path.join(config.templatesDir, tplName, 'html.handlebars');
	var dataPath = path.join(config.templatesDir, tplName, 'content.json');

	// get the Handlebars code and the data
	var allPromises = [
		getFile(hbsPath),
		getFile(dataPath)
	];

	// compile the HTML template
	q.all(allPromises).then(function(sources) {

		var hbs = sources[0];
		var data = JSON.parse(sources[1]);

		if(!hbs) {
			var error = tplName + ' could not find html.handlebars';
			logError(2, error);
			defer.reject(new Error(error));
		}

		var template = handlebars.compile(hbs);
		var html = template(data ? data : null);

		defer.resolve(html);

	});

	return defer.promise;

}

function getFile(path) {

	var defer = q.defer();

	fse.readFile(path, 'utf-8', function(error, source) {
		defer.resolve(error ? false : source);
	});

	return defer.promise;

}

function compileMainStyles(tplName) {

	var defer = q.defer();

	var sassPath = path.join(config.templatesDir, tplName, 'style.scss');

	compileSass(sassPath)
		.then(condenseCSS)
		.then(separateMediaQueries)
		.then(defer.resolve);

	return defer.promise;

}

function condenseCSS(styles) {

	var defer = q.defer();

	var compressedCSS = cssc.compress(styles, {
		consolidateViaSelectors    : false,
		consolidateViaDeclarations : false,
		sort                       : false
	});

	defer.resolve(compressedCSS);

	return defer.promise;

}

function separateMediaQueries(styles) {

	var defer = q.defer();

	var ast = css.parse(styles);
	var mqast = css.parse('');

	var mediaQuery;
	var rules = ast.stylesheet.rules;

	for(var i = 0; i < rules.length; i++) {
		if(rules[i].type === 'media') {
			mediaQuery = _.first(rules.splice(i, 1));
			mqast = addStyleRuleToAST(mqast, mediaQuery);
		}
	}

	defer.resolve({
		styles       : css.stringify(ast, {compress: true, sourcemap: false}),
		mediaQueries : css.stringify(mqast, {compress: true, sourcemap: false})
	});

	return defer.promise;

}

function addStyleRuleToAST(ast, rule) {
	ast.stylesheet.rules.push(rule);
	return ast;
}

function cleanSpecialChars(args) {

	var defer = q.defer();

	// convert special characters to HTML entities
	args.html = entityconvert.html(args.html);

	// replace non-ASCII characters with ASCII equivalents
	args.text = args.text
		.replace(/[\u2018\u2019]/g, '\'')
		.replace(/[\u201C\u201D]/g, '"')
		.replace(/[\u2013\u2014]/g, '-')
		.replace(/[\u2026]/g, '...')
		.replace(/[^\x00-\x7F]/g, ''); // removes any remaining non-ASCII characters

	defer.resolve(args);

	return defer.promise;

}

function injectResetStyles(args) {

	var defer = q.defer();

	// look for custom reset styles first
	var resetPath = path.join(config.templatesDir, args.tplName, 'reset.scss');

	fse.exists(resetPath, function(exists) {

		// if custom reset styles don't exist, use the common reset styles
		if(!exists) {
			resetPath = path.join(config.commonDir, 'reset.scss');
		}

		// compile the reset styles
		compileSass(resetPath)

			// inject the reset styles
			.then(function(styles) {
				return injectInternalStyles(args.html, styles);
			})

			// resolve the promise with the updated HTML
			.then(function(html) {
				args.html = html;
				defer.resolve(args);
			});

	});

	return defer.promise;

}

function injectInternalStyles(html, styles) {

	var defer = q.defer();

	var $ = cheerio.load(html);

	if(!$('head style').length) {
		$('head').append('<style type="text/css"></style>');
	}

	$('head style').append(styles);

	defer.resolve($.html());

	return defer.promise;

}

function compileSass(sassPath) {

	var defer = q.defer();

	sass.render({
		file: sassPath,
		//outputStyle: devMode ? 'expanded' : 'compressed',
		success: function(styles) {
			defer.resolve(styles);
		},
		error: function(error) {
			logError(3, error);
			defer.reject(new Error(error));
		}
	});

	return defer.promise;

}

function saveEmails(emails) {
	saveEmail(emails.html, emails.tplName, 'html');
	saveEmail(emails.text, emails.tplName, 'txt');
}

function saveEmail(email, tplName, extension) {
	var defer = q.defer();
	var path = getBuildPath(tplName, extension);
	fse.outputFile(path, email, outputFileCb(path, defer));
	return defer.promise;
}

function getBuildPath(tplName, extension) {
	return path.join(config.buildDir, tplName, tplName+'.'+extension);
}

function outputFileCb(filePath, defer) {

	var cb = function(error) {
		if(error) {
			logError(4, 'Failed to save file: ' + filePath);
			defer.reject(new Error(error));
		}
		else {
			defer.resolve();
		}
	};

	return cb;

}

function reload() {

	var defer = q.defer();

	if(browserSync.active) {
		browserSync.reload();
	}

	else {
		startServer();
	}

	return defer.promise;

}

function startServer() {
	browserSync({
		server: {
			baseDir: 'build',
			directory: true
		}
	});
}

function logSuccess(msg) {
	console.log(chalk.bold.green('Success!') + ' ' + msg);
}

function logError(errCode, msg) {
	console.log(chalk.bold.red('Error ' + errCode + ':') + ' ' + msg);
}
<commit_msg>Add support for reset-inline and reset-head<commit_after>/****************************
 HTML Email Builder
 Max Lapides
 September 2014
****************************/

'use strict';

// includes
var gulp           = require('gulp');
var fse            = require('fs-extra');
var path           = require('path');
var _              = require('lodash');
var q              = require('q');
var entityconvert  = require('entity-convert');
var sass           = require('node-sass');
var css            = require('css');
var cssc           = require('css-condense');
var chalk          = require('chalk');
var browserSync    = require('browser-sync');
var handlebars     = require('handlebars');
var cheerio        = require('cheerio');
var juice          = require('juice');

var configClass = require('./lib/config.js');
var config      = new configClass(__dirname);

var templateInfoClass = require('./lib/templateInfo.js');
var templateInfo      = new templateInfoClass(config);

// globals
var devBuildsOn  = true;
var prodBuildsOn = true;

/*** GULP TASKS ***/

gulp.task('default', ['start']);
gulp.task('dev-only', ['disableProdBuilds', 'start']);
gulp.task('prod-only', ['disableDevBuilds', 'start']);

gulp.task('start', ['compile', 'watch']);

gulp.task('compile', compile);

gulp.task('watch', function() {
	gulp.watch(config.commonDir+'/**/*', compile);
	gulp.watch(config.templatesDir+'/**/*', compile);
});

gulp.task('disableDevBuilds', function() {
	devBuildsOn = false;

});

gulp.task('disableProdBuilds', function() {
	prodBuildsOn = false;
});

/*** BUILD METHODS ***/

function compile(event) {
	templateInfo.getTplNames(event.path)
		.then(generateEmails)
		.then(reload)
		.done();
}

function generateEmails(templates) {

	var defer = q.defer();
	var allPromises = [];

	_.each(templates, function(tplName) {

		var promise = prepareBuild(tplName)
			.then(buildHTMLEmail)
			.then(buildTextEmail)
			.then(cleanSpecialChars)
			.then(injectHeadResetStyles)
			.then(saveEmails);

		allPromises.push(promise);

	});

	q.all(allPromises).then(function() {
		defer.resolve();
		logSuccess('Emails compiled and saved.');
	});

	return defer.promise;

}

function prepareBuild(tplName) {

	var defer = q.defer();

	defer.resolve({
		tplName : tplName
	});

	return defer.promise;

}

function buildHTMLEmail(args) {

	var defer = q.defer();

	var htmlPromise = compileHandlebars(args.tplName);
	var stylesPromise = compileMainStyles(args.tplName);
	var inlineResetStylesPromise = compileInlineResetStyles();

	var allPromises = [htmlPromise, stylesPromise, inlineResetStylesPromise];

	q.all(allPromises).then(function(compiled) {

		var html = compiled[0];
		var styles = compiled[1];
		var inlineResetStyles = compiled[2];

		var tplInlineStyles = styles.styles;
		var responsiveStyles = styles.mediaQueries;

		var allInlineStyles = inlineResetStyles + tplInlineStyles;

		// inline styles
		inlineCSS(html, allInlineStyles)

			// inject responsive styles
			.then(function(html) {
				return injectInternalStyles(html, responsiveStyles);
			})

			// save HTML
			.then(function(html) {
				args.html = html;
				defer.resolve(args);
			});

	});

	return defer.promise;

}

function inlineCSS(html, styles) {

	var defer = q.defer();

	// inline styles using Juice
	html = juice.inlineContent(html, styles);

	// add DOCTYPE
	// this is a bug in Juice, hopefully it will be patched soon
	var doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n';
	html = html.trim();
	if(_.indexOf(html.toLowerCase(), '<!doctype') < 0) {
		html = doctype + html;
	}

	defer.resolve(html);
	return defer.promise;
}

function buildTextEmail(args) {

	var defer = q.defer();

	// @todo: compile text version
	args.text = '';

	defer.resolve(args);

	return defer.promise;

}

function compileHandlebars(tplName) {

	var defer = q.defer();

	// get the paths for the Handlebars code and the data
	var hbsPath = path.join(config.templatesDir, tplName, 'html.handlebars');
	var dataPath = path.join(config.templatesDir, tplName, 'content.json');

	// get the Handlebars code and the data
	var allPromises = [
		getFile(hbsPath),
		getFile(dataPath)
	];

	// compile the HTML template
	q.all(allPromises).then(function(sources) {

		var hbs = sources[0];
		var data = JSON.parse(sources[1]);

		if(!hbs) {
			var error = tplName + ' could not find html.handlebars';
			logError(2, error);
			defer.reject(new Error(error));
		}

		var template = handlebars.compile(hbs);
		var html = template(data ? data : null);

		defer.resolve(html);

	});

	return defer.promise;

}

function getFile(path) {

	var defer = q.defer();

	fse.readFile(path, 'utf-8', function(error, source) {
		defer.resolve(error ? false : source);
	});

	return defer.promise;

}

function compileMainStyles(tplName) {

	var defer = q.defer();

	var sassPath = path.join(config.templatesDir, tplName, 'style.scss');

	compileSass(sassPath)
		.then(condenseCSS)
		.then(separateMediaQueries)
		.then(defer.resolve);

	return defer.promise;

}

function compileInlineResetStyles() {
	var inlineResetStylesPath = path.join(config.commonDir, 'reset-inline.scss');
	return compileSass(inlineResetStylesPath);
}

function condenseCSS(styles) {

	var defer = q.defer();

	var compressedCSS = cssc.compress(styles, {
		consolidateViaSelectors    : false,
		consolidateViaDeclarations : false,
		sort                       : false
	});

	defer.resolve(compressedCSS);

	return defer.promise;

}

function separateMediaQueries(styles) {

	var defer = q.defer();

	var ast = css.parse(styles);
	var mqast = css.parse('');

	var mediaQuery;
	var rules = ast.stylesheet.rules;

	for(var i = 0; i < rules.length; i++) {
		if(rules[i].type === 'media') {
			mediaQuery = _.first(rules.splice(i, 1));
			mqast = addStyleRuleToAST(mqast, mediaQuery);
		}
	}

	defer.resolve({
		styles       : css.stringify(ast, {compress: true, sourcemap: false}),
		mediaQueries : css.stringify(mqast, {compress: true, sourcemap: false})
	});

	return defer.promise;

}

function addStyleRuleToAST(ast, rule) {
	ast.stylesheet.rules.push(rule);
	return ast;
}

function cleanSpecialChars(args) {

	var defer = q.defer();

	// convert special characters to HTML entities
	args.html = entityconvert.html(args.html);

	// replace non-ASCII characters with ASCII equivalents
	args.text = args.text
		.replace(/[\u2018\u2019]/g, '\'')
		.replace(/[\u201C\u201D]/g, '"')
		.replace(/[\u2013\u2014]/g, '-')
		.replace(/[\u2026]/g, '...')
		.replace(/[^\x00-\x7F]/g, ''); // removes any remaining non-ASCII characters

	defer.resolve(args);

	return defer.promise;

}

function injectHeadResetStyles(args) {

	var defer = q.defer();

	// look for custom reset styles first
	var resetPath = path.join(config.templatesDir, args.tplName, 'reset-head.scss');

	fse.exists(resetPath, function(exists) {

		// if custom reset styles don't exist, use the common reset styles
		if(!exists) {
			resetPath = path.join(config.commonDir, 'reset-head.scss');
		}

		// compile the reset styles
		compileSass(resetPath)

			// inject the reset styles
			.then(function(styles) {
				return injectInternalStyles(args.html, styles);
			})

			// resolve the promise with the updated HTML
			.then(function(html) {
				args.html = html;
				defer.resolve(args);
			});

	});

	return defer.promise;

}

function injectInternalStyles(html, styles) {

	var defer = q.defer();

	var $ = cheerio.load(html);

	if(!$('head style').length) {
		$('head').append('<style type="text/css"></style>');
	}

	$('head style').append(styles);

	defer.resolve($.html());

	return defer.promise;

}

function compileSass(sassPath) {

	var defer = q.defer();

	sass.render({
		file: sassPath,
		//outputStyle: devMode ? 'expanded' : 'compressed',
		success: function(styles) {
			defer.resolve(styles);
		},
		error: function(error) {
			logError(3, error);
			defer.reject(new Error(error));
		}
	});

	return defer.promise;

}

function saveEmails(emails) {
	saveEmail(emails.html, emails.tplName, 'html');
	saveEmail(emails.text, emails.tplName, 'txt');
}

function saveEmail(email, tplName, extension) {
	var defer = q.defer();
	var path = getBuildPath(tplName, extension);
	fse.outputFile(path, email, outputFileCb(path, defer));
	return defer.promise;
}

function getBuildPath(tplName, extension) {
	return path.join(config.buildDir, tplName, tplName+'.'+extension);
}

function outputFileCb(filePath, defer) {

	var cb = function(error) {
		if(error) {
			logError(4, 'Failed to save file: ' + filePath);
			defer.reject(new Error(error));
		}
		else {
			defer.resolve();
		}
	};

	return cb;

}

function reload() {

	var defer = q.defer();

	if(browserSync.active) {
		browserSync.reload();
	}

	else {
		startServer();
	}

	return defer.promise;

}

function startServer() {
	browserSync({
		server: {
			baseDir: 'build',
			directory: true
		}
	});
}

function logSuccess(msg) {
	console.log(chalk.bold.green('Success!') + ' ' + msg);
}

function logError(errCode, msg) {
	console.log(chalk.bold.red('Error ' + errCode + ':') + ' ' + msg);
}
<|endoftext|>


<commit_before>var gulp   = require('gulp');
var jshint = require('gulp-jshint');
var less   = require('gulp-less');
var path   = require('path');
var app    = require('./app');
var debug  = require('debug')('podplay:server');
var http   = require('http');

// compile less stylesheets
gulp.task('style', function() {
  return gulp.src('./styles/**/*.less')
    .pipe(less({
      paths: [ path.join(__dirname, 'styles', 'includes') ]
    }))
    .pipe(gulp.dest('./public/stylesheets'));
});

// lint javascript
gulp.task('lint', function() {
  return gulp.src('./public/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default')); // maybe install a better reporter
});

// run the express server
gulp.task('serve', function() {
  var port = '80';
  app.set('port', port);

  var server = http.createServer(app);

  server.listen(port);
  console.log('server running on port ' + port);
  server.on('error', function(error) {

    if (error.syscall !== 'listen') {
      throw error;
    }

    switch (error.code) {
      case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
      case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
      default:
        throw error;
    }
  });

  server.on('listening', function() {
    var addr = server.address();
    var bind = typeof addr === 'string'
      ? 'pipe ' + addr
      : 'port ' + addr.port;
    debug('Listening on ' + bind);
  });

})

// build less, lint JS and run application
gulp.task('default', ['style', 'lint', 'serve'], function() {
  console.log('all done');
});

<commit_msg>Revert "Changed port back to 80 for master branch"<commit_after>var gulp   = require('gulp');
var jshint = require('gulp-jshint');
var less   = require('gulp-less');
var path   = require('path');
var app    = require('./app');
var debug  = require('debug')('podplay:server');
var http   = require('http');

// compile less stylesheets
gulp.task('style', function() {
  return gulp.src('./styles/**/*.less')
    .pipe(less({
      paths: [ path.join(__dirname, 'styles', 'includes') ]
    }))
    .pipe(gulp.dest('./public/stylesheets'));
});

// lint javascript
gulp.task('lint', function() {
  return gulp.src('./public/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default')); // maybe install a better reporter
});

// run the express server
gulp.task('serve', function() {
  var port = '8080';
  app.set('port', port);

  var server = http.createServer(app);

  server.listen(port);
  console.log('server running on port ' + port);
  server.on('error', function(error) {

    if (error.syscall !== 'listen') {
      throw error;
    }

    switch (error.code) {
      case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
      case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
      default:
        throw error;
    }
  });

  server.on('listening', function() {
    var addr = server.address();
    var bind = typeof addr === 'string'
      ? 'pipe ' + addr
      : 'port ' + addr.port;
    debug('Listening on ' + bind);
  });

})

// build less, lint JS and run application
gulp.task('default', ['style', 'lint', 'serve'], function() {
  console.log('all done');
});

<|endoftext|>


<commit_before>'use strict';

const es = require('event-stream');
const del = require('del');
const browserSync = require('browser-sync').create();

const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const mqpacker = require('css-mqpacker');
const csswring = require('csswring');

const gulp = require('gulp');
const aigis = require('gulp-aigis');
const concat = require('gulp-concat');
const consolidate = require('gulp-consolidate');
const iconfont = require('gulp-iconfont');
const plumber = require('gulp-plumber');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const awspublish = require('gulp-awspublish');

gulp.task('serve', function() {
  browserSync.init({
    server: {
      baseDir: './',
      directory: true,
    },
    files: ['build'],
    notify: false,
    open: false,
  });
});

gulp.task('clean', function() {
  return del('./build/');
});

x;
gulp.task('copy-font', function() {
  return gulp
    .src(['./src/assets2/font/zero-width.woff'])
    .pipe(gulp.dest('./build/assets2/font/'));
});

gulp.task('copy-img', function() {
  return gulp
    .src(['./src/assets2/img/*/**'])
    .pipe(gulp.dest('./build/assets2/img/'));
});

gulp.task('copy-static', function() {
  return gulp.src(['./static/*/**']).pipe(gulp.dest('./build/'));
});

gulp.task('js', function() {
  return gulp
    .src([
      './src/assets2/js/vendor/EventDispatcher.js',
      './src/assets2/js/vendor/prism.js',
      './src/assets2/js/prism.extend.js',
      './src/assets2/js/CG2.js',
      './src/assets2/js/CG2-pageHeader.js',
      './src/assets2/js/CG2-drawer.js',
      './src/assets2/js/CG2-compactNav.js',
      './src/assets2/js/CG2-tab.js',
      './src/assets2/js/CG2-articleSeriesNav.js',
      './src/assets2/js/CG2-livecode.js',
      './src/assets2/js/CG2-forms.js',
      './src/assets2/js/old-jade-click-to-play.js',
      './src/assets2/js/old-jade-prism.js',
    ])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(concat('codegrid-ui.js'))
    .pipe(gulp.dest('./build/assets2/js/'))
    .pipe(uglify())
    .pipe(rename({ extname: '.min.js' }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./build/assets2/js/'));
});

gulp.task('css', function() {
  return gulp
    .src([
      './src/assets2/scss/codegrid-ui.scss',
      './src/assets2/scss/codegrid-ui-core.scss',
      './src/assets2/scss/codegrid-ui-www.scss',
    ])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(postcss([autoprefixer({ supports: false })]))
    .pipe(gulp.dest('./build/assets2/css/'))
    .pipe(postcss([mqpacker(), csswring()]))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./build/assets2/css/'));
});

gulp.task('iconfont', function() {
  const fontName = 'codegrid-icon';

  return gulp
    .src(['./src/assets2/font/codegrid-icon/*.svg'])
    .pipe(
      iconfont({
        fontName: fontName,
        formats: ['woff', 'woff2'],
        appendCodepoints: true,
      })
    )
    .on('glyphs', function(glyphs, options) {
      gulp
        .src([
          './src/assets2/font/codegrid-icon/_icon.scss',
          './src/assets2/font/codegrid-icon/_icon-utils.scss',
        ])
        .pipe(
          consolidate('underscore', {
            glyphs: glyphs,
            fontName: fontName,
            fontPath: '../font/',
            prefix: 'CG2-icon',
          })
        )
        .pipe(gulp.dest('./src/assets2/scss/'));
    })
    .pipe(gulp.dest('./build/assets2/font/'));
});

gulp.task('numfont', function() {
  const fontName = 'codegrid-num';

  return gulp
    .src(['./src/assets2/font/codegrid-num/*.svg'])
    .pipe(
      iconfont({
        fontName: fontName,
        formats: ['woff', 'woff2'],
        fontHeight: 256,
        descent: 24,
      })
    )
    .pipe(gulp.dest('./build/assets2/font/'));
});

gulp.task('guide', function() {
  return gulp.src('./aigis_config.yml').pipe(aigis());
});

// todo: スタイルガイドのHTMLの変更を検知して更新するタスク
// todo: アイコンフォント用SVGファイルの変更を検知するタスク（要るかな）

gulp.task('watch:css', function() {
  return gulp.watch('./src/assets2/scss/**/*.scss', gulp.series('css'));
});

gulp.task('watch:js', function() {
  return gulp.watch('./src/assets2/js/**/*.js', gulp.series('js'));
});

gulp.task('watch', gulp.parallel('watch:css', 'watch:js'));

gulp.task(
  'default',
  gulp.series(
    'iconfont',
    gulp.parallel(
      'numfont',
      'copy-font',
      'copy-img',
      'copy-static',
      'js',
      'css'
    ),
    gulp.parallel('watch', 'serve')
  )
);

gulp.task(
  'build',
  gulp.series(
    'clean',
    'iconfont',
    gulp.parallel(
      'numfont',
      'copy-font',
      'copy-img',
      'copy-static',
      'js',
      'css'
    ),
    'guide'
  )
);

gulp.task('deploy', function() {
  const publisher = awspublish.create({
    params: {
      Bucket: 'ui.codegrid.net',
    },
    endpoint: 's3-ap-northeast-1.amazonaws.com',
  });

  gulp
    .src('./build/**/*')
    .pipe(publisher.publish())
    .pipe(publisher.sync())
    .pipe(awspublish.reporter());
});
<commit_msg>gulpfile: アロー関数に<commit_after>'use strict';

const es = require('event-stream');
const del = require('del');
const browserSync = require('browser-sync').create();

const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const mqpacker = require('css-mqpacker');
const csswring = require('csswring');

const gulp = require('gulp');
const aigis = require('gulp-aigis');
const concat = require('gulp-concat');
const consolidate = require('gulp-consolidate');
const iconfont = require('gulp-iconfont');
const plumber = require('gulp-plumber');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const awspublish = require('gulp-awspublish');

gulp.task('serve', () => {
  browserSync.init({
    server: {
      baseDir: './',
      directory: true,
    },
    files: ['build'],
    notify: false,
    open: false,
  });
});

gulp.task('clean', () => {
  return del('./build/');
});

gulp.task('copy-font', () => {
  return gulp
    .src(['./src/assets2/font/zero-width.woff'])
    .pipe(gulp.dest('./build/assets2/font/'));
});

gulp.task('copy-img', () => {
  return gulp
    .src(['./src/assets2/img/*/**'])
    .pipe(gulp.dest('./build/assets2/img/'));
});

gulp.task('copy-static', () => {
  return gulp.src(['./static/*/**']).pipe(gulp.dest('./build/'));
});

gulp.task('js', () => {
  return gulp
    .src([
      './src/assets2/js/vendor/EventDispatcher.js',
      './src/assets2/js/vendor/prism.js',
      './src/assets2/js/prism.extend.js',
      './src/assets2/js/CG2.js',
      './src/assets2/js/CG2-pageHeader.js',
      './src/assets2/js/CG2-drawer.js',
      './src/assets2/js/CG2-compactNav.js',
      './src/assets2/js/CG2-tab.js',
      './src/assets2/js/CG2-articleSeriesNav.js',
      './src/assets2/js/CG2-livecode.js',
      './src/assets2/js/CG2-forms.js',
      './src/assets2/js/old-jade-click-to-play.js',
      './src/assets2/js/old-jade-prism.js',
    ])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(concat('codegrid-ui.js'))
    .pipe(gulp.dest('./build/assets2/js/'))
    .pipe(uglify())
    .pipe(rename({ extname: '.min.js' }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./build/assets2/js/'));
});

gulp.task('css', () => {
  return gulp
    .src([
      './src/assets2/scss/codegrid-ui.scss',
      './src/assets2/scss/codegrid-ui-core.scss',
      './src/assets2/scss/codegrid-ui-www.scss',
    ])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(postcss([autoprefixer({ supports: false })]))
    .pipe(gulp.dest('./build/assets2/css/'))
    .pipe(postcss([mqpacker(), csswring()]))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./build/assets2/css/'));
});

gulp.task('iconfont', () => {
  const fontName = 'codegrid-icon';

  return gulp
    .src(['./src/assets2/font/codegrid-icon/*.svg'])
    .pipe(
      iconfont({
        fontName: fontName,
        formats: ['woff', 'woff2'],
        appendCodepoints: true,
      })
    )
    .on('glyphs', (glyphs, options) => {
      gulp
        .src([
          './src/assets2/font/codegrid-icon/_icon.scss',
          './src/assets2/font/codegrid-icon/_icon-utils.scss',
        ])
        .pipe(
          consolidate('underscore', {
            glyphs: glyphs,
            fontName: fontName,
            fontPath: '../font/',
            prefix: 'CG2-icon',
          })
        )
        .pipe(gulp.dest('./src/assets2/scss/'));
    })
    .pipe(gulp.dest('./build/assets2/font/'));
});

gulp.task('numfont', () => {
  const fontName = 'codegrid-num';

  return gulp
    .src(['./src/assets2/font/codegrid-num/*.svg'])
    .pipe(
      iconfont({
        fontName: fontName,
        formats: ['woff', 'woff2'],
        fontHeight: 256,
        descent: 24,
      })
    )
    .pipe(gulp.dest('./build/assets2/font/'));
});

gulp.task('guide', () => {
  return gulp.src('./aigis_config.yml').pipe(aigis());
});

// todo: スタイルガイドのHTMLの変更を検知して更新するタスク
// todo: アイコンフォント用SVGファイルの変更を検知するタスク（要るかな）

gulp.task('watch:css', () => {
  return gulp.watch('./src/assets2/scss/**/*.scss', gulp.series('css'));
});

gulp.task('watch:js', () => {
  return gulp.watch('./src/assets2/js/**/*.js', gulp.series('js'));
});

gulp.task('watch', gulp.parallel('watch:css', 'watch:js'));

gulp.task(
  'default',
  gulp.series(
    'iconfont',
    gulp.parallel(
      'numfont',
      'copy-font',
      'copy-img',
      'copy-static',
      'js',
      'css'
    ),
    gulp.parallel('watch', 'serve')
  )
);

gulp.task(
  'build',
  gulp.series(
    'clean',
    'iconfont',
    gulp.parallel(
      'numfont',
      'copy-font',
      'copy-img',
      'copy-static',
      'js',
      'css'
    ),
    'guide'
  )
);

gulp.task('deploy', () => {
  const publisher = awspublish.create({
    params: {
      Bucket: 'ui.codegrid.net',
    },
    endpoint: 's3-ap-northeast-1.amazonaws.com',
  });

  gulp
    .src('./build/**/*')
    .pipe(publisher.publish())
    .pipe(publisher.sync())
    .pipe(awspublish.reporter());
});
<|endoftext|>


<commit_before>var gulp = require('gulp')
var gutil = require('gulp-util')
var concat = require('gulp-concat')
var connect = require('gulp-connect')
var iconfont = require('gulp-iconfont')
var iconfontCSS = require("gulp-iconfont-css")
var jshint = require('gulp-jshint')
var karma = require('gulp-karma')
var ngAnnotate = require('gulp-ng-annotate')
var plumber = require('gulp-plumber')
var rimraf = require('rimraf')
var sourcemaps = require('gulp-sourcemaps')
var sass = require('gulp-sass')
var streamqueue = require('streamqueue')
var templateCache = require('gulp-angular-templatecache')
var uglify = require('gulp-uglify')

//
// Variables
//
var srcDir = './src';
var distDir = './dist';
var vendorDir = './bower_components';
var isDebug = !gutil.env.prod;

var vendorFiles = [
  vendorDir + '/jquery/dist/jquery.js',
  vendorDir + '/lodash/dist/lodash.js',
  vendorDir + '/string/lib/string.js',
  vendorDir + '/angular/angular.js',
  vendorDir + '/angular-ui-router/release/angular-ui-router.js',
  vendorDir + '/angular-gravatar/build/md5.js',
  vendorDir + '/angular-gravatar/build/angular-gravatar.js',
  vendorDir + '/angular-hotkeys/build/hotkeys.js',
  vendorDir + '/ngInfiniteScroll/build/ng-infinite-scroll.js',
  vendorDir + '/angular-elastic/elastic.js',
  vendorDir + '/angular-scroll/angular-scroll.js',
];
var sourceFiles = [
  srcDir + '/app.js',
  srcDir + '/**/*.js',
  '!' + srcDir + '/public/**/*.js',
];
var testFiles = [
  'bower_components/angular-mocks/angular-mocks.js',
  'test/**/*.js'
];

//
// Default
//
gulp.task('default', ['build'], function() {
  gulp.start('watch');
});

//
// Clean
//
gulp.task('clean', function(cb) {
  rimraf(distDir, cb);
});

//
// Build
//
gulp.task('build', ['clean'], function() {
  gulp.start('scripts', 'styles', 'public', 'templates');
});

//
// Watch
//
gulp.task('watch', ['server'], function() {
  gulp.watch(srcDir + '/**/*.js', ['scripts']);

  gulp.watch(srcDir + '/**/*.scss', ['styles']);

  gulp.watch(srcDir + '/public/**/*', ['public']);

  gulp.watch(srcDir + '/views/**/*', ['templates']);

  gulp.src(vendorFiles.concat(sourceFiles).concat(testFiles))
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'watch'
    }));
});

//
// Server
//
gulp.task('server', function() {
  connect.server({
    root: distDir,
    port: 3000,
    livereload: false
  });
});

//
// Assets
//
gulp.task('public', function () {
  // Versionned assets
  gulp.src(srcDir + '/public/**/*')
    .pipe(gulp.dest(distDir))

  // Flags icons
  gulp.src(vendorDir + '/flag-icon-css/flags/**/*')
    .pipe(gulp.dest(distDir + '/images/flags'))
})

//
// Templates
//
gulp.task('templates', function () {
  gulp.src(srcDir + '/views/**/*')
    .pipe(gulp.dest(distDir + '/views'))
})

//
// Javascript
//
gulp.task('scripts', function () {
  var bootstrap = gulp.src(srcDir + '/bootstrap.js');

  var vendor = gulp.src(vendorFiles)

  var src = gulp.src(sourceFiles)
    .pipe(plumber())
    .pipe(ngAnnotate())

  // Combine into a single app script
  var queue = new streamqueue({ objectMode: true })
    .queue(bootstrap)
    .queue(vendor)
    .queue(src)

  // Inline templates in prod mode
  if (!isDebug) {
    var templates = gulp.src(srcDir + '/views/*.html')
      .pipe(templateCache('templates.js', {
        standalone: true,
        root: 'views',
      }))

    queue.queue(templates)
  }

  queue.done()
    .pipe(sourcemaps.init())
      .pipe(concat('app.js', {newLine: ';'}))
      // .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(distDir))
})

//
// Stylesheet
//
gulp.task('styles', function () {
  gulp.src(srcDir + '/styles/app.scss')
    .pipe(plumber())
    .pipe(sass())
    .pipe(gulp.dest(distDir))
})

//
// Icons
//
gulp.task('icons', function(){
  gulp.src([srcDir + '/icons/*.svg'])
    .pipe(iconfontCSS({
      fontName : 'icons',
      // path: 'scss',
      path: srcDir + '/styles/templates/icons.scss',
      targetPath: '../../styles/icons.scss',
      fontPath: '../fonts/' // relative path
    }))
    .pipe(iconfont({
      fontName: 'icons',
      // fixedWidth: true,
      normalize: true
    }))
    .pipe(gulp.dest(srcDir + '/public/fonts'));
});

//
// Lint
//
gulp.task('lint', function() {
  return gulp.src(sourceFiles)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

//
// Test
//
gulp.task('test', function (done) {
  var files = [srcDir + '/bootstrap.js']
    .concat(vendorFiles)
    .concat(sourceFiles)
    .concat(testFiles)

  return gulp.src(files)
    .pipe(karma({
      configFile: __dirname + '/karma.conf.js',
      action: 'run'
    }))
    .on('error', function(err) {
      // Make sure failed tests cause gulp to exit non-zero
      throw err;
    });
});
<commit_msg>Uglify when building for prod<commit_after>var gulp = require('gulp')
var gutil = require('gulp-util')
var concat = require('gulp-concat')
var connect = require('gulp-connect')
var iconfont = require('gulp-iconfont')
var iconfontCSS = require("gulp-iconfont-css")
var jshint = require('gulp-jshint')
var karma = require('gulp-karma')
var ngAnnotate = require('gulp-ng-annotate')
var plumber = require('gulp-plumber')
var rimraf = require('rimraf')
var sourcemaps = require('gulp-sourcemaps')
var sass = require('gulp-sass')
var streamqueue = require('streamqueue')
var templateCache = require('gulp-angular-templatecache')
var uglify = require('gulp-uglify')

//
// Variables
//
var srcDir = './src';
var distDir = './dist';
var vendorDir = './bower_components';
var isDebug = !gutil.env.prod;

var vendorFiles = [
  vendorDir + '/jquery/dist/jquery.js',
  vendorDir + '/lodash/dist/lodash.js',
  vendorDir + '/string/lib/string.js',
  vendorDir + '/angular/angular.js',
  vendorDir + '/angular-ui-router/release/angular-ui-router.js',
  vendorDir + '/angular-gravatar/build/md5.js',
  vendorDir + '/angular-gravatar/build/angular-gravatar.js',
  vendorDir + '/angular-hotkeys/build/hotkeys.js',
  vendorDir + '/ngInfiniteScroll/build/ng-infinite-scroll.js',
  vendorDir + '/angular-elastic/elastic.js',
  vendorDir + '/angular-scroll/angular-scroll.js',
];
var sourceFiles = [
  srcDir + '/app.js',
  srcDir + '/**/*.js',
  '!' + srcDir + '/public/**/*.js',
];
var testFiles = [
  'bower_components/angular-mocks/angular-mocks.js',
  'test/**/*.js'
];

//
// Default
//
gulp.task('default', ['build'], function() {
  gulp.start('watch');
});

//
// Clean
//
gulp.task('clean', function(cb) {
  rimraf(distDir, cb);
});

//
// Build
//
gulp.task('build', ['clean'], function() {
  gulp.start('scripts', 'styles', 'public', 'templates');
});

//
// Watch
//
gulp.task('watch', ['server'], function() {
  gulp.watch(srcDir + '/**/*.js', ['scripts']);

  gulp.watch(srcDir + '/**/*.scss', ['styles']);

  gulp.watch(srcDir + '/public/**/*', ['public']);

  gulp.watch(srcDir + '/views/**/*', ['templates']);

  gulp.src(vendorFiles.concat(sourceFiles).concat(testFiles))
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'watch'
    }));
});

//
// Server
//
gulp.task('server', function() {
  connect.server({
    root: distDir,
    port: 3000,
    livereload: false
  });
});

//
// Assets
//
gulp.task('public', function () {
  // Versionned assets
  gulp.src(srcDir + '/public/**/*')
    .pipe(gulp.dest(distDir))

  // Flags icons
  gulp.src(vendorDir + '/flag-icon-css/flags/**/*')
    .pipe(gulp.dest(distDir + '/images/flags'))
})

//
// Templates
//
gulp.task('templates', function () {
  gulp.src(srcDir + '/views/**/*')
    .pipe(gulp.dest(distDir + '/views'))
})

//
// Javascript
//
gulp.task('scripts', function () {
  var bootstrap = gulp.src(srcDir + '/bootstrap.js');

  var vendor = gulp.src(vendorFiles)

  var src = gulp.src(sourceFiles)
    .pipe(plumber())
    .pipe(ngAnnotate())

  // Combine into a single app script
  var queue = new streamqueue({ objectMode: true })
    .queue(bootstrap)
    .queue(vendor)
    .queue(src)

  // Inline templates in prod mode
  if (!isDebug) {
    var templates = gulp.src(srcDir + '/views/*.html')
      .pipe(templateCache('templates.js', {
        standalone: true,
        root: 'views',
      }))

    queue.queue(templates)
  }

  queue.done()
    .pipe(isDebug ? sourcemaps.init() : gutil.noop())
      .pipe(concat('app.js', {newLine: ';'}))
      .pipe(isDebug ? gutil.noop() : uglify())
    .pipe(isDebug ? sourcemaps.write() : gutil.noop())
    .pipe(gulp.dest(distDir))
})

//
// Stylesheet
//
gulp.task('styles', function () {
  gulp.src(srcDir + '/styles/app.scss')
    .pipe(plumber())
    .pipe(sass())
    .pipe(gulp.dest(distDir))
})

//
// Icons
//
gulp.task('icons', function(){
  gulp.src([srcDir + '/icons/*.svg'])
    .pipe(iconfontCSS({
      fontName : 'icons',
      // path: 'scss',
      path: srcDir + '/styles/templates/icons.scss',
      targetPath: '../../styles/icons.scss',
      fontPath: '../fonts/' // relative path
    }))
    .pipe(iconfont({
      fontName: 'icons',
      // fixedWidth: true,
      normalize: true
    }))
    .pipe(gulp.dest(srcDir + '/public/fonts'));
});

//
// Lint
//
gulp.task('lint', function() {
  return gulp.src(sourceFiles)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

//
// Test
//
gulp.task('test', function (done) {
  var files = [srcDir + '/bootstrap.js']
    .concat(vendorFiles)
    .concat(sourceFiles)
    .concat(testFiles)

  return gulp.src(files)
    .pipe(karma({
      configFile: __dirname + '/karma.conf.js',
      action: 'run'
    }))
    .on('error', function(err) {
      // Make sure failed tests cause gulp to exit non-zero
      throw err;
    });
});
<|endoftext|>


<commit_before>'use strict';

var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');

gulp.task('js', function () {
  // set up the browserify instance on a task basis
  var b = browserify({
    entries: './public/js/app.js',
    debug: true
  });

  return b.bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
        // Add transformation tasks to the pipeline here.
        .pipe(uglify())
        .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./public/js/'));
});
<commit_msg>Add auto JS building on source change<commit_after>'use strict';

var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');

var config = {
  js: ['src/**/*.js']
};

gulp.task('js', function () {
  // set up the browserify instance on a task basis
  var b = browserify({
    entries: './public/js/app.js',
    debug: true
  });

  return b.bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
        // Add transformation tasks to the pipeline here.
        .pipe(uglify())
        .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./public/js/'));
});

gulp.task('develop', function() {
  gulp.watch(config.js, ['js']);
});
<|endoftext|>


<commit_before>"use strict";

var gulp = require("gulp");
var plumber = require("gulp-plumber");
var purescript = require("gulp-purescript");
var jsvalidate = require("gulp-jsvalidate");
var run = require("gulp-run");

var paths = [
  "src/**/*.purs",
  "bower_components/purescript-*/src/**/*.purs",
  "test/**/*.purs"
];

gulp.task("make", function() {
  return gulp.src(paths)
    .pipe(plumber())
    .pipe(purescript.pscMake());
});

gulp.task("jsvalidate", ["make"], function () {
  return gulp.src("output/**/*.js")
    .pipe(plumber())
    .pipe(jsvalidate());
});

var docTasks = [];

var docTask = function(name) {
  var taskName = "docs-" + name.toLowerCase();
  gulp.task(taskName, function () {
    return gulp.src("src/" + name.replace(/\./g, "/") + ".purs")
      .pipe(plumber())
      .pipe(purescript.pscDocs())
      .pipe(gulp.dest("docs/" + name + ".md"));
  });
  docTasks.push(taskName);
};

["Data.Array", "Data.Array.ST", "Data.Array.Unsafe"].forEach(docTask);

gulp.task("docs", docTasks);

gulp.task("test", function() {
  return gulp.src(paths)
    .pipe(plumber())
    .pipe(purescript.psc({ main: "Test.Main" }))
    .pipe(run("node"));
});

gulp.task("default", ["jsvalidate", "docs"]);
<commit_msg>Test by default<commit_after>"use strict";

var gulp = require("gulp");
var plumber = require("gulp-plumber");
var purescript = require("gulp-purescript");
var jsvalidate = require("gulp-jsvalidate");
var run = require("gulp-run");

var paths = [
  "src/**/*.purs",
  "bower_components/purescript-*/src/**/*.purs",
  "test/**/*.purs"
];

gulp.task("make", function() {
  return gulp.src(paths)
    .pipe(plumber())
    .pipe(purescript.pscMake());
});

gulp.task("jsvalidate", ["make"], function () {
  return gulp.src("output/**/*.js")
    .pipe(plumber())
    .pipe(jsvalidate());
});

var docTasks = [];

var docTask = function(name) {
  var taskName = "docs-" + name.toLowerCase();
  gulp.task(taskName, function () {
    return gulp.src("src/" + name.replace(/\./g, "/") + ".purs")
      .pipe(plumber())
      .pipe(purescript.pscDocs())
      .pipe(gulp.dest("docs/" + name + ".md"));
  });
  docTasks.push(taskName);
};

["Data.Array", "Data.Array.ST", "Data.Array.Unsafe"].forEach(docTask);

gulp.task("docs", docTasks);

gulp.task("test", function() {
  return gulp.src(paths)
    .pipe(plumber())
    .pipe(purescript.psc({ main: "Test.Main" }))
    .pipe(run("node"));
});

gulp.task("default", ["jsvalidate", "docs", "test"]);
<|endoftext|>


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

var files = ['index.js', 'test/*.js', 'gulpfile.js'];

gulp.task('lint', function () {
    var eslint = require('gulp-eslint');
    return gulp.src(files)
    .pipe(eslint())
    .pipe(eslint.format());
});

gulp.task('test', function () {
    var mocha = require('gulp-mocha');
    return gulp.src('test/*.js', { read: false })
    .pipe(mocha());
});

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

gulp.task('watch', function () {
    gulp.watch(files, ['test']);
});
<commit_msg>remove empty space<commit_after>var gulp = require('gulp');
var files = ['index.js', 'test/*.js', 'gulpfile.js'];

gulp.task('lint', function () {
    var eslint = require('gulp-eslint');
    return gulp.src(files)
    .pipe(eslint())
    .pipe(eslint.format());
});

gulp.task('test', function () {
    var mocha = require('gulp-mocha');
    return gulp.src('test/*.js', { read: false })
    .pipe(mocha());
});

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

gulp.task('watch', function () {
    gulp.watch(files, ['test']);
});
<|endoftext|>


<commit_before>"use strict"
var gulp = require("gulp"),
    gutil = require("gulp-util"),

    streamify = require("gulp-streamify"),
    uglify = require("gulp-uglify"),
    rename = require("gulp-rename"),
    browserify = require("browserify"),
    source = require("vinyl-source-stream"),
    watchify = require("watchify"),
    fs = require("fs"),
    babelify = require("babelify"),
    babelPresetEs2015 = require('babel-preset-es2015'),
    envify = require("gulp-envify"),
    notifier = require("node-notifier"),
    merge = require("gulp-merge"),
    eslint = require("gulp-eslint"),
    postcss = require("gulp-postcss"),
    gulpIf = require('gulp-if'),

    packageJson = require("./package.json") || {};

// Read settings from package.json
var settings = packageJson.gulp //todo: validate and provide reasonable defaults

function onError(err) {
    gutil.log(gutil.colors.red(err.message))
}

var babelConfig = {
    global: true,
    presets: [babelPresetEs2015],
};

gulp.task("scripts_vendor", function(){
    var bundler = browserify("", {
        debug: false,
        cache: {},
        packageCache: {},
        fullPaths: true,
        extensions: [".js", ".jsx"],
        require: Object.keys(packageJson.dependencies)
    })

    bundler = bundler.transform(babelify, babelConfig)

    return bundler.bundle()
        .on("error",  onError)
        .pipe(source("vendor.js"))
        .on("error", onError)
        .pipe(streamify(envify({NODE_ENV: "production"})))
        .on("error", onError)
        .pipe(streamify(uglify()))
        .on("error", onError)
        .pipe(gulp.dest(settings.dest.scripts))
        .on("error", onError)
})

gulp.task("scripts", function(){
    function makeBundle(entryPoint) {
        var bundler = browserify(settings.src.scripts + "/" + entryPoint, {
            debug: false,
            cache: {},
            packageCache: {},
            fullPaths: true,
            extensions: [".js", ".jsx"]
        })

        // Register all dependencies as external (they are loaded via vendor bundle)
        Object.keys(packageJson.dependencies).forEach(function(dep){
            bundler.external(dep)
        })

        bundler = bundler.transform(babelify, babelConfig)

        return bundler.bundle()
            .on("error",  onError)
            .pipe(source(entryPoint))
            .on("error", onError)
            .pipe(streamify(envify({NODE_ENV: "production"})))
            .on("error", onError)
            .pipe(streamify(uglify()))
            .on("error", onError)
            .pipe(gulp.dest(settings.dest.scripts))
            .on("error", onError)
    }

    return merge(settings.entryPoints.map(makeBundle))
})

gulp.task("styles", function(){
    var files = settings.src.styles + "/**.css"

    var plugins = [
        require("postcss-nested"),
        require("postcss-simple-vars"),
        require("autoprefixer")({browsers: ["last 2 versions"]}),
    ];
    return gulp.src(files)
        .pipe(postcss(plugins))
        .pipe(gulp.dest(settings.dest.styles))
})

gulp.task('lint', function() {
    return gulp.src(settings.src.scripts + '/**').pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failOnError())
});

gulp.task('lint-n-fix', function() {
    function isFixed(file) {
        return file.eslint != null && file.eslint.fixed
    }
    return gulp.src('scripts/**.js').pipe(eslint({fix:true}))
        .pipe(eslint.format())
        .pipe(gulpIf(isFixed, gulp.dest('scripts')))
});

gulp.task("default", ["lint", "scripts_vendor", "scripts", "styles"])
<commit_msg>Remove hardcoded pathes<commit_after>"use strict"
var gulp = require("gulp"),
    gutil = require("gulp-util"),

    streamify = require("gulp-streamify"),
    uglify = require("gulp-uglify"),
    rename = require("gulp-rename"),
    browserify = require("browserify"),
    source = require("vinyl-source-stream"),
    watchify = require("watchify"),
    fs = require("fs"),
    babelify = require("babelify"),
    babelPresetEs2015 = require('babel-preset-es2015'),
    envify = require("gulp-envify"),
    notifier = require("node-notifier"),
    merge = require("gulp-merge"),
    eslint = require("gulp-eslint"),
    postcss = require("gulp-postcss"),
    gulpIf = require('gulp-if'),

    packageJson = require("./package.json") || {};

// Read settings from package.json
var settings = packageJson.gulp //todo: validate and provide reasonable defaults

function onError(err) {
    gutil.log(gutil.colors.red(err.message))
}

var babelConfig = {
    global: true,
    presets: [babelPresetEs2015],
};

gulp.task("scripts_vendor", function(){
    var bundler = browserify("", {
        debug: false,
        cache: {},
        packageCache: {},
        fullPaths: true,
        extensions: [".js", ".jsx"],
        require: Object.keys(packageJson.dependencies)
    })

    bundler = bundler.transform(babelify, babelConfig)

    return bundler.bundle()
        .on("error",  onError)
        .pipe(source("vendor.js"))
        .on("error", onError)
        .pipe(streamify(envify({NODE_ENV: "production"})))
        .on("error", onError)
        .pipe(streamify(uglify()))
        .on("error", onError)
        .pipe(gulp.dest(settings.dest.scripts))
        .on("error", onError)
})

gulp.task("scripts", function(){
    function makeBundle(entryPoint) {
        var bundler = browserify(settings.src.scripts + "/" + entryPoint, {
            debug: false,
            cache: {},
            packageCache: {},
            fullPaths: true,
            extensions: [".js", ".jsx"]
        })

        // Register all dependencies as external (they are loaded via vendor bundle)
        Object.keys(packageJson.dependencies).forEach(function(dep){
            bundler.external(dep)
        })

        bundler = bundler.transform(babelify, babelConfig)

        return bundler.bundle()
            .on("error",  onError)
            .pipe(source(entryPoint))
            .on("error", onError)
            .pipe(streamify(envify({NODE_ENV: "production"})))
            .on("error", onError)
            .pipe(streamify(uglify()))
            .on("error", onError)
            .pipe(gulp.dest(settings.dest.scripts))
            .on("error", onError)
    }

    return merge(settings.entryPoints.map(makeBundle))
})

gulp.task("styles", function(){
    var files = settings.src.styles + "/**.css"

    var plugins = [
        require("postcss-nested"),
        require("postcss-simple-vars"),
        require("autoprefixer")({browsers: ["last 2 versions"]}),
    ];
    return gulp.src(files)
        .pipe(postcss(plugins))
        .pipe(gulp.dest(settings.dest.styles))
})

gulp.task('lint', function() {
    return gulp.src(settings.src.scripts + '/**').pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failOnError())
});

gulp.task('lint-n-fix', function() {
    function isFixed(file) {
        return file.eslint != null && file.eslint.fixed
    }
    return gulp.src(settings.src.js + '/**.js').pipe(eslint({fix:true}))
        .pipe(eslint.format())
        .pipe(gulpIf(isFixed, gulp.dest(settings.src.js)))
});

gulp.task("default", ["lint", "scripts_vendor", "scripts", "styles"])
<|endoftext|>


<commit_before>"use strict";
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var zopfli = require('imagemin-zopfli');
var htmlmin = require('gulp-htmlmin');
var uglify = require('gulp-uglify');
var cleanCSS = require('gulp-clean-css');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var babel = require('babelify');

/* build-dev:
		* Build task for development.
*/
gulp.task('build-dev',
	[
		'copy-root',
		'copy-images',
		'copy-vendor',
		'copy-styles',
		'compile-source'
	],
	() => { console.log('Built for development.'); }
);

/* build-deploy:
		* Build task for deployment.
*/
gulp.task('build-deploy',
	[
		'produce-root',
		'produce-images',
		'copy-vendor',
		'produce-styles',
		'produce-source'
	],
	() => {
		console.log('Built for deployment.');
		return 0;
	}
);

/* copy-root:
		* Root copy task.
*/
gulp.task('copy-root', () => {
	gulp.src([
    'robots.txt',
    'README.md',
    'LICENSE',
		'index.html',
    'humans.txt',
		'CNAME',
		'.gitignore'
  ]).pipe(gulp.dest('build/'));
	console.log('Copied root files.');
	return 0;
});

/* produce-root:
		* Root production task.
*/
gulp.task('produce-root', () => {
	gulp.src([
    'robots.txt',
    'README.md',
    'LICENSE',
    'humans.txt',
		'CNAME',
		'.gitignore'
  ]).pipe(gulp.dest('build/'));
	gulp.src('index.html')
	.pipe(htmlmin({
		collapseWhitespace: true
	}))
	.pipe(gulp.dest('build/'));
	console.log('Produced root files.');
	return 0;
});

/* copy-images:
		* Root copy task.
*/
gulp.task('copy-images', () => {
  gulp.src('img/**/*.{png,jpg}')
  .pipe(gulp.dest('build/img/'));
	console.log('Images copied.');
	return 0;
});

/* produce-images:
		* Image optimization task.
*/
gulp.task('produce-images', () => {
	gulp.src('img/**/*.{png,jpg}')
	.pipe(imagemin({
		use: [zopfli()]
	}))
	.pipe(gulp.dest('build/img/'));
	console.log('Images compressed.');
	return 0;
});

/* copy-vendor:
		* Vendor copy task.
*/
gulp.task('copy-vendor', () => {
  gulp.src('js/vendor/**/*.js')
  .pipe(gulp.dest('build/js/vendor/'));
	console.log('Vendor js copied.');
	return 0;
});

/* copy-styles:
		* CSS copy task.
*/
gulp.task('copy-styles', () => {
  gulp.src('styles/**/*.css')
  .pipe(gulp.dest('build/styles/'));
	console.log('CSS copied.');
	return 0;
});

/* produce-styles:
		* CSS production task.
*/
gulp.task('produce-styles', () => {
  gulp.src('styles/**/*.css')
	.pipe(cleanCSS())
  .pipe(gulp.dest('build/styles/'));
	console.log('CSS composed.');
	return 0;
});

/* compile-source:
		* Source compilation task.
*/
gulp.task('compile-source', () => {
  browserify('js/main.js', {debug: true})
	.transform(babel.configure({
      	presets : ["es2015"]
    	})
		)
	.bundle()
	.pipe(source('bundle.js'))
	.pipe(gulp.dest('build/js'));
	gulp.src('js/plugins.js')
	.pipe(gulp.dest('build/js'));
	console.log('Source compiled.');
	return 0;
});

/* produce-source:
		* Source production task.
*/
gulp.task('produce-source', () => {
  browserify('js/main.js')
	.transform(babel.configure({
				presets : ["es2015"]
			})
		)
	.bundle()
	.pipe(source('bundle.js'))
	.pipe(buffer())
	.pipe(uglify())
	.pipe(gulp.dest('build/js'));
	gulp.src('js/plugins.js')
	.pipe(buffer())
	.pipe(gulp.dest('build/js'));
	console.log('Source composed.');
	return 0;
});

gulp.task('default', ['build-dev'], () => {
	//gulp.watch('!build/**', ['build-dev']);
	console.log('Watch nonfunctional. Blob goofy.');
	return 0;
});
<commit_msg>theres always one more thing<commit_after>"use strict";
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var zopfli = require('imagemin-zopfli');
var htmlmin = require('gulp-htmlmin');
var uglify = require('gulp-uglify');
var cleanCSS = require('gulp-clean-css');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var babel = require('babelify');

/* build-dev:
		* Build task for development.
*/
gulp.task('build-dev',
	[
		'copy-root',
		'copy-images',
		'copy-vendor',
		'copy-styles',
		'compile-source'
	],
	() => {
		console.log('Built for development.');
		return 0;
	}
);

/* build-deploy:
		* Build task for deployment.
*/
gulp.task('build-deploy',
	[
		'produce-root',
		'produce-images',
		'copy-vendor',
		'produce-styles',
		'produce-source'
	],
	() => {
		console.log('Built for deployment.');
		return 0;
	}
);

/* copy-root:
		* Root copy task.
*/
gulp.task('copy-root', () => {
	gulp.src([
    'robots.txt',
    'README.md',
    'LICENSE',
		'index.html',
    'humans.txt',
		'CNAME',
		'.gitignore'
  ]).pipe(gulp.dest('build/'));
	console.log('Copied root files.');
	return 0;
});

/* produce-root:
		* Root production task.
*/
gulp.task('produce-root', () => {
	gulp.src([
    'robots.txt',
    'README.md',
    'LICENSE',
    'humans.txt',
		'CNAME',
		'.gitignore'
  ]).pipe(gulp.dest('build/'));
	gulp.src('index.html')
	.pipe(htmlmin({
		collapseWhitespace: true
	}))
	.pipe(gulp.dest('build/'));
	console.log('Produced root files.');
	return 0;
});

/* copy-images:
		* Root copy task.
*/
gulp.task('copy-images', () => {
  gulp.src('img/**/*.{png,jpg}')
  .pipe(gulp.dest('build/img/'));
	console.log('Images copied.');
	return 0;
});

/* produce-images:
		* Image optimization task.
*/
gulp.task('produce-images', () => {
	gulp.src('img/**/*.{png,jpg}')
	.pipe(imagemin({
		use: [zopfli()]
	}))
	.pipe(gulp.dest('build/img/'));
	console.log('Images compressed.');
	return 0;
});

/* copy-vendor:
		* Vendor copy task.
*/
gulp.task('copy-vendor', () => {
  gulp.src('js/vendor/**/*.js')
  .pipe(gulp.dest('build/js/vendor/'));
	console.log('Vendor js copied.');
	return 0;
});

/* copy-styles:
		* CSS copy task.
*/
gulp.task('copy-styles', () => {
  gulp.src('styles/**/*.css')
  .pipe(gulp.dest('build/styles/'));
	console.log('CSS copied.');
	return 0;
});

/* produce-styles:
		* CSS production task.
*/
gulp.task('produce-styles', () => {
  gulp.src('styles/**/*.css')
	.pipe(cleanCSS())
  .pipe(gulp.dest('build/styles/'));
	console.log('CSS composed.');
	return 0;
});

/* compile-source:
		* Source compilation task.
*/
gulp.task('compile-source', () => {
  browserify('js/main.js', {debug: true})
	.transform(babel.configure({
      	presets : ["es2015"]
    	})
		)
	.bundle()
	.pipe(source('bundle.js'))
	.pipe(gulp.dest('build/js'));
	gulp.src('js/plugins.js')
	.pipe(gulp.dest('build/js'));
	console.log('Source compiled.');
	return 0;
});

/* produce-source:
		* Source production task.
*/
gulp.task('produce-source', () => {
  browserify('js/main.js')
	.transform(babel.configure({
				presets : ["es2015"]
			})
		)
	.bundle()
	.pipe(source('bundle.js'))
	.pipe(buffer())
	.pipe(uglify())
	.pipe(gulp.dest('build/js'));
	gulp.src('js/plugins.js')
	.pipe(buffer())
	.pipe(gulp.dest('build/js'));
	console.log('Source composed.');
	return 0;
});

gulp.task('default', ['build-dev'], () => {
	//gulp.watch('!build/**', ['build-dev']);
	console.log('Watch nonfunctional. Blob goofy.');
	return 0;
});
<|endoftext|>


<commit_before>var browserify = require('browserify'),
	shim = require('browserify-shim'),
	chalk = require('chalk'),
	del = require('del'),
	gulp = require('gulp'),
	bump = require('gulp-bump'),
	connect = require('gulp-connect'),
	deploy = require("gulp-gh-pages"),
	less = require('gulp-less'),
	rename = require('gulp-rename'),
	streamify = require('gulp-streamify'),
	uglify = require('gulp-uglify'),
	gutil = require('gulp-util'),
	merge = require('merge-stream'),
	reactify = require('reactify'),
	source = require('vinyl-source-stream'),
	watchify = require('watchify');

/**
 * Constants
 */

var SRC_PATH = 'src';
var DIST_PATH = 'dist';

var PACKAGE_FILE = 'MyComponent.js';
var PACKAGE_NAME = 'my-component';
var COMPONENT_NAME = 'MyComponent';

var DEPENDENCIES = ['react'];

var EXAMPLE_SRC_PATH = 'example/src';
var EXAMPLE_DIST_PATH = 'example/dist';

var EXAMPLE_APP = 'app.js';
var EXAMPLE_LESS = 'app.less';
var EXAMPLE_FILES = [
	'index.html',
	'standalone.html'
];

/**
 * Bundle helpers
 */

function doBundle(target, name, dest) {
	return target.bundle()
		.on('error', function(e) {
			gutil.log('Browserify Error', e);
		})
		.pipe(source(name))
		.pipe(gulp.dest(dest))
		.pipe(connect.reload());
}

function watchBundle(target, name, dest) {
	return watchify(target)
		.on('update', function (scriptIds) {
			scriptIds = scriptIds
				.filter(function(i) { return i.substr(0,2) !== './' })
				.map(function(i) { return chalk.blue(i.replace(__dirname, '')) });
			if (scriptIds.length > 1) {
				gutil.log(scriptIds.length + ' Scripts updated:\n* ' + scriptIds.join('\n* ') + '\nrebuilding...');
			} else {
				gutil.log(scriptIds[0] + ' updated, rebuilding...');
			}
			doBundle(target, name, dest);
		})
		.on('time', function (time) {
			gutil.log(chalk.green(name + ' built in ' + (Math.round(time / 10) / 100) + 's'));
		});
}

/**
 * Prepare task for examples
 */

gulp.task('prepare:examples', function(done) {
	del([EXAMPLE_DIST_PATH], done);
});

/**
 * Build example files
 */

function buildExampleFiles() {
	return gulp.src(EXAMPLE_FILES.map(function(i) { return EXAMPLE_SRC_PATH + '/' + i }))
		.pipe(gulp.dest(EXAMPLE_DIST_PATH))
		.pipe(connect.reload());
}

gulp.task('dev:build:example:files', buildExampleFiles);
gulp.task('build:example:files', ['prepare:examples'], buildExampleFiles);

/**
 * Build example css from less
 */

function buildExampleCSS() {
	return gulp.src(EXAMPLE_SRC_PATH + '/' + EXAMPLE_LESS)
		.pipe(less())
		.pipe(gulp.dest(EXAMPLE_DIST_PATH))
		.pipe(connect.reload());
}

gulp.task('dev:build:example:css', buildExampleCSS);
gulp.task('build:example:css', ['prepare:examples'], buildExampleCSS);

/**
 * Build example scripts
 *
 * Returns a gulp task with watchify when in development mode
 */

function buildExampleScripts(dev) {

	var dest = EXAMPLE_DIST_PATH;

	var opts = dev ? watchify.args : {};
	opts.debug = dev ? true : false;
	opts.hasExports = true;

	return function() {

		var common = browserify(opts),
			bundle = browserify(opts).require('./' + SRC_PATH + '/' + PACKAGE_FILE, { expose: PACKAGE_NAME }),
			example = browserify(opts).exclude(PACKAGE_NAME).add('./' + EXAMPLE_SRC_PATH + '/' + EXAMPLE_APP),
			standalone = browserify('./' + SRC_PATH + '/' + PACKAGE_FILE, { standalone: COMPONENT_NAME })
				.transform(reactify)
				.transform(shim);

		DEPENDENCIES.forEach(function(pkg) {
			common.require(pkg);
			bundle.exclude(pkg);
			example.exclude(pkg);
			standalone.exclude(pkg);
		});

		if (dev) {
			watchBundle(common, 'common.js', dest);
			watchBundle(bundle, 'bundle.js', dest);
			watchBundle(example, 'app.js', dest);
			watchBundle(standalone, 'standalone.js', dest);
		}

		return merge(
			doBundle(common, 'common.js', dest),
			doBundle(bundle, 'bundle.js', dest),
			doBundle(example, 'app.js', dest),
			doBundle(standalone, 'standalone.js', dest)
		);

	}

};

gulp.task('dev:build:example:scripts', buildExampleScripts(true));
gulp.task('build:example:scripts', ['prepare:examples'], buildExampleScripts());

/**
 * Build examples
 */

gulp.task('build:examples', [
	'build:example:files',
	'build:example:css',
	'build:example:scripts'
]);

gulp.task('watch:examples', [
	'dev:build:example:files',
	'dev:build:example:css',
	'dev:build:example:scripts'
], function() {
	gulp.watch(EXAMPLE_FILES.map(function(i) { return EXAMPLE_SRC_PATH + '/' + i }), ['dev:build:example:files']);
	gulp.watch([EXAMPLE_SRC_PATH + './' + EXAMPLE_LESS], ['dev:build:example:css']);
});

/**
 * Serve task for local development
 */

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

/**
 * Development task
 */

gulp.task('dev', [
	'dev:server',
	'watch:examples'
]);

/**
 * Build task
 */

gulp.task('prepare:dist', function(done) {
	del([DIST_PATH], done);
});

gulp.task('build:dist', ['prepare:dist'], function() {

	var standalone = browserify('./' + SRC_PATH + '/' + PACKAGE_FILE, {
			standalone: COMPONENT_NAME
		})
		.transform(reactify)
		.transform(shim);

	DEPENDENCIES.forEach(function(pkg) {
		standalone.exclude(pkg);
	});

	return standalone.bundle()
		.on('error', function(e) {
			gutil.log('Browserify Error', e);
		})
		.pipe(source(PACKAGE_NAME + '.js'))
		.pipe(gulp.dest(DIST_PATH))
		.pipe(rename(PACKAGE_NAME + '.min.js'))
		.pipe(streamify(uglify()))
		.pipe(gulp.dest(DIST_PATH));

});

gulp.task('build', [
	'build:dist',
	'build:examples'
]);

/**
 * Version bump tasks
 */

function getBumpTask(type) {
	return function() {
		return gulp.src(['./package.json', './bower.json'])
			.pipe(bump({ type: type }))
			.pipe(gulp.dest('./'));
	};
}

gulp.task('bump', getBumpTask('patch'));
gulp.task('bump:minor', getBumpTask('minor'));
gulp.task('bump:major', getBumpTask('major'));

/**
 * Git tag task
 * (version *must* be bumped first)
 */

gulp.task('publish:tag', function() {
	var pkg = require('./package.json');
	var v = 'v' + pkg.version;
	var message = 'Release ' + v;

	return gulp.src('./')
		.pipe(git.commit(message))
		.pipe(git.tag(v, message))
		.pipe(git.push('origin', 'master', '--tags'))
		.pipe(gulp.dest('./'));
});

/**
 * npm publish task
 * * (version *must* be bumped first)
 */

gulp.task('publish:npm', function(done) {
	require('child_process')
		.spawn('npm', ['publish'], { stdio: 'inherit' })
		.on('close', done);
});

/**
 * Deploy tasks
 */

gulp.task('publish:examples', ['build:examples'], function() {
	return gulp.src(EXAMPLE_DIST_PATH + '/**/*').pipe(deploy());
});

gulp.task('release', ['publish:tag', 'publish:npm', 'publish:examples']);
<commit_msg>Updating gulpfile<commit_after>var browserify = require('browserify'),
	shim = require('browserify-shim'),
	chalk = require('chalk'),
	del = require('del'),
	gulp = require('gulp'),
	bump = require('gulp-bump'),
	connect = require('gulp-connect'),
	deploy = require("gulp-gh-pages"),
	git = require("gulp-git"),
	less = require('gulp-less'),
	rename = require('gulp-rename'),
	streamify = require('gulp-streamify'),
	uglify = require('gulp-uglify'),
	gutil = require('gulp-util'),
	merge = require('merge-stream'),
	reactify = require('reactify'),
	source = require('vinyl-source-stream'),
	watchify = require('watchify');

/**
 * Constants
 */

var SRC_PATH = 'src';
var DIST_PATH = 'dist';

var PACKAGE_FILE = 'MyComponent.js';
var PACKAGE_NAME = 'my-component';
var COMPONENT_NAME = 'MyComponent';

var DEPENDENCIES = ['react'];

var EXAMPLE_SRC_PATH = 'example/src';
var EXAMPLE_DIST_PATH = 'example/dist';

var EXAMPLE_APP = 'app.js';
var EXAMPLE_LESS = 'app.less';
var EXAMPLE_FILES = [
	'index.html',
	'standalone.html'
];

/**
 * Bundle helpers
 */

function doBundle(target, name, dest) {
	return target.bundle()
		.on('error', function(e) {
			gutil.log('Browserify Error', e);
		})
		.pipe(source(name))
		.pipe(gulp.dest(dest))
		.pipe(connect.reload());
}

function watchBundle(target, name, dest) {
	return watchify(target)
		.on('update', function (scriptIds) {
			scriptIds = scriptIds
				.filter(function(i) { return i.substr(0,2) !== './' })
				.map(function(i) { return chalk.blue(i.replace(__dirname, '')) });
			if (scriptIds.length > 1) {
				gutil.log(scriptIds.length + ' Scripts updated:\n* ' + scriptIds.join('\n* ') + '\nrebuilding...');
			} else {
				gutil.log(scriptIds[0] + ' updated, rebuilding...');
			}
			doBundle(target, name, dest);
		})
		.on('time', function (time) {
			gutil.log(chalk.green(name + ' built in ' + (Math.round(time / 10) / 100) + 's'));
		});
}

/**
 * Prepare task for examples
 */

gulp.task('prepare:examples', function(done) {
	del([EXAMPLE_DIST_PATH], done);
});

/**
 * Build example files
 */

function buildExampleFiles() {
	return gulp.src(EXAMPLE_FILES.map(function(i) { return EXAMPLE_SRC_PATH + '/' + i }))
		.pipe(gulp.dest(EXAMPLE_DIST_PATH))
		.pipe(connect.reload());
}

gulp.task('dev:build:example:files', buildExampleFiles);
gulp.task('build:example:files', ['prepare:examples'], buildExampleFiles);

/**
 * Build example css from less
 */

function buildExampleCSS() {
	return gulp.src(EXAMPLE_SRC_PATH + '/' + EXAMPLE_LESS)
		.pipe(less())
		.pipe(gulp.dest(EXAMPLE_DIST_PATH))
		.pipe(connect.reload());
}

gulp.task('dev:build:example:css', buildExampleCSS);
gulp.task('build:example:css', ['prepare:examples'], buildExampleCSS);

/**
 * Build example scripts
 *
 * Returns a gulp task with watchify when in development mode
 */

function buildExampleScripts(dev) {

	var dest = EXAMPLE_DIST_PATH;

	var opts = dev ? watchify.args : {};
	opts.debug = dev ? true : false;
	opts.hasExports = true;

	return function() {

		var common = browserify(opts),
			bundle = browserify(opts).require('./' + SRC_PATH + '/' + PACKAGE_FILE, { expose: PACKAGE_NAME }),
			example = browserify(opts).exclude(PACKAGE_NAME).add('./' + EXAMPLE_SRC_PATH + '/' + EXAMPLE_APP),
			standalone = browserify('./' + SRC_PATH + '/' + PACKAGE_FILE, { standalone: COMPONENT_NAME })
				.transform(reactify)
				.transform(shim);

		DEPENDENCIES.forEach(function(pkg) {
			common.require(pkg);
			bundle.exclude(pkg);
			example.exclude(pkg);
			standalone.exclude(pkg);
		});

		if (dev) {
			watchBundle(common, 'common.js', dest);
			watchBundle(bundle, 'bundle.js', dest);
			watchBundle(example, 'app.js', dest);
			watchBundle(standalone, 'standalone.js', dest);
		}

		return merge(
			doBundle(common, 'common.js', dest),
			doBundle(bundle, 'bundle.js', dest),
			doBundle(example, 'app.js', dest),
			doBundle(standalone, 'standalone.js', dest)
		);

	}

};

gulp.task('dev:build:example:scripts', buildExampleScripts(true));
gulp.task('build:example:scripts', ['prepare:examples'], buildExampleScripts());

/**
 * Build examples
 */

gulp.task('build:examples', [
	'build:example:files',
	'build:example:css',
	'build:example:scripts'
]);

gulp.task('watch:examples', [
	'dev:build:example:files',
	'dev:build:example:css',
	'dev:build:example:scripts'
], function() {
	gulp.watch(EXAMPLE_FILES.map(function(i) { return EXAMPLE_SRC_PATH + '/' + i }), ['dev:build:example:files']);
	gulp.watch([EXAMPLE_SRC_PATH + './' + EXAMPLE_LESS], ['dev:build:example:css']);
});

/**
 * Serve task for local development
 */

gulp.task('dev:server', function() {
	connect.server({
		root: EXAMPLE_DIST_PATH,
		port: 8000,
		livereload: true
	});
});

/**
 * Development task
 */

gulp.task('dev', [
	'dev:server',
	'watch:examples'
]);

/**
 * Build task
 */

gulp.task('prepare:dist', function(done) {
	del([DIST_PATH], done);
});

gulp.task('build:dist', ['prepare:dist'], function() {

	var standalone = browserify('./' + SRC_PATH + '/' + PACKAGE_FILE, {
			standalone: COMPONENT_NAME
		})
		.transform(reactify)
		.transform(shim);

	DEPENDENCIES.forEach(function(pkg) {
		standalone.exclude(pkg);
	});

	return standalone.bundle()
		.on('error', function(e) {
			gutil.log('Browserify Error', e);
		})
		.pipe(source(PACKAGE_NAME + '.js'))
		.pipe(gulp.dest(DIST_PATH))
		.pipe(rename(PACKAGE_NAME + '.min.js'))
		.pipe(streamify(uglify()))
		.pipe(gulp.dest(DIST_PATH));

});

gulp.task('build', [
	'build:dist',
	'build:examples'
]);

/**
 * Version bump tasks
 */

function getBumpTask(type) {
	return function() {
		return gulp.src(['./package.json', './bower.json'])
			.pipe(bump({ type: type }))
			.pipe(gulp.dest('./'));
	};
}

gulp.task('bump', getBumpTask('patch'));
gulp.task('bump:minor', getBumpTask('minor'));
gulp.task('bump:major', getBumpTask('major'));

/**
 * Git tag task
 * (version *must* be bumped first)
 */

gulp.task('publish:tag', function(done) {
	var pkg = require('./package.json');
	var v = 'v' + pkg.version;
	var message = 'Release ' + v;

	git.tag(v, message, function (err) {
		if (err) throw err;
		git.push('origin', v, function (err) {
			if (err) throw err;
			done();
		});
	});
});

/**
 * npm publish task
 * * (version *must* be bumped first)
 */

gulp.task('publish:npm', function(done) {
	require('child_process')
		.spawn('npm', ['publish'], { stdio: 'inherit' })
		.on('close', done);
});

/**
 * Deploy tasks
 */

gulp.task('publish:examples', ['build:examples'], function() {
	return gulp.src(EXAMPLE_DIST_PATH + '/**/*').pipe(deploy());
});

gulp.task('release', ['publish:tag', 'publish:npm', 'publish:examples']);
<|endoftext|>